-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
_regionprops.py
1423 lines (1236 loc) · 49.9 KB
/
_regionprops.py
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
from functools import wraps
from math import atan2
from math import pi as PI
from math import sqrt
from warnings import warn
import numpy as np
from scipy import ndimage as ndi
from scipy.spatial.distance import pdist
from . import _moments
from ._find_contours import find_contours
from ._marching_cubes_lewiner import marching_cubes
from ._regionprops_utils import (
euler_number,
perimeter,
perimeter_crofton,
_normalize_spacing,
)
__all__ = ['regionprops', 'euler_number', 'perimeter', 'perimeter_crofton']
# All values in this PROPS dict correspond to current scikit-image property
# names. The keys in this PROPS dict correspond to older names used in prior
# releases. For backwards compatibility, these older names will continue to
# work, but will not be documented.
PROPS = {
'Area': 'area',
'BoundingBox': 'bbox',
'BoundingBoxArea': 'area_bbox',
'bbox_area': 'area_bbox',
'CentralMoments': 'moments_central',
'Centroid': 'centroid',
'ConvexArea': 'area_convex',
'convex_area': 'area_convex',
# 'ConvexHull',
'ConvexImage': 'image_convex',
'convex_image': 'image_convex',
'Coordinates': 'coords',
'Eccentricity': 'eccentricity',
'EquivDiameter': 'equivalent_diameter_area',
'equivalent_diameter': 'equivalent_diameter_area',
'EulerNumber': 'euler_number',
'Extent': 'extent',
# 'Extrema',
'FeretDiameter': 'feret_diameter_max',
'FeretDiameterMax': 'feret_diameter_max',
'FilledArea': 'area_filled',
'filled_area': 'area_filled',
'FilledImage': 'image_filled',
'filled_image': 'image_filled',
'HuMoments': 'moments_hu',
'Image': 'image',
'InertiaTensor': 'inertia_tensor',
'InertiaTensorEigvals': 'inertia_tensor_eigvals',
'IntensityImage': 'image_intensity',
'intensity_image': 'image_intensity',
'Label': 'label',
'LocalCentroid': 'centroid_local',
'local_centroid': 'centroid_local',
'MajorAxisLength': 'axis_major_length',
'major_axis_length': 'axis_major_length',
'MaxIntensity': 'intensity_max',
'max_intensity': 'intensity_max',
'MeanIntensity': 'intensity_mean',
'mean_intensity': 'intensity_mean',
'MinIntensity': 'intensity_min',
'min_intensity': 'intensity_min',
'std_intensity': 'intensity_std',
'MinorAxisLength': 'axis_minor_length',
'minor_axis_length': 'axis_minor_length',
'Moments': 'moments',
'NormalizedMoments': 'moments_normalized',
'Orientation': 'orientation',
'Perimeter': 'perimeter',
'CroftonPerimeter': 'perimeter_crofton',
# 'PixelIdxList',
# 'PixelList',
'Slice': 'slice',
'Solidity': 'solidity',
# 'SubarrayIdx'
'WeightedCentralMoments': 'moments_weighted_central',
'weighted_moments_central': 'moments_weighted_central',
'WeightedCentroid': 'centroid_weighted',
'weighted_centroid': 'centroid_weighted',
'WeightedHuMoments': 'moments_weighted_hu',
'weighted_moments_hu': 'moments_weighted_hu',
'WeightedLocalCentroid': 'centroid_weighted_local',
'weighted_local_centroid': 'centroid_weighted_local',
'WeightedMoments': 'moments_weighted',
'weighted_moments': 'moments_weighted',
'WeightedNormalizedMoments': 'moments_weighted_normalized',
'weighted_moments_normalized': 'moments_weighted_normalized',
}
COL_DTYPES = {
'area': float,
'area_bbox': float,
'area_convex': float,
'area_filled': float,
'axis_major_length': float,
'axis_minor_length': float,
'bbox': int,
'centroid': float,
'centroid_local': float,
'centroid_weighted': float,
'centroid_weighted_local': float,
'coords': object,
'coords_scaled': object,
'eccentricity': float,
'equivalent_diameter_area': float,
'euler_number': int,
'extent': float,
'feret_diameter_max': float,
'image': object,
'image_convex': object,
'image_filled': object,
'image_intensity': object,
'inertia_tensor': float,
'inertia_tensor_eigvals': float,
'intensity_max': float,
'intensity_mean': float,
'intensity_min': float,
'intensity_std': float,
'label': int,
'moments': float,
'moments_central': float,
'moments_hu': float,
'moments_normalized': float,
'moments_weighted': float,
'moments_weighted_central': float,
'moments_weighted_hu': float,
'moments_weighted_normalized': float,
'num_pixels': int,
'orientation': float,
'perimeter': float,
'perimeter_crofton': float,
'slice': object,
'solidity': float,
}
OBJECT_COLUMNS = [col for col, dtype in COL_DTYPES.items() if dtype == object]
PROP_VALS = set(PROPS.values())
_require_intensity_image = (
'image_intensity',
'intensity_max',
'intensity_mean',
'intensity_min',
'intensity_std',
'moments_weighted',
'moments_weighted_central',
'centroid_weighted',
'centroid_weighted_local',
'moments_weighted_hu',
'moments_weighted_normalized',
)
def _infer_number_of_required_args(func):
"""Infer the number of required arguments for a function
Parameters
----------
func : callable
The function that is being inspected.
Returns
-------
n_args : int
The number of required arguments of func.
"""
argspec = inspect.getfullargspec(func)
n_args = len(argspec.args)
if argspec.defaults is not None:
n_args -= len(argspec.defaults)
return n_args
def _infer_regionprop_dtype(func, *, intensity, ndim):
"""Infer the dtype of a region property calculated by func.
If a region property function always returns the same shape and type of
output regardless of input size, then the dtype is the dtype of the
returned array. Otherwise, the property has object dtype.
Parameters
----------
func : callable
Function to be tested. The signature should be array[bool] -> Any if
intensity is False, or *(array[bool], array[float]) -> Any otherwise.
intensity : bool
Whether the regionprop is calculated on an intensity image.
ndim : int
The number of dimensions for which to check func.
Returns
-------
dtype : NumPy data type
The data type of the returned property.
"""
mask_1 = np.ones((1,) * ndim, dtype=bool)
mask_1 = np.pad(mask_1, (0, 1), constant_values=False)
mask_2 = np.ones((2,) * ndim, dtype=bool)
mask_2 = np.pad(mask_2, (1, 0), constant_values=False)
propmasks = [mask_1, mask_2]
rng = np.random.default_rng()
if intensity and _infer_number_of_required_args(func) == 2:
def _func(mask):
return func(mask, rng.random(mask.shape))
else:
_func = func
props1, props2 = map(_func, propmasks)
if (
np.isscalar(props1)
and np.isscalar(props2)
or np.array(props1).shape == np.array(props2).shape
):
dtype = np.array(props1).dtype.type
else:
dtype = np.object_
return dtype
def _cached(f):
@wraps(f)
def wrapper(obj):
cache = obj._cache
prop = f.__name__
if not ((prop in cache) and obj._cache_active):
cache[prop] = f(obj)
return cache[prop]
return wrapper
def only2d(method):
@wraps(method)
def func2d(self, *args, **kwargs):
if self._ndim > 2:
raise NotImplementedError(
f"Property {method.__name__} is not implemented for 3D images"
)
return method(self, *args, **kwargs)
return func2d
def _inertia_eigvals_to_axes_lengths_3D(inertia_tensor_eigvals):
"""Compute ellipsoid axis lengths from inertia tensor eigenvalues.
Parameters
---------
inertia_tensor_eigvals : sequence of float
A sequence of 3 floating point eigenvalues, sorted in descending order.
Returns
-------
axis_lengths : list of float
The ellipsoid axis lengths sorted in descending order.
Notes
-----
Let a >= b >= c be the ellipsoid semi-axes and s1 >= s2 >= s3 be the
inertia tensor eigenvalues.
The inertia tensor eigenvalues are given for a solid ellipsoid in [1]_.
s1 = 1 / 5 * (a**2 + b**2)
s2 = 1 / 5 * (a**2 + c**2)
s3 = 1 / 5 * (b**2 + c**2)
Rearranging to solve for a, b, c in terms of s1, s2, s3 gives
a = math.sqrt(5 / 2 * ( s1 + s2 - s3))
b = math.sqrt(5 / 2 * ( s1 - s2 + s3))
c = math.sqrt(5 / 2 * (-s1 + s2 + s3))
We can then simply replace sqrt(5/2) by sqrt(10) to get the full axes
lengths rather than the semi-axes lengths.
References
----------
..[1] https://en.wikipedia.org/wiki/List_of_moments_of_inertia#List_of_3D_inertia_tensors # noqa
"""
axis_lengths = []
for ax in range(2, -1, -1):
w = sum(v * -1 if i == ax else v for i, v in enumerate(inertia_tensor_eigvals))
axis_lengths.append(sqrt(10 * w))
return axis_lengths
class RegionProperties:
"""Please refer to `skimage.measure.regionprops` for more information
on the available region properties.
"""
def __init__(
self,
slice,
label,
label_image,
intensity_image,
cache_active,
*,
extra_properties=None,
spacing=None,
offset=None,
):
if intensity_image is not None:
ndim = label_image.ndim
if not (
intensity_image.shape[:ndim] == label_image.shape
and intensity_image.ndim in [ndim, ndim + 1]
):
raise ValueError(
'Label and intensity image shapes must match,'
' except for channel (last) axis.'
)
multichannel = label_image.shape < intensity_image.shape
else:
multichannel = False
self.label = label
if offset is None:
offset = np.zeros((label_image.ndim,), dtype=int)
self._offset = np.array(offset)
self._slice = slice
self.slice = slice
self._label_image = label_image
self._intensity_image = intensity_image
self._cache_active = cache_active
self._cache = {}
self._ndim = label_image.ndim
self._multichannel = multichannel
self._spatial_axes = tuple(range(self._ndim))
if spacing is None:
spacing = np.full(self._ndim, 1.0)
self._spacing = _normalize_spacing(spacing, self._ndim)
self._pixel_area = np.prod(self._spacing)
self._extra_properties = {}
if extra_properties is not None:
for func in extra_properties:
name = func.__name__
if hasattr(self, name):
msg = (
f"Extra property '{name}' is shadowed by existing "
f"property and will be inaccessible. Consider "
f"renaming it."
)
warn(msg)
self._extra_properties = {func.__name__: func for func in extra_properties}
def __getattr__(self, attr):
if self._intensity_image is None and attr in _require_intensity_image:
raise AttributeError(
f"Attribute '{attr}' unavailable when `intensity_image` "
f"has not been specified."
)
if attr in self._extra_properties:
func = self._extra_properties[attr]
n_args = _infer_number_of_required_args(func)
# determine whether func requires intensity image
if n_args == 2:
if self._intensity_image is not None:
if self._multichannel:
multichannel_list = [
func(self.image, self.image_intensity[..., i])
for i in range(self.image_intensity.shape[-1])
]
return np.stack(multichannel_list, axis=-1)
else:
return func(self.image, self.image_intensity)
else:
raise AttributeError(
f'intensity image required to calculate {attr}'
)
elif n_args == 1:
return func(self.image)
else:
raise AttributeError(
f'Custom regionprop function\'s number of arguments must '
f'be 1 or 2, but {attr} takes {n_args} arguments.'
)
elif attr in PROPS and attr.lower() == attr:
if (
self._intensity_image is None
and PROPS[attr] in _require_intensity_image
):
raise AttributeError(
f"Attribute '{attr}' unavailable when `intensity_image` "
f"has not been specified."
)
# retrieve deprecated property (excluding old CamelCase ones)
return getattr(self, PROPS[attr])
else:
raise AttributeError(f"'{type(self)}' object has no attribute '{attr}'")
def __setattr__(self, name, value):
if name in PROPS:
super().__setattr__(PROPS[name], value)
else:
super().__setattr__(name, value)
@property
@_cached
def num_pixels(self):
return np.sum(self.image)
@property
@_cached
def area(self):
return np.sum(self.image) * self._pixel_area
@property
def bbox(self):
"""
Returns
-------
A tuple of the bounding box's start coordinates for each dimension,
followed by the end coordinates for each dimension
"""
return tuple(
[self.slice[i].start for i in range(self._ndim)]
+ [self.slice[i].stop for i in range(self._ndim)]
)
@property
def area_bbox(self):
return self.image.size * self._pixel_area
@property
def centroid(self):
return tuple(self.coords_scaled.mean(axis=0))
@property
@_cached
def area_convex(self):
return np.sum(self.image_convex) * self._pixel_area
@property
@_cached
def image_convex(self):
from ..morphology.convex_hull import convex_hull_image
return convex_hull_image(self.image)
@property
def coords_scaled(self):
indices = np.argwhere(self.image)
object_offset = np.array([self.slice[i].start for i in range(self._ndim)])
return (object_offset + indices) * self._spacing + self._offset
@property
def coords(self):
indices = np.argwhere(self.image)
object_offset = np.array([self.slice[i].start for i in range(self._ndim)])
return object_offset + indices + self._offset
@property
@only2d
def eccentricity(self):
l1, l2 = self.inertia_tensor_eigvals
if l1 == 0:
return 0
return sqrt(1 - l2 / l1)
@property
def equivalent_diameter_area(self):
return (2 * self._ndim * self.area / PI) ** (1 / self._ndim)
@property
def euler_number(self):
if self._ndim not in [2, 3]:
raise NotImplementedError(
'Euler number is implemented for ' '2D or 3D images only'
)
return euler_number(self.image, self._ndim)
@property
def extent(self):
return self.area / self.area_bbox
@property
def feret_diameter_max(self):
identity_convex_hull = np.pad(
self.image_convex, 2, mode='constant', constant_values=0
)
if self._ndim == 2:
coordinates = np.vstack(
find_contours(identity_convex_hull, 0.5, fully_connected='high')
)
elif self._ndim == 3:
coordinates, _, _, _ = marching_cubes(identity_convex_hull, level=0.5)
distances = pdist(coordinates * self._spacing, 'sqeuclidean')
return sqrt(np.max(distances))
@property
def area_filled(self):
return np.sum(self.image_filled) * self._pixel_area
@property
@_cached
def image_filled(self):
structure = np.ones((3,) * self._ndim)
return ndi.binary_fill_holes(self.image, structure)
@property
@_cached
def image(self):
return self._label_image[self.slice] == self.label
@property
@_cached
def inertia_tensor(self):
mu = self.moments_central
return _moments.inertia_tensor(self.image, mu, spacing=self._spacing)
@property
@_cached
def inertia_tensor_eigvals(self):
return _moments.inertia_tensor_eigvals(self.image, T=self.inertia_tensor)
@property
@_cached
def image_intensity(self):
if self._intensity_image is None:
raise AttributeError('No intensity image specified.')
image = (
self.image
if not self._multichannel
else np.expand_dims(self.image, self._ndim)
)
return self._intensity_image[self.slice] * image
def _image_intensity_double(self):
return self.image_intensity.astype(np.float64, copy=False)
@property
def centroid_local(self):
M = self.moments
M0 = M[(0,) * self._ndim]
def _get_element(axis):
return (0,) * axis + (1,) + (0,) * (self._ndim - 1 - axis)
return np.asarray(
tuple(M[_get_element(axis)] / M0 for axis in range(self._ndim))
)
@property
def intensity_max(self):
vals = self.image_intensity[self.image]
return np.max(vals, axis=0).astype(np.float64, copy=False)
@property
def intensity_mean(self):
return np.mean(self.image_intensity[self.image], axis=0)
@property
def intensity_min(self):
vals = self.image_intensity[self.image]
return np.min(vals, axis=0).astype(np.float64, copy=False)
@property
def intensity_std(self):
vals = self.image_intensity[self.image]
return np.std(vals, axis=0)
@property
def axis_major_length(self):
if self._ndim == 2:
l1 = self.inertia_tensor_eigvals[0]
return 4 * sqrt(l1)
elif self._ndim == 3:
# equivalent to _inertia_eigvals_to_axes_lengths_3D(ev)[0]
ev = self.inertia_tensor_eigvals
return sqrt(10 * (ev[0] + ev[1] - ev[2]))
else:
raise ValueError("axis_major_length only available in 2D and 3D")
@property
def axis_minor_length(self):
if self._ndim == 2:
l2 = self.inertia_tensor_eigvals[-1]
return 4 * sqrt(l2)
elif self._ndim == 3:
# equivalent to _inertia_eigvals_to_axes_lengths_3D(ev)[-1]
ev = self.inertia_tensor_eigvals
return sqrt(10 * (-ev[0] + ev[1] + ev[2]))
else:
raise ValueError("axis_minor_length only available in 2D and 3D")
@property
@_cached
def moments(self):
M = _moments.moments(self.image.astype(np.uint8), 3, spacing=self._spacing)
return M
@property
@_cached
def moments_central(self):
mu = _moments.moments_central(
self.image.astype(np.uint8),
self.centroid_local,
order=3,
spacing=self._spacing,
)
return mu
@property
@only2d
def moments_hu(self):
if any(s != 1.0 for s in self._spacing):
raise NotImplementedError('`moments_hu` supports spacing = (1, 1) only')
return _moments.moments_hu(self.moments_normalized)
@property
@_cached
def moments_normalized(self):
return _moments.moments_normalized(
self.moments_central, 3, spacing=self._spacing
)
@property
@only2d
def orientation(self):
a, b, b, c = self.inertia_tensor.flat
if a - c == 0:
if b < 0:
return PI / 4.0
else:
return -PI / 4.0
else:
return 0.5 * atan2(-2 * b, c - a)
@property
@only2d
def perimeter(self):
if len(np.unique(self._spacing)) != 1:
raise NotImplementedError('`perimeter` supports isotropic spacings only')
return perimeter(self.image, 4) * self._spacing[0]
@property
@only2d
def perimeter_crofton(self):
if len(np.unique(self._spacing)) != 1:
raise NotImplementedError('`perimeter` supports isotropic spacings only')
return perimeter_crofton(self.image, 4) * self._spacing[0]
@property
def solidity(self):
return self.area / self.area_convex
@property
def centroid_weighted(self):
ctr = self.centroid_weighted_local
return tuple(
idx + slc.start * spc
for idx, slc, spc in zip(ctr, self.slice, self._spacing)
)
@property
def centroid_weighted_local(self):
M = self.moments_weighted
M0 = M[(0,) * self._ndim]
def _get_element(axis):
return (0,) * axis + (1,) + (0,) * (self._ndim - 1 - axis)
return np.asarray(
tuple(M[_get_element(axis)] / M0 for axis in range(self._ndim))
)
@property
@_cached
def moments_weighted(self):
image = self._image_intensity_double()
if self._multichannel:
moments = np.stack(
[
_moments.moments(image[..., i], order=3, spacing=self._spacing)
for i in range(image.shape[-1])
],
axis=-1,
)
else:
moments = _moments.moments(image, order=3, spacing=self._spacing)
return moments
@property
@_cached
def moments_weighted_central(self):
ctr = self.centroid_weighted_local
image = self._image_intensity_double()
if self._multichannel:
moments_list = [
_moments.moments_central(
image[..., i], center=ctr[..., i], order=3, spacing=self._spacing
)
for i in range(image.shape[-1])
]
moments = np.stack(moments_list, axis=-1)
else:
moments = _moments.moments_central(
image, ctr, order=3, spacing=self._spacing
)
return moments
@property
@only2d
def moments_weighted_hu(self):
if not (np.array(self._spacing) == np.array([1, 1])).all():
raise NotImplementedError('`moments_hu` supports spacing = (1, 1) only')
nu = self.moments_weighted_normalized
if self._multichannel:
nchannels = self._intensity_image.shape[-1]
return np.stack(
[_moments.moments_hu(nu[..., i]) for i in range(nchannels)],
axis=-1,
)
else:
return _moments.moments_hu(nu)
@property
@_cached
def moments_weighted_normalized(self):
mu = self.moments_weighted_central
if self._multichannel:
nchannels = self._intensity_image.shape[-1]
return np.stack(
[
_moments.moments_normalized(
mu[..., i], order=3, spacing=self._spacing
)
for i in range(nchannels)
],
axis=-1,
)
else:
return _moments.moments_normalized(mu, order=3, spacing=self._spacing)
def __iter__(self):
props = PROP_VALS
if self._intensity_image is None:
unavailable_props = _require_intensity_image
props = props.difference(unavailable_props)
return iter(sorted(props))
def __getitem__(self, key):
value = getattr(self, key, None)
if value is not None:
return value
else: # backwards compatibility
return getattr(self, PROPS[key])
def __eq__(self, other):
if not isinstance(other, RegionProperties):
return False
for key in PROP_VALS:
try:
# so that NaNs are equal
np.testing.assert_equal(
getattr(self, key, None), getattr(other, key, None)
)
except AssertionError:
return False
return True
# For compatibility with code written prior to 0.16
_RegionProperties = RegionProperties
def _props_to_dict(regions, properties=('label', 'bbox'), separator='-'):
"""Convert image region properties list into a column dictionary.
Parameters
----------
regions : (K,) list
List of RegionProperties objects as returned by :func:`regionprops`.
properties : tuple or list of str, optional
Properties that will be included in the resulting dictionary
For a list of available properties, please see :func:`regionprops`.
Users should remember to add "label" to keep track of region
identities.
separator : str, optional
For non-scalar properties not listed in OBJECT_COLUMNS, each element
will appear in its own column, with the index of that element separated
from the property name by this separator. For example, the inertia
tensor of a 2D region will appear in four columns:
``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``,
and ``inertia_tensor-1-1`` (where the separator is ``-``).
Object columns are those that cannot be split in this way because the
number of columns would change depending on the object. For example,
``image`` and ``coords``.
Returns
-------
out_dict : dict
Dictionary mapping property names to an array of values of that
property, one value per region. This dictionary can be used as input to
pandas ``DataFrame`` to map property names to columns in the frame and
regions to rows.
Notes
-----
Each column contains either a scalar property, an object property, or an
element in a multidimensional array.
Properties with scalar values for each region, such as "eccentricity", will
appear as a float or int array with that property name as key.
Multidimensional properties *of fixed size* for a given image dimension,
such as "centroid" (every centroid will have three elements in a 3D image,
no matter the region size), will be split into that many columns, with the
name {property_name}{separator}{element_num} (for 1D properties),
{property_name}{separator}{elem_num0}{separator}{elem_num1} (for 2D
properties), and so on.
For multidimensional properties that don't have a fixed size, such as
"image" (the image of a region varies in size depending on the region
size), an object array will be used, with the corresponding property name
as the key.
Examples
--------
>>> from skimage import data, util, measure
>>> image = data.coins()
>>> label_image = measure.label(image > 110, connectivity=image.ndim)
>>> proplist = regionprops(label_image, image)
>>> props = _props_to_dict(proplist, properties=['label', 'inertia_tensor',
... 'inertia_tensor_eigvals'])
>>> props # doctest: +ELLIPSIS +SKIP
{'label': array([ 1, 2, ...]), ...
'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ...
...,
'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])}
The resulting dictionary can be directly passed to pandas, if installed, to
obtain a clean DataFrame:
>>> import pandas as pd # doctest: +SKIP
>>> data = pd.DataFrame(props) # doctest: +SKIP
>>> data.head() # doctest: +SKIP
label inertia_tensor-0-0 ... inertia_tensor_eigvals-1
0 1 4012.909888 ... 267.065503
1 2 8.514739 ... 2.834806
2 3 0.666667 ... 0.000000
3 4 0.000000 ... 0.000000
4 5 0.222222 ... 0.111111
"""
out = {}
n = len(regions)
for prop in properties:
r = regions[0]
# Copy the original property name so the output will have the
# user-provided property name in the case of deprecated names.
orig_prop = prop
# determine the current property name for any deprecated property.
prop = PROPS.get(prop, prop)
rp = getattr(r, prop)
if prop in COL_DTYPES:
dtype = COL_DTYPES[prop]
else:
func = r._extra_properties[prop]
dtype = _infer_regionprop_dtype(
func,
intensity=r._intensity_image is not None,
ndim=r.image.ndim,
)
# scalars and objects are dedicated one column per prop
# array properties are raveled into multiple columns
# for more info, refer to notes 1
if np.isscalar(rp) or prop in OBJECT_COLUMNS or dtype is np.object_:
column_buffer = np.empty(n, dtype=dtype)
for i in range(n):
column_buffer[i] = regions[i][prop]
out[orig_prop] = np.copy(column_buffer)
else:
# precompute property column names and locations
modified_props = []
locs = []
for ind in np.ndindex(np.shape(rp)):
modified_props.append(separator.join(map(str, (orig_prop,) + ind)))
locs.append(ind if len(ind) > 1 else ind[0])
# fill temporary column data_array
n_columns = len(locs)
column_data = np.empty((n, n_columns), dtype=dtype)
for k in range(n):
# we coerce to a numpy array to ensure structures like
# tuple-of-arrays expand correctly into columns
rp = np.asarray(regions[k][prop])
for i, loc in enumerate(locs):
column_data[k, i] = rp[loc]
# add the columns to the output dictionary
for i, modified_prop in enumerate(modified_props):
out[modified_prop] = column_data[:, i]
return out
def regionprops_table(
label_image,
intensity_image=None,
properties=('label', 'bbox'),
*,
cache=True,
separator='-',
extra_properties=None,
spacing=None,
):
"""Compute image properties and return them as a pandas-compatible table.
The table is a dictionary mapping column names to value arrays. See Notes
section below for details.
.. versionadded:: 0.16
Parameters
----------
label_image : (M, N[, P]) ndarray
Labeled input image. Labels with value 0 are ignored.
intensity_image : (M, N[, P][, C]) ndarray, optional
Intensity (i.e., input) image with same size as labeled image, plus
optionally an extra dimension for multichannel data. The channel dimension,
if present, must be the last axis. Default is None.
.. versionchanged:: 0.18.0
The ability to provide an extra dimension for channels was added.
properties : tuple or list of str, optional
Properties that will be included in the resulting dictionary
For a list of available properties, please see :func:`regionprops`.
Users should remember to add "label" to keep track of region
identities.
cache : bool, optional
Determine whether to cache calculated properties. The computation is
much faster for cached properties, whereas the memory consumption
increases.
separator : str, optional
For non-scalar properties not listed in OBJECT_COLUMNS, each element
will appear in its own column, with the index of that element separated
from the property name by this separator. For example, the inertia
tensor of a 2D region will appear in four columns:
``inertia_tensor-0-0``, ``inertia_tensor-0-1``, ``inertia_tensor-1-0``,
and ``inertia_tensor-1-1`` (where the separator is ``-``).
Object columns are those that cannot be split in this way because the
number of columns would change depending on the object. For example,
``image`` and ``coords``.
extra_properties : Iterable of callables
Add extra property computation functions that are not included with
skimage. The name of the property is derived from the function name,
the dtype is inferred by calling the function on a small sample.
If the name of an extra property clashes with the name of an existing
property the extra property will not be visible and a UserWarning is
issued. A property computation function must take a region mask as its
first argument. If the property requires an intensity image, it must
accept the intensity image as the second argument.
spacing: tuple of float, shape (ndim,)
The pixel spacing along each axis of the image.
Returns
-------
out_dict : dict
Dictionary mapping property names to an array of values of that
property, one value per region. This dictionary can be used as input to
pandas ``DataFrame`` to map property names to columns in the frame and
regions to rows. If the image has no regions,
the arrays will have length 0, but the correct type.
Notes
-----
Each column contains either a scalar property, an object property, or an
element in a multidimensional array.
Properties with scalar values for each region, such as "eccentricity", will
appear as a float or int array with that property name as key.
Multidimensional properties *of fixed size* for a given image dimension,
such as "centroid" (every centroid will have three elements in a 3D image,