0
# Data Evaluation
1
2
Analysis tools for extracting quantitative information from microscopy data including line profiles, ring diffraction analysis, stack alignment evaluation, and multi-correlation techniques for advanced image analysis.
3
4
## Capabilities
5
6
### Line Profile Analysis
7
8
Functions for extracting and analyzing intensity profiles along specified paths in images.
9
10
```python { .api }
11
def line_profile(image, start, end, linewidth=1, order=1):
12
"""
13
Extract line profile from image along specified path.
14
15
Parameters:
16
- image: numpy.ndarray, input 2D image
17
- start: tuple, starting coordinates (y, x)
18
- end: tuple, ending coordinates (y, x)
19
- linewidth: int, width of profile extraction region
20
- order: int, interpolation order
21
22
Returns:
23
dict: Dictionary containing:
24
- 'profile': numpy.ndarray, intensity values along line
25
- 'coordinates': numpy.ndarray, coordinate positions
26
- 'distance': numpy.ndarray, distance along line
27
"""
28
29
def _gen_line(start, end, num_points=None):
30
"""
31
Generate line coordinates between two points.
32
33
Parameters:
34
- start: tuple, starting coordinates (y, x)
35
- end: tuple, ending coordinates (y, x)
36
- num_points: int, number of points along line
37
38
Returns:
39
numpy.ndarray: Coordinate arrays for line points
40
"""
41
```
42
43
### Ring Diffraction Analysis
44
45
Comprehensive analysis tools for powder diffraction ring patterns with settings management and batch processing capabilities.
46
47
```python { .api }
48
def get_settings():
49
"""
50
Get current ring diffraction analysis settings.
51
52
Returns:
53
dict: Current analysis settings including:
54
- center: tuple, diffraction center coordinates
55
- radii_range: tuple, (min_radius, max_radius)
56
- angular_sectors: int, number of angular sectors
57
- background_method: str, background subtraction method
58
"""
59
60
def put_settings(settings_dict):
61
"""
62
Save ring diffraction analysis settings.
63
64
Parameters:
65
- settings_dict: dict, analysis settings to save
66
"""
67
68
def run_sglgroup(image, settings, group_name):
69
"""
70
Process single diffraction ring group.
71
72
Parameters:
73
- image: numpy.ndarray, diffraction pattern image
74
- settings: dict, analysis settings from get_settings()
75
- group_name: str, identifier for this analysis group
76
77
Returns:
78
dict: Analysis results including:
79
- radial_profile: numpy.ndarray, integrated radial intensity
80
- peak_positions: numpy.ndarray, detected ring positions
81
- d_spacings: numpy.ndarray, calculated d-spacings
82
- intensities: numpy.ndarray, integrated intensities
83
"""
84
85
def put_sglgroup(results, group_name, output_path):
86
"""
87
Save results from single group analysis.
88
89
Parameters:
90
- results: dict, analysis results from run_sglgroup()
91
- group_name: str, group identifier
92
- output_path: str, path for saving results
93
"""
94
95
def run_all(image_list, settings, output_path):
96
"""
97
Process all diffraction groups in batch.
98
99
Parameters:
100
- image_list: list, list of diffraction pattern images
101
- settings: dict, analysis settings
102
- output_path: str, path for saving batch results
103
104
Returns:
105
dict: Combined results from all groups
106
"""
107
```
108
109
### Stack Alignment Evaluation
110
111
Functions for evaluating and performing alignment of image stacks with quality metrics.
112
113
```python { .api }
114
def stack_align(image_stack, reference_frame=0, method='cross_correlation'):
115
"""
116
Align image stack with alignment quality evaluation.
117
118
Parameters:
119
- image_stack: numpy.ndarray, 3D array (frames, y, x)
120
- reference_frame: int, reference frame index
121
- method: str, alignment method ('cross_correlation', 'phase_correlation')
122
123
Returns:
124
dict: Dictionary containing:
125
- 'aligned_stack': numpy.ndarray, aligned image stack
126
- 'shifts': numpy.ndarray, calculated shifts for each frame
127
- 'correlation_scores': numpy.ndarray, alignment quality scores
128
- 'reference_frame': int, used reference frame
129
- 'alignment_method': str, used alignment method
130
"""
131
```
132
133
### Multi-Correlation Analysis
134
135
Advanced correlation techniques for template matching and feature tracking across image sequences.
136
137
```python { .api }
138
def multicorr(image_stack, template=None, correlation_method='normalized'):
139
"""
140
Multi-correlation analysis for template matching.
141
142
Parameters:
143
- image_stack: numpy.ndarray, 3D array (frames, y, x)
144
- template: numpy.ndarray, template image for matching
145
- correlation_method: str, correlation computation method
146
147
Returns:
148
dict: Dictionary containing:
149
- 'correlation_maps': numpy.ndarray, correlation maps for each frame
150
- 'peak_positions': numpy.ndarray, detected correlation peaks
151
- 'correlation_scores': numpy.ndarray, correlation strength values
152
- 'template_used': numpy.ndarray, template image used
153
- 'tracking_results': dict, feature tracking results
154
"""
155
```
156
157
## Usage Examples
158
159
### Line Profile Extraction
160
161
```python
162
import ncempy.eval as eval
163
import matplotlib.pyplot as plt
164
165
# Extract line profile across crystal boundary
166
image = microscopy_data['data']
167
start_point = (100, 50) # (y, x) coordinates
168
end_point = (100, 200)
169
170
profile_data = eval.line_profile(image, start_point, end_point, linewidth=3)
171
172
# Plot the profile
173
plt.figure(figsize=(10, 4))
174
plt.subplot(1, 2, 1)
175
plt.imshow(image, cmap='gray')
176
plt.plot([start_point[1], end_point[1]], [start_point[0], end_point[0]], 'r-', linewidth=2)
177
plt.title('Line Profile Location')
178
179
plt.subplot(1, 2, 2)
180
plt.plot(profile_data['distance'], profile_data['profile'])
181
plt.xlabel('Distance (pixels)')
182
plt.ylabel('Intensity')
183
plt.title('Intensity Profile')
184
plt.show()
185
```
186
187
### Ring Diffraction Analysis
188
189
```python
190
import ncempy.eval.ring_diff as ring_diff
191
192
# Set up analysis parameters
193
settings = {
194
'center': (256, 256),
195
'radii_range': (50, 200),
196
'angular_sectors': 36,
197
'background_method': 'polynomial'
198
}
199
200
# Save settings
201
ring_diff.put_settings(settings)
202
203
# Analyze single diffraction pattern
204
diffraction_image = load_diffraction_data()
205
results = ring_diff.run_sglgroup(diffraction_image, settings, 'sample_001')
206
207
# Display results
208
print(f"Detected {len(results['peak_positions'])} diffraction rings")
209
print(f"D-spacings: {results['d_spacings']}")
210
211
# Save results
212
ring_diff.put_sglgroup(results, 'sample_001', './analysis_results/')
213
```
214
215
### Stack Alignment with Quality Assessment
216
217
```python
218
import ncempy.eval as eval
219
import numpy as np
220
import matplotlib.pyplot as plt
221
222
# Load image stack (time series or tilt series)
223
stack = load_image_stack() # shape: (frames, height, width)
224
225
# Perform alignment with evaluation
226
alignment_results = eval.stack_align(stack, reference_frame=0,
227
method='cross_correlation')
228
229
aligned_stack = alignment_results['aligned_stack']
230
shifts = alignment_results['shifts']
231
scores = alignment_results['correlation_scores']
232
233
# Plot alignment results
234
plt.figure(figsize=(12, 4))
235
236
plt.subplot(1, 3, 1)
237
plt.imshow(stack[0], cmap='gray')
238
plt.title('Original Frame 0')
239
240
plt.subplot(1, 3, 2)
241
plt.imshow(aligned_stack[0], cmap='gray')
242
plt.title('Aligned Frame 0')
243
244
plt.subplot(1, 3, 3)
245
plt.plot(scores)
246
plt.xlabel('Frame Number')
247
plt.ylabel('Correlation Score')
248
plt.title('Alignment Quality')
249
plt.show()
250
251
# Display shift information
252
print(f"Maximum shift: {np.max(np.abs(shifts))} pixels")
253
print(f"Average alignment score: {np.mean(scores):.3f}")
254
```
255
256
### Multi-Correlation Feature Tracking
257
258
```python
259
import ncempy.eval as eval
260
import matplotlib.pyplot as plt
261
262
# Load image sequence
263
image_sequence = load_time_series()
264
265
# Define template from first frame
266
template_region = image_sequence[0, 100:150, 100:150] # 50x50 template
267
268
# Perform multi-correlation tracking
269
tracking_results = eval.multicorr(image_sequence, template=template_region)
270
271
correlation_maps = tracking_results['correlation_maps']
272
peak_positions = tracking_results['peak_positions']
273
scores = tracking_results['correlation_scores']
274
275
# Plot tracking results
276
plt.figure(figsize=(15, 5))
277
278
# Show template
279
plt.subplot(1, 3, 1)
280
plt.imshow(template_region, cmap='gray')
281
plt.title('Template')
282
283
# Show correlation map for frame 10
284
plt.subplot(1, 3, 2)
285
plt.imshow(correlation_maps[10], cmap='hot')
286
plt.title('Correlation Map (Frame 10)')
287
288
# Plot tracking trajectory
289
plt.subplot(1, 3, 3)
290
plt.plot(peak_positions[:, 1], peak_positions[:, 0], 'b-o')
291
plt.xlabel('X Position')
292
plt.ylabel('Y Position')
293
plt.title('Feature Trajectory')
294
plt.axis('equal')
295
plt.show()
296
297
print(f"Tracked feature across {len(peak_positions)} frames")
298
print(f"Average correlation score: {np.mean(scores):.3f}")
299
```
300
301
### Batch Processing Multiple Samples
302
303
```python
304
import ncempy.eval.ring_diff as ring_diff
305
import glob
306
307
# Set up analysis settings
308
settings = ring_diff.get_settings()
309
settings.update({
310
'center': (256, 256),
311
'radii_range': (30, 250),
312
'angular_sectors': 72
313
})
314
ring_diff.put_settings(settings)
315
316
# Process multiple diffraction patterns
317
diffraction_files = glob.glob('diffraction_data/*.dm4')
318
image_list = [ncempy.read(f)['data'] for f in diffraction_files]
319
320
# Run batch analysis
321
batch_results = ring_diff.run_all(image_list, settings, './batch_results/')
322
323
# Analyze batch statistics
324
all_d_spacings = []
325
for result in batch_results.values():
326
all_d_spacings.extend(result['d_spacings'])
327
328
print(f"Processed {len(image_list)} diffraction patterns")
329
print(f"Total rings detected: {len(all_d_spacings)}")
330
print(f"D-spacing range: {min(all_d_spacings):.3f} - {max(all_d_spacings):.3f} Å")
331
```
332
333
### Combined Analysis Workflow
334
335
```python
336
import ncempy.eval as eval
337
import ncempy.algo as algo
338
import ncempy.viz as viz
339
340
# Load and preprocess data
341
raw_data = ncempy.read('sample.dm4')['data']
342
343
# 1. Align if it's a stack
344
if raw_data.ndim == 3:
345
alignment_results = eval.stack_align(raw_data)
346
processed_data = alignment_results['aligned_stack']
347
print(f"Stack aligned with average score: {np.mean(alignment_results['correlation_scores']):.3f}")
348
else:
349
processed_data = raw_data
350
351
# 2. Extract line profiles for analysis
352
center_line = eval.line_profile(processed_data, (0, 128), (255, 128))
353
cross_line = eval.line_profile(processed_data, (128, 0), (128, 255))
354
355
# 3. Visualize results
356
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
357
358
# Original data
359
axes[0,0].imshow(processed_data, cmap='gray')
360
axes[0,0].set_title('Processed Data')
361
362
# Line profile locations
363
viz.plot_points(processed_data, [(128, 128)], ax=axes[0,1])
364
axes[0,1].plot([0, 255], [128, 128], 'r-', alpha=0.7)
365
axes[0,1].plot([128, 128], [0, 255], 'b-', alpha=0.7)
366
axes[0,1].set_title('Line Profile Locations')
367
368
# Profile plots
369
axes[1,0].plot(center_line['distance'], center_line['profile'], 'r-')
370
axes[1,0].set_title('Horizontal Profile')
371
axes[1,0].set_xlabel('Distance (pixels)')
372
axes[1,0].set_ylabel('Intensity')
373
374
axes[1,1].plot(cross_line['distance'], cross_line['profile'], 'b-')
375
axes[1,1].set_title('Vertical Profile')
376
axes[1,1].set_xlabel('Distance (pixels)')
377
axes[1,1].set_ylabel('Intensity')
378
379
plt.tight_layout()
380
plt.show()
381
```