-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathradiographyDataNormalize_class.py
More file actions
373 lines (302 loc) · 15.6 KB
/
Copy pathradiographyDataNormalize_class.py
File metadata and controls
373 lines (302 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
from IPython.display import display
from ipyfilechooser import FileChooser
import h5py
import numpy as np
import matplotlib.pyplot as plt
from ipywidgets import IntSlider, Text, HBox, VBox, Output, Button, Layout, Label
from scipy import ndimage
from skimage.registration import phase_cross_correlation
from skimage.io import imsave
import imageio
class RadiographyDataNormalize:
def __init__(self, raw_data_path=None, raw_skip=[], flat_data_path=None, flat_skip=[], dark_data_path=None, dark_skip=[], dest_root_path=None):
self.raw_data_path = raw_data_path
self.flat_data_path = flat_data_path
self.dark_data_path = dark_data_path
self.dest_root_path = dest_root_path
self.normalized_data = None
self.normalized_proj = None
self.dark_field = None
self.flat_field = None
self.raw_skip = self.expand_excluded_indices(raw_skip)
self.flat_skip = self.expand_excluded_indices(flat_skip)
self.dark_skip = self.expand_excluded_indices(dark_skip)
self.SingleProjection = False
def expand_excluded_indices(self, exclusions):
excluded = set()
for item in exclusions:
if isinstance(item, tuple):
excluded.update(range(item[0], item[1] + 1))
else:
excluded.add(item)
return excluded
def load_raw_data_path(self, chooser):
if chooser.selected:
self.raw_data_path = chooser.selected
def load_flat_data_path(self, chooser):
if chooser.selected:
self.flat_data_path = chooser.selected
def load_dark_data_path(self, chooser):
if chooser.selected:
self.dark_data_path = chooser.selected
def load_dest_root_path(self, chooser):
if chooser.selected:
self.dest_root_path = chooser.selected
def InputOutput(self):
if self.raw_data_path is None:
dfile_chooser = FileChooser()
dfile_chooser.title = 'Raw Radiography Data:'
dfile_chooser.register_callback(self.load_raw_data_path)
display(dfile_chooser)
if self.flat_data_path is None:
ifile_chooser = FileChooser()
ifile_chooser.title = 'Flat Field Radiography Data:'
ifile_chooser.register_callback(self.load_flat_data_path)
display(ifile_chooser)
if self.dark_data_path is None:
ofile_chooser = FileChooser()
ofile_chooser.title = 'Dark Field Radiography Data):'
ofile_chooser.register_callback(self.load_dark_data_path)
display(ofile_chooser)
if self.dest_root_path is None:
destfile_chooser = FileChooser()
destfile_chooser.title = 'Destination Root File Path:'
destfile_chooser.register_callback(self.load_dest_root_path)
display(destfile_chooser)
def ReadData(self):
with h5py.File(self.raw_data_path, 'r') as f:
image_keys = f['/entry/instrument/imaging/image_key'][()]
indices = (image_keys == 0)
indx_values = np.arange(len(image_keys))
exclusion_mask = np.isin(indx_values, list(self.raw_skip))
valid_indices = np.where(indices & ~exclusion_mask)[0]
self.raw_data = f['/entry/imaging/data'][valid_indices]
self.normalized_data = self.raw_data
# Load flat data
with h5py.File(self.flat_data_path, 'r') as f:
image_keys = f['/entry/instrument/imaging/image_key'][()]
indices = (image_keys == 1)
indx_values = np.arange(len(image_keys))
exclusion_mask = np.isin(indx_values, list(self.flat_skip))
valid_indices = np.where(indices & ~exclusion_mask)[0]
self.flat_field = np.mean(f['/entry/imaging/data'][indices], axis=0, dtype=self.raw_data.dtype)
# Load dark data
with h5py.File(self.dark_data_path, 'r') as f:
image_keys = f['/entry/instrument/imaging/image_key'][()]
indices = (image_keys == 2)
indx_values = np.arange(len(image_keys))
exclusion_mask = np.isin(indx_values, list(self.dark_skip))
valid_indices = np.where(indices & ~exclusion_mask)[0]
self.dark_field = np.mean(f['/entry/imaging/data'][indices], axis=0, dtype=self.raw_data.dtype)
def save_snapshot(self, frame):
if self.SingleProjection == False:
plt.figure(figsize=(10, 8))
plt.imshow(self.normalized_data[frame], cmap='gray')
plt.axis('off')
plt.savefig(f'{self.dest_root_path}_{frame}.png', bbox_inches='tight', pad_inches=0)
plt.close()
else:
plt.figure(figsize=(10, 8))
plt.imshow(self.normalized_proj, cmap='gray')
plt.axis('off')
plt.savefig(f'{self.dest_root_path}_{frame}.png', bbox_inches='tight', pad_inches=0)
plt.close()
def on_save_button_clicked(self, b):
frame = self.slider.value
self.save_snapshot(frame)
def save_all_frames(self):
if self.SingleProjection == False:
frames = (self.normalized_data * 255).astype('uint8')
with imageio.get_writer(f'{self.dest_root_path}_all_frames.mp4', fps=30) as writer:
for frame in frames:
writer.append_data(frame)
with h5py.File(f'{self.dest_root_path}_all_frames.h5', 'w') as f:
f.create_dataset('normalized_frames', data=self.normalized_data)
def RadiographyExplorer(self):
if len(self.normalized_data) == 0:
print("None normalization applied!")
return
# Create a slider for frame selection
self.slider = IntSlider(min=0, max=len(self.raw_data)-1, layout=Layout(width='200px'), readout=False)
# Create a text input for frame number and initialize it with the slider's initial value
self.text = Text(value=str(self.slider.value), layout=Layout(width='100px'))
# Create an output widget for displaying plots
self.output = Output()
# Create a button to save the current snapshot
save_button = Button(description="Save Snapshot", layout=Layout(width='120px'))
save_button.on_click(self.on_save_button_clicked)
# Create a button to save all frames
save_all_button = Button(description="Save All Frames", layout=Layout(width='120px'))
save_all_button.on_click(lambda b: self.save_all_frames())
# Link slider and text input
def update_text(change):
self.text.value = str(change['new'])
self.update_plot(change['new'])
def update_slider(change):
self.slider.value = int(change['new'])
self.update_plot(int(change['new']))
self.slider.observe(update_text, names='value')
self.text.observe(update_slider, names='value')
# Display the title, slider, text input, save button, and save all button together
display(VBox([HBox([Label('Frame:'), self.slider, self.text, save_button, save_all_button]), self.output]))
# Initial plot
self.update_plot(self.slider.value)
def update_plot(self, frame):
with self.output:
self.output.clear_output() # Clear the previous output
fig, axes = plt.subplots(1, 2, figsize=(15, 8)) # Create two subplots side by side
# Display the normalized radiography image
if self.SingleProjection == False:
axes[0].imshow(self.normalized_data[frame], cmap='gray')
axes[0].set_title("Normalized Radiography")
axes[0].axis('off')
else:
axes[0].imshow(self.normalized_proj, cmap='gray')
axes[0].set_title("Normalized Radiography")
axes[0].axis('off')
# Display the original raw radiography data
axes[1].imshow(self.raw_data[frame], cmap='gray')
axes[1].set_title("Original Raw Radiography")
axes[1].axis('off')
plt.show() # Show the updated figure
def Normalize_FlatDark(self):
self.normalized_data = self.normalized_data.astype(np.float16)
self.dark_field = self.dark_field.astype(np.float16)
self.flat_field = self.flat_field.astype(np.float16)
self.normalized_data -= self.dark_field
self.normalized_data /= (self.flat_field - self.dark_field)
def Normalize_AlignROI(self, center_x=100, center_y=100, roi_size=200, upsample_factor=100, reference_index=0):
"""
Align radiographs using phase cross-correlation on a specified region of interest.
Args:
center_x, center_y: Center coordinates of the region of interest
roi_size: Size of the region of interest (square)
upsample_factor: Upsampling factor for sub-pixel registration
reference_index: Index of reference image
Returns:
Array of aligned radiographs
"""
num_images, height, width = self.normalized_data.shape
# Calculate ROI boundaries
half_size = roi_size // 2
x_min = max(0, center_x - half_size)
x_max = min(width, center_x + half_size)
y_min = max(0, center_y - half_size)
y_max = min(height, center_y + half_size)
# Get reference image and ROI
reference_full = self.normalized_data[reference_index]
reference_roi = reference_full[y_min:y_max, x_min:x_max]
# Initialize output array
aligned = np.zeros_like(self.normalized_data)
aligned[reference_index] = reference_full # No shift for reference
#print(f"Using image {reference_index} as reference")
# Visualize the ROI selection
fig, axes = plt.subplots(1, 2, figsize=(12, 6))
# Full image with ROI rectangle
axes[0].imshow(reference_full, cmap='gray')
axes[0].set_title('Reference Image')
from matplotlib.patches import Rectangle
rect = Rectangle((x_min, y_min), x_max-x_min, y_max-y_min,
edgecolor='r', facecolor='none', linewidth=2)
axes[0].add_patch(rect)
# ROI
axes[1].imshow(reference_roi, cmap='gray')
axes[1].set_title('ROI for Alignment')
plt.tight_layout()
plt.show()
# Track alignment statistics
all_shifts = []
error_count = 0
display_interval = max(1, num_images // 20) # Show progress every ~5%
for i in range(num_images):
if i == reference_index:
all_shifts.append((0, 0))
continue
# Get ROI for current image
current_roi = self.normalized_data[i][y_min:y_max, x_min:x_max]
try:
# Find shift using phase cross-correlation
shift, error, diffphase = phase_cross_correlation(
reference_roi, current_roi, upsample_factor=upsample_factor)
# Apply shift to full image
aligned[i] = ndimage.shift(self.normalized_data[i], shift)
all_shifts.append(shift)
# Print progress at intervals
if i % display_interval == 0 or i == num_images - 1:
percent_done = (i + 1) / num_images * 100
print(f" Shift for image {i}: [{shift[0]:.3f}, {shift[1]:.3f}]")
except Exception as e:
print(f" Error aligning image {i}: {e}")
aligned[i] = self.normalized_data[i] # Keep original if alignment fails
all_shifts.append((0, 0))
error_count += 1
# Calculate shift statistics
shifts_array = np.array(all_shifts)
x_shifts = shifts_array[:, 0]
y_shifts = shifts_array[:, 1]
# Print alignment summary
print("\nAlignment complete!")
print(f"Images with alignment errors: {error_count}/{num_images}")
print("\nShift statistics:")
print(f" X shift - Mean: {np.mean(x_shifts):.3f}, Min: {np.min(x_shifts):.3f}, Max: {np.max(x_shifts):.3f}")
print(f" Y shift - Mean: {np.mean(y_shifts):.3f}, Min: {np.min(y_shifts):.3f}, Max: {np.max(y_shifts):.3f}")
self.normalized_data = aligned
def Normalize_WeightedMeanAverage(self, reference_index=0):
"""
Apply Gaussian-weighted mean averaging with optional sharpening.
Args:
radiographs = self.normalized_data
reference_index: Index of reference image
apply_sharpening: Whether to apply unsharp masking for sharpening
sharpen_amount: Strength of sharpening (1.0 = standard, higher = stronger)
blur_radius: Radius of Gaussian blur for sharpening (higher = broader edges)
threshold: Minimum brightness difference for sharpening (reduces noise)
Returns:
Weighted average image with optional sharpening
"""
# Create Gaussian weights centered on reference image
num_images = len(self.normalized_data)
# Create weights with reference image having highest weight
indices = np.arange(num_images)
distances = np.abs(indices - reference_index)
# Convert to Gaussian weights
sigma = num_images / 5 # Control weight falloff
weights = np.exp(-distances**2 / (2 * sigma**2))
# Normalize weights
weights = weights / np.sum(weights)
# Apply weighted average
weighted_avg = np.zeros_like(self.normalized_data[0], dtype=np.float32)
for i in range(num_images):
weighted_avg += self.normalized_data[i] * weights[i]
# Show progress for large datasets
if i % 20 == 0 or i == num_images - 1:
progress = (i + 1) / num_images * 100
print(f" Processed {i+1}/{num_images} images ({progress:.1f}%)")
self.normalized_proj = weighted_avg
self.SingleProjection = True
def Normalize_Sharpening(self, sharpen_amount=1.0, blur_radius=1.0, threshold=0):
if self.SingleProjection == False:
if len(self.normalized_data) > 1:
print("This operation requires a single projection input!")
return
else:
self.normalized_proj = self.normalized_data[0]
self.SingleProjection = True
# Create blurred version of the image
blurred = ndimage.gaussian_filter(self.normalized_proj, sigma=blur_radius)
# Calculate unsharp mask (detail layer)
unsharp_mask = self.normalized_proj - blurred
# Apply threshold to reduce noise amplification
if threshold > 0:
mask = np.abs(unsharp_mask) > threshold
unsharp_mask = unsharp_mask * mask
# Add scaled mask to original image for sharpening
sharpened = self.normalized_proj + sharpen_amount * unsharp_mask
# Ensure values remain in valid range
sharpened = np.clip(sharpened, np.min(self.normalized_proj), np.max(self.normalized_proj))
# Calculate sharpening statistics
print("\nSharpening statistics:")
print(f" Original max value: {np.max(self.normalized_proj):.4f}")
print(f" Sharpened max value: {np.max(sharpened):.4f}")
print(f" Detail layer max magnitude: {np.max(np.abs(unsharp_mask)):.4f}")
self.normalized_proj = sharpened