-
-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy path__init__.py
More file actions
832 lines (663 loc) · 24.3 KB
/
Copy path__init__.py
File metadata and controls
832 lines (663 loc) · 24.3 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
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
# -*- coding: utf-8 -*-
import collections
import functools
import operator
import warnings
from dask import compute, delayed
import dask.config as dask_config
import dask.array as da
import dask.bag as db
import numpy as np
from . import _utils
from ._utils import _label
from ._utils._find_objects import (
_array_chunk_location,
_find_bounding_boxes,
_find_objects,
)
__all__ = [
"area",
"center_of_mass",
"extrema",
"histogram",
"label",
"labeled_comprehension",
"maximum",
"maximum_position",
"mean",
"median",
"minimum",
"minimum_position",
"standard_deviation",
"sum",
"sum_labels",
"variance",
]
def area(image, label_image=None, index=None):
"""Find the area of specified subregions in an image.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers.
If None (default), returns area of total image dimensions.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
area : ndarray
Area of ``index`` selected regions from ``label_image``.
Example
-------
>>> import dask.array as da
>>> image = da.random.random((3, 3))
>>> label_image = da.from_array(
[[1, 1, 0],
[1, 0, 3],
[0, 7, 0]], chunks=(1, 3))
>>> # No labels given, returns area of total image dimensions
>>> area(image)
9
>>> # Combined area of all non-zero labels
>>> area(image, label_image).compute()
5
>>> # Areas of selected labels selected with the ``index`` keyword argument
>>> area(image, label_image, index=[0, 1, 2, 3]).compute()
array([4, 3, 0, 1], dtype=int64)
"""
if label_image is None:
return da.prod(np.array([i for i in image.shape]))
else:
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
ones = da.ones(
label_image.shape, dtype=bool, chunks=label_image.chunks
)
area_lbl = labeled_comprehension(
ones, label_image, index, len, int, int(0)
)
return area_lbl
def center_of_mass(image, label_image=None, index=None):
"""
Find the center of mass over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
center_of_mass : ndarray
Coordinates of centers-of-mass of ``image`` over the ``index`` selected
regions from ``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
# SciPy transposes these for some reason.
# So we do the same thing here.
# This only matters if index is some array.
index = index.T
out_dtype = np.dtype([("com", float, (image.ndim,))])
default_1d = np.full((1,), np.nan, dtype=out_dtype)
func = functools.partial(
_utils._center_of_mass, shape=image.shape, dtype=out_dtype
)
com_lbl = labeled_comprehension(
image, label_image, index,
func, out_dtype, default_1d[0], pass_positions=True
)
com_lbl = com_lbl["com"]
return com_lbl
def extrema(image, label_image=None, index=None):
"""
Find the min and max with positions over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
minimums, maximums, min_positions, max_positions : tuple of ndarrays
Values and coordinates of minimums and maximums in each feature.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
out_dtype = np.dtype([
("min_val", image.dtype),
("max_val", image.dtype),
("min_pos", np.dtype(int), image.ndim),
("max_pos", np.dtype(int), image.ndim)
])
default_1d = np.zeros((1,), dtype=out_dtype)
func = functools.partial(
_utils._extrema, shape=image.shape, dtype=out_dtype
)
extrema_lbl = labeled_comprehension(
image, label_image, index,
func, out_dtype, default_1d[0], pass_positions=True
)
extrema_lbl = collections.OrderedDict([
(k, extrema_lbl[k])
for k in ["min_val", "max_val", "min_pos", "max_pos"]
])
for pos_key in ["min_pos", "max_pos"]:
pos_nd = extrema_lbl[pos_key]
if index.ndim == 0:
pos_nd = da.squeeze(pos_nd)
elif index.ndim > 1:
pos_nd = pos_nd.reshape(
(int(np.prod(pos_nd.shape[:-1])), pos_nd.shape[-1])
)
extrema_lbl[pos_key] = pos_nd
result = tuple(extrema_lbl.values())
return result
def find_objects(label_image):
"""Return bounding box slices for each object labelled by integers.
Parameters
----------
label_image : ndarray
Image features noted by integers.
Returns
-------
Dask dataframe
Each row represents an individual integer label. Columns contain the
slice information for the object boundaries in each dimension
(dimensions are named: 0, 1, ..., nd).
Notes
-----
You must have the optional dependencies ``dask[dataframe]`` and
``pandas`` installed to use the ``find_objects`` function. They can
be installed together via the ``dataframe`` extras group:
``pip install dask-image[dataframe]``.
"""
try:
import pandas # noqa: F401 # used by the private helpers below
import dask.dataframe as dd
except ImportError as e:
raise ImportError(
"dask_image.ndmeasure.find_objects requires the optional "
"dependencies `dask[dataframe]` and `pandas`. Install them "
"with `pip install dask-image[dataframe]`."
) from e
if label_image.dtype.char not in np.typecodes['AllInteger']:
raise ValueError("find_objects only accepts integer dtype arrays")
block_iter = zip(
np.ndindex(*label_image.numblocks),
map(functools.partial(operator.getitem, label_image),
da.core.slices_from_chunks(label_image.chunks))
)
arrays = []
for block_id, block in block_iter:
array_location = _array_chunk_location(block_id, label_image.chunks)
arrays.append(delayed(_find_bounding_boxes)(block, array_location))
bag = db.from_sequence(arrays)
result = bag.fold(
functools.partial(_find_objects, label_image.ndim), split_every=2
).to_delayed()
meta = dd.utils.make_meta([(i, object) for i in range(label_image.ndim)])
# avoid the user having to call compute twice on result
result = delayed(compute)(result)[0]
with dask_config.set({'dataframe.convert-string': False}):
result = dd.from_delayed(
result, meta=meta, prefix="find-objects-", verify_meta=False
)
return result
def histogram(image,
min,
max,
bins,
label_image=None,
index=None):
"""
Find the histogram over an image at specified subregions.
Histogram calculates the frequency of values in an array within bins
determined by ``min``, ``max``, and ``bins``. The ``label_image`` and
``index`` keywords can limit the scope of the histogram to specified
sub-regions within the array.
Parameters
----------
image : ndarray
N-D image data
min : int
Minimum value of range of histogram bins.
max : int
Maximum value of range of histogram bins.
bins : int
Number of bins.
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
histogram : ndarray
Histogram of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
min = int(min)
max = int(max)
bins = int(bins)
func = functools.partial(_utils._histogram, min=min, max=max, bins=bins)
result = labeled_comprehension(
image, label_image, index, func, object, None
)
return result
def label(image, structure=None, wrap_axes=None):
"""
Label features in an array.
Parameters
----------
image : ndarray
An array-like object to be labeled. Any non-zero values in ``image``
are counted as features and zero values are considered the background.
structure : ndarray, optional
A structuring element that defines feature connections.
``structure`` must be symmetric. If no structuring element is
provided, one is automatically generated with a squared connectivity
equal to one. That is, for a 2-D ``image`` array, the default
structuring element is::
[[0,1,0],
[1,1,1],
[0,1,0]]
wrap_axes : tuple of int, optional
Whether labels should be wrapped across array boundaries, and if so
which axes.
This feature is not present in `ndimage.label`.
Examples:
- (0,) only wrap across the 0th axis.
- (0, 1) wrap across the 0th and 1st axis.
- (0, 1, 3) wrap across 0th, 1st and 3rd axis.
Returns
-------
label : ndarray or int
An integer ndarray where each unique feature in ``image`` has a unique
label in the returned array.
num_features : int
How many objects were found.
"""
image = da.asarray(image)
labeled_blocks = np.empty(image.numblocks, dtype=object)
# First, label each block independently, incrementing the labels in that
# block by the total number of labels from previous blocks. This way, each
# block's labels are globally unique.
block_iter = zip(
np.ndindex(*image.numblocks),
map(functools.partial(operator.getitem, image),
da.core.slices_from_chunks(image.chunks))
)
index, input_block = next(block_iter)
labeled_blocks[index], total = _label.block_ndi_label_delayed(input_block,
structure)
for index, input_block in block_iter:
labeled_block, n = _label.block_ndi_label_delayed(input_block,
structure)
block_label_offset = da.where(labeled_block > 0,
total,
_label.LABEL_DTYPE.type(0))
labeled_block += block_label_offset
labeled_blocks[index] = labeled_block
total += n
# Put all the blocks together
block_labeled = da.block(labeled_blocks.tolist())
# Now, build a label connectivity graph that groups labels across blocks.
# We use this graph to find connected components and then relabel each
# block according to those.
label_groups = _label.label_adjacency_graph(
block_labeled, structure, total, wrap_axes=wrap_axes
)
new_labeling = _label.connected_components_delayed(label_groups)
relabeled = _label.relabel_blocks(block_labeled, new_labeling)
n = da.max(relabeled)
return (relabeled, n)
def labeled_comprehension(image,
label_image,
index,
func,
out_dtype,
default,
pass_positions=False):
"""
Compute a function over an image at specified subregions.
Roughly equivalent to [func(image[labels == i]) for i in index].
Sequentially applies an arbitrary function (that works on array_like image)
to subsets of an n-D image array specified by ``label_image`` and
``index``. The option exists to provide the function with positional
parameters as the second argument.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
func : callable
Python function to apply to ``label_image`` from ``image``.
out_dtype : dtype
Dtype to use for ``result``.
default : int, float or None
Default return value when a element of ``index`` does not exist
in ``label_image``.
pass_positions : bool, optional
If True, pass linear indices to ``func`` as a second argument.
Default is False.
Returns
-------
result : ndarray
Result of applying ``func`` on ``image`` over the ``index`` selected
regions from ``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
out_dtype = np.dtype(out_dtype)
default_1d = np.full((1,), default, dtype=out_dtype)
pass_positions = bool(pass_positions)
args = (image,)
if pass_positions:
positions = _utils._ravel_shape_indices(
image.shape, chunks=image.chunks
)
args = (image, positions)
result = np.empty(index.shape, dtype=object)
for i in np.ndindex(index.shape):
lbl_mtch_i = (label_image == index[i])
args_lbl_mtch_i = tuple(e[lbl_mtch_i] for e in args)
result[i] = _utils._labeled_comprehension_func(
func, out_dtype, default_1d, *args_lbl_mtch_i
)
for i in range(result.ndim - 1, -1, -1):
result2 = result[..., 0]
for j in np.ndindex(index.shape[:i]):
result2[j] = da.stack(result[j].tolist(), axis=0)
result = result2
result = result[()][..., 0]
return result
def maximum(image, label_image=None, index=None):
"""
Find the maxima over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
maxima : ndarray
Maxima of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
return labeled_comprehension(
image, label_image, index, np.max, image.dtype, image.dtype.type(0)
)
def maximum_position(image, label_image=None, index=None):
"""
Find the positions of maxima over an image at specified subregions.
For each region specified by ``label_image``, the position of the maximum
value of ``image`` within the region is returned.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
maxima_positions : ndarray
Maxima positions of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
if index.shape:
index = index.flatten()
out_dtype = np.dtype([("pos", int, (image.ndim,))])
default_1d = np.zeros((1,), dtype=out_dtype)
func = functools.partial(
_utils._argmax, shape=image.shape, dtype=out_dtype
)
max_pos_lbl = labeled_comprehension(
image, label_image, index,
func, out_dtype, default_1d[0], pass_positions=True
)
max_pos_lbl = max_pos_lbl["pos"]
if index.shape == tuple():
max_pos_lbl = da.squeeze(max_pos_lbl)
return max_pos_lbl
def mean(image, label_image=None, index=None):
"""
Find the mean over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
means : ndarray
Mean of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
nan = np.float64(np.nan)
mean_lbl = labeled_comprehension(
image, label_image, index, np.mean, np.float64, nan
)
return mean_lbl
def median(image, label_image=None, index=None):
"""
Find the median over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
medians : ndarray
Median of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
nan = np.float64(np.nan)
return labeled_comprehension(
image, label_image, index, np.median, np.float64, nan
)
def minimum(image, label_image=None, index=None):
"""
Find the minima over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
minima : ndarray
Minima of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
return labeled_comprehension(
image, label_image, index, np.min, image.dtype, image.dtype.type(0)
)
def minimum_position(image, label_image=None, index=None):
"""
Find the positions of minima over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
minima_positions : ndarray
Maxima positions of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
if index.shape:
index = index.flatten()
out_dtype = np.dtype([("pos", int, (image.ndim,))])
default_1d = np.zeros((1,), dtype=out_dtype)
func = functools.partial(
_utils._argmin, shape=image.shape, dtype=out_dtype
)
min_pos_lbl = labeled_comprehension(
image, label_image, index,
func, out_dtype, default_1d[0], pass_positions=True
)
min_pos_lbl = min_pos_lbl["pos"]
if index.shape == tuple():
min_pos_lbl = da.squeeze(min_pos_lbl)
return min_pos_lbl
def standard_deviation(image, label_image=None, index=None):
"""
Find the standard deviation over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
standard_deviation : ndarray
Standard deviation of ``image`` over the ``index`` selected regions
from ``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
nan = np.float64(np.nan)
std_lbl = labeled_comprehension(
image, label_image, index, np.std, np.float64, nan
)
return std_lbl
def sum_labels(image, label_image=None, index=None):
"""
Find the sum of all pixels over specified subregions of an image.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
sum_lbl : ndarray
Sum of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
sum_lbl = labeled_comprehension(
image, label_image, index, np.sum, np.float64, np.float64(0)
)
return sum_lbl
def sum(image, label_image=None, index=None):
"""DEPRECATED FUNCTION. Use `sum_labels` instead."""
warnings.warn("DEPRECATED FUNCTION. Use `sum_labels` instead.",
DeprecationWarning)
return sum_labels(image, label_image=label_image, index=index)
def variance(image, label_image=None, index=None):
"""
Find the variance over an image at specified subregions.
Parameters
----------
image : ndarray
N-D image data
label_image : ndarray, optional
Image features noted by integers. If None (default), all values.
index : int or sequence of ints, optional
Labels to include in output. If None (default), all values where
non-zero ``label_image`` are used.
The ``index`` argument only works when ``label_image`` is specified.
Returns
-------
variance : ndarray
Variance of ``image`` over the ``index`` selected regions from
``label_image``.
"""
image, label_image, index = _utils._norm_input_labels_index(
image, label_image, index
)
nan = np.float64(np.nan)
var_lbl = labeled_comprehension(
image, label_image, index, np.var, np.float64, nan
)
return var_lbl