0
# Measurement
1
2
Image measurement and analysis functions for extracting quantitative information from images. Includes region properties, geometric measurements, image moments, contour analysis, and statistical measures.
3
4
## Capabilities
5
6
### Region Properties and Analysis
7
8
Measure properties of labeled regions in images including geometric, intensity, and shape characteristics.
9
10
```python { .api }
11
def regionprops(label_image, intensity_image=None, cache=True, coordinates=None, separator='-', extra_properties=None):
12
"""
13
Measure properties of labeled image regions.
14
15
Parameters:
16
label_image : array_like
17
Labeled input image
18
intensity_image : array_like, optional
19
Intensity image for intensity measurements
20
cache : bool, optional
21
Cache computed properties
22
coordinates : str, optional
23
Coordinate system ('rc' or 'xy')
24
separator : str, optional
25
Separator for property names
26
extra_properties : iterable, optional
27
Additional property functions
28
29
Returns:
30
list
31
List of RegionProperties objects
32
"""
33
34
def regionprops_table(label_image, intensity_image=None, properties=('label', 'bbox'), cache=True, separator='-', extra_properties=None):
35
"""
36
Compute region properties and return as table.
37
38
Parameters:
39
label_image : array_like
40
Labeled input image
41
intensity_image : array_like, optional
42
Intensity image for intensity measurements
43
properties : tuple, optional
44
Properties to compute
45
cache : bool, optional
46
Cache computed properties
47
separator : str, optional
48
Separator for property names
49
extra_properties : iterable, optional
50
Additional property functions
51
52
Returns:
53
dict
54
Dictionary of property arrays
55
"""
56
57
def label(image, background=None, return_num=False, connectivity=None):
58
"""
59
Label connected components in binary image.
60
61
Parameters:
62
image : array_like
63
Binary input image
64
background : int, optional
65
Background value
66
return_num : bool, optional
67
Return number of labels
68
connectivity : int, optional
69
Pixel connectivity
70
71
Returns:
72
ndarray or tuple
73
Labeled image and optionally number of labels
74
"""
75
```
76
77
### Contour Analysis
78
79
Find and analyze image contours for shape analysis and boundary detection.
80
81
```python { .api }
82
def find_contours(image, level=0.5, fully_connected='low', positive_orientation='low', mask=None):
83
"""
84
Find iso-valued contours in a 2D array.
85
86
Parameters:
87
image : array_like
88
2D input array
89
level : float, optional
90
Value along which to find contours
91
fully_connected : str, optional
92
Connectivity mode ('low' or 'high')
93
positive_orientation : str, optional
94
Orientation mode ('low' or 'high')
95
mask : array_like, optional
96
Mask limiting contour detection
97
98
Returns:
99
list
100
List of contour coordinate arrays
101
"""
102
103
def approximate_polygon(coords, tolerance):
104
"""
105
Approximate polygon using Douglas-Peucker algorithm.
106
107
Parameters:
108
coords : array_like
109
Polygon coordinates
110
tolerance : float
111
Maximum distance from original polygon
112
113
Returns:
114
ndarray
115
Approximated polygon coordinates
116
"""
117
118
def subdivide_polygon(coords, degree=2, preserve_ends=False):
119
"""
120
Subdivide polygon by inserting new vertices.
121
122
Parameters:
123
coords : array_like
124
Polygon coordinates
125
degree : int, optional
126
Degree of B-spline used for subdivision
127
preserve_ends : bool, optional
128
Whether to preserve end points
129
130
Returns:
131
ndarray
132
Subdivided polygon coordinates
133
"""
134
```
135
136
### Geometric Measurements
137
138
Measure basic geometric properties of image regions and objects.
139
140
```python { .api }
141
def perimeter(image, neighbourhood=4):
142
"""
143
Calculate perimeter of objects in binary image.
144
145
Parameters:
146
image : array_like
147
Binary input image
148
neighbourhood : int, optional
149
Connectivity (4 or 8 for 2D)
150
151
Returns:
152
float
153
Perimeter length
154
"""
155
156
def perimeter_crofton(image, directions=4):
157
"""
158
Calculate perimeter using Crofton formula.
159
160
Parameters:
161
image : array_like
162
Binary input image
163
directions : int, optional
164
Number of directions for line integral
165
166
Returns:
167
float
168
Perimeter estimate
169
"""
170
171
def euler_number(image, connectivity=None):
172
"""
173
Calculate Euler number (topological invariant).
174
175
Parameters:
176
image : array_like
177
Binary input image
178
connectivity : int, optional
179
Pixel connectivity
180
181
Returns:
182
int
183
Euler number
184
"""
185
186
def centroid(image):
187
"""
188
Calculate centroid of binary image.
189
190
Parameters:
191
image : array_like
192
Binary input image
193
194
Returns:
195
tuple
196
Centroid coordinates
197
"""
198
```
199
200
### Image Moments
201
202
Compute various types of image moments for shape analysis and recognition.
203
204
```python { .api }
205
def moments(image, order=3):
206
"""
207
Calculate raw image moments.
208
209
Parameters:
210
image : array_like
211
Input image
212
order : int, optional
213
Maximum moment order
214
215
Returns:
216
ndarray
217
Raw moments array
218
"""
219
220
def moments_central(image, center=None, order=3):
221
"""
222
Calculate central moments.
223
224
Parameters:
225
image : array_like
226
Input image
227
center : tuple, optional
228
Center point for moments
229
order : int, optional
230
Maximum moment order
231
232
Returns:
233
ndarray
234
Central moments array
235
"""
236
237
def moments_normalized(mu, order=3):
238
"""
239
Calculate normalized central moments.
240
241
Parameters:
242
mu : array_like
243
Central moments array
244
order : int, optional
245
Maximum moment order
246
247
Returns:
248
ndarray
249
Normalized moments array
250
"""
251
252
def moments_hu(nu):
253
"""
254
Calculate Hu moment invariants.
255
256
Parameters:
257
nu : array_like
258
Normalized central moments
259
260
Returns:
261
ndarray
262
Hu moment invariants
263
"""
264
265
def moments_coords(coords, order=3):
266
"""
267
Calculate moments from coordinate list.
268
269
Parameters:
270
coords : array_like
271
Coordinate array
272
order : int, optional
273
Maximum moment order
274
275
Returns:
276
ndarray
277
Raw moments array
278
"""
279
280
def moments_coords_central(coords, center=None, order=3):
281
"""
282
Calculate central moments from coordinates.
283
284
Parameters:
285
coords : array_like
286
Coordinate array
287
center : tuple, optional
288
Center point for moments
289
order : int, optional
290
Maximum moment order
291
292
Returns:
293
ndarray
294
Central moments array
295
"""
296
```
297
298
### Inertia Analysis
299
300
Compute inertia tensors and principal axes for shape orientation analysis.
301
302
```python { .api }
303
def inertia_tensor(image, mu=None):
304
"""
305
Compute inertia tensor of image.
306
307
Parameters:
308
image : array_like
309
Input binary image
310
mu : array_like, optional
311
Central moments array
312
313
Returns:
314
ndarray
315
Inertia tensor matrix
316
"""
317
318
def inertia_tensor_eigvals(image, mu=None, T=None):
319
"""
320
Compute eigenvalues of inertia tensor.
321
322
Parameters:
323
image : array_like
324
Input binary image
325
mu : array_like, optional
326
Central moments array
327
T : array_like, optional
328
Inertia tensor matrix
329
330
Returns:
331
ndarray
332
Eigenvalues of inertia tensor
333
"""
334
```
335
336
### 3D Analysis
337
338
Analyze three-dimensional image data including surface extraction and volume measurements.
339
340
```python { .api }
341
def marching_cubes(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, mask=None, method='lewiner'):
342
"""
343
Generate mesh from 3D volume using marching cubes.
344
345
Parameters:
346
volume : array_like
347
Input 3D volume
348
level : float, optional
349
Contour value for surface extraction
350
spacing : tuple, optional
351
Voxel spacing
352
gradient_direction : str, optional
353
Direction of gradient ('descent' or 'ascent')
354
step_size : int, optional
355
Step size for sampling
356
allow_degenerate : bool, optional
357
Allow degenerate triangles
358
mask : array_like, optional
359
Mask limiting extraction region
360
method : str, optional
361
Algorithm variant ('lewiner' or 'classic')
362
363
Returns:
364
tuple
365
(vertices, faces, normals, values)
366
"""
367
368
def mesh_surface_area(verts, faces):
369
"""
370
Calculate surface area of triangular mesh.
371
372
Parameters:
373
verts : array_like
374
Vertex coordinates
375
faces : array_like
376
Face connectivity
377
378
Returns:
379
float
380
Total surface area
381
"""
382
```
383
384
### Profile Analysis
385
386
Extract intensity profiles along lines and curves for quantitative analysis.
387
388
```python { .api }
389
def profile_line(image, src, dst, linewidth=1, order=None, mode='constant', cval=0.0, reduce_func=None):
390
"""
391
Extract intensity profile along line.
392
393
Parameters:
394
image : array_like
395
Input image
396
src : tuple
397
Start point coordinates
398
dst : tuple
399
End point coordinates
400
linewidth : int, optional
401
Width of profile line
402
order : int, optional
403
Interpolation order
404
mode : str, optional
405
Boundary condition mode
406
cval : float, optional
407
Constant value for boundaries
408
reduce_func : callable, optional
409
Function to reduce values across line width
410
411
Returns:
412
ndarray
413
Intensity profile array
414
"""
415
```
416
417
### Geometric Model Fitting
418
419
Fit geometric models to point data using robust estimation methods.
420
421
```python { .api }
422
class LineModelND:
423
"""
424
N-dimensional line model for RANSAC fitting.
425
"""
426
427
def estimate(self, data):
428
"""Estimate line from data points."""
429
pass
430
431
def residuals(self, data):
432
"""Calculate residuals for data points."""
433
pass
434
435
class CircleModel:
436
"""
437
Circle model for RANSAC fitting.
438
"""
439
440
def estimate(self, data):
441
"""Estimate circle from data points."""
442
pass
443
444
def residuals(self, data):
445
"""Calculate residuals for data points."""
446
pass
447
448
class EllipseModel:
449
"""
450
Ellipse model for RANSAC fitting.
451
"""
452
453
def estimate(self, data):
454
"""Estimate ellipse from data points."""
455
pass
456
457
def residuals(self, data):
458
"""Calculate residuals for data points."""
459
pass
460
461
def ransac(data, model_class, min_samples, residual_threshold, is_data_valid=None, is_model_valid=None, max_trials=100, stop_sample_num=np.inf, stop_residuals_sum=0, stop_probability=0.99, random_state=None, initial_inliers=None):
462
"""
463
Fit model to data using RANSAC algorithm.
464
465
Parameters:
466
data : array_like
467
Input data points
468
model_class : class
469
Model class to fit
470
min_samples : int
471
Minimum samples needed to fit model
472
residual_threshold : float
473
Maximum residual for inliers
474
is_data_valid : callable, optional
475
Function to check data validity
476
is_model_valid : callable, optional
477
Function to check model validity
478
max_trials : int, optional
479
Maximum number of iterations
480
stop_sample_num : int, optional
481
Stop when this many inliers found
482
stop_residuals_sum : float, optional
483
Stop when residuals sum below this
484
stop_probability : float, optional
485
Stop probability
486
random_state : RandomState, optional
487
Random number generator
488
initial_inliers : array_like, optional
489
Initial inlier indices
490
491
Returns:
492
tuple
493
(model, inliers)
494
"""
495
```
496
497
## Usage Examples
498
499
### Region Analysis
500
501
```python
502
from skimage import data, measure, segmentation
503
import matplotlib.pyplot as plt
504
505
# Load and segment image
506
image = data.coins()
507
thresh = image > filters.threshold_otsu(image)
508
labeled = measure.label(thresh)
509
510
# Measure region properties
511
props = measure.regionprops(labeled, intensity_image=image)
512
513
# Display results
514
fig, ax = plt.subplots()
515
ax.imshow(image, cmap='gray')
516
517
for prop in props:
518
y0, x0 = prop.centroid
519
orientation = prop.orientation
520
x1 = x0 + np.cos(orientation) * 0.5 * prop.axis_minor_length
521
y1 = y0 - np.sin(orientation) * 0.5 * prop.axis_minor_length
522
x2 = x0 - np.sin(orientation) * 0.5 * prop.axis_major_length
523
y2 = y0 - np.cos(orientation) * 0.5 * prop.axis_major_length
524
525
ax.plot((x0, x1), (y0, y1), '-r', linewidth=2.5)
526
ax.plot((x0, x2), (y0, y2), '-b', linewidth=2.5)
527
ax.plot(x0, y0, '.g', markersize=15)
528
529
print(f"Found {len(props)} objects")
530
print(f"Mean area: {np.mean([p.area for p in props]):.1f}")
531
```
532
533
### Contour Detection
534
535
```python
536
from skimage import data, measure
537
import matplotlib.pyplot as plt
538
539
# Load image
540
image = data.camera()
541
542
# Find contours at different levels
543
contours_low = measure.find_contours(image, 0.3)
544
contours_high = measure.find_contours(image, 0.7)
545
546
# Display contours
547
fig, ax = plt.subplots()
548
ax.imshow(image, cmap='gray')
549
550
for contour in contours_low:
551
ax.plot(contour[:, 1], contour[:, 0], linewidth=2, color='red')
552
553
for contour in contours_high:
554
ax.plot(contour[:, 1], contour[:, 0], linewidth=2, color='blue')
555
556
print(f"Low level contours: {len(contours_low)}")
557
print(f"High level contours: {len(contours_high)}")
558
```
559
560
## Types
561
562
```python { .api }
563
from typing import List, Tuple, Optional, Union, Callable
564
from numpy.typing import NDArray
565
import numpy as np
566
567
# Region properties
568
RegionProperties = object
569
PropertiesTable = dict
570
571
# Contours and shapes
572
Contour = NDArray[np.floating]
573
ContourList = List[Contour]
574
Polygon = NDArray[np.floating]
575
576
# Moments and measurements
577
MomentArray = NDArray[np.floating]
578
InertiaTensor = NDArray[np.floating]
579
GeometricMeasurement = Union[float, int, Tuple[float, ...]]
580
581
# 3D analysis
582
MeshVertices = NDArray[np.floating]
583
MeshFaces = NDArray[np.integer]
584
MeshNormals = NDArray[np.floating]
585
MeshData = Tuple[MeshVertices, MeshFaces, MeshNormals, NDArray[np.floating]]
586
587
# Model fitting
588
GeometricModel = Union[LineModelND, CircleModel, EllipseModel]
589
RANSACResult = Tuple[GeometricModel, NDArray[np.bool_]]
590
```