Debian Codegraph @

dask_image/ndmeasure/__init__.py

raw
1 # -*- coding: utf-8 -*-
2
3 import collections
4 import functools
5 import operator
6 import warnings
7 from dask import compute, delayed
8 import dask.config as dask_config
9
10 import dask.array as da
11 import dask.bag as db
12 import numpy as np
13
14 from . import _utils
15 from ._utils import _label
16 from ._utils._find_objects import (
17 _array_chunk_location,
18 _find_bounding_boxes,
19 _find_objects,
20 )
21
22 __all__ = [
23 "area",
24 "center_of_mass",
25 "extrema",
26 "histogram",
27 "label",
28 "labeled_comprehension",
29 "maximum",
30 "maximum_position",
31 "mean",
32 "median",
33 "minimum",
34 "minimum_position",
35 "standard_deviation",
36 "sum",
37 "sum_labels",
38 "variance",
39 ]
40
41
42 def area(image, label_image=None, index=None):
43 """Find the area of specified subregions in an image.
44
45 Parameters
46 ----------
47 image : ndarray
48 N-D image data
49 label_image : ndarray, optional
50 Image features noted by integers.
51 If None (default), returns area of total image dimensions.
52 index : int or sequence of ints, optional
53 Labels to include in output. If None (default), all values where
54 non-zero ``label_image`` are used.
55 The ``index`` argument only works when ``label_image`` is specified.
56
57 Returns
58 -------
59 area : ndarray
60 Area of ``index`` selected regions from ``label_image``.
61
62 Example
63 -------
64 >>> import dask.array as da
65 >>> image = da.random.random((3, 3))
66 >>> label_image = da.from_array(
67 [[1, 1, 0],
68 [1, 0, 3],
69 [0, 7, 0]], chunks=(1, 3))
70
71 >>> # No labels given, returns area of total image dimensions
72 >>> area(image)
73 9
74
75 >>> # Combined area of all non-zero labels
76 >>> area(image, label_image).compute()
77 5
78
79 >>> # Areas of selected labels selected with the ``index`` keyword argument
80 >>> area(image, label_image, index=[0, 1, 2, 3]).compute()
81 array([4, 3, 0, 1], dtype=int64)
82 """
83
84 if label_image is None:
85 return da.prod(np.array([i for i in image.shape]))
86
87 else:
88 image, label_image, index = _utils._norm_input_labels_index(
89 image, label_image, index
90 )
91
92 ones = da.ones(
93 label_image.shape, dtype=bool, chunks=label_image.chunks
94 )
95
96 area_lbl = labeled_comprehension(
97 ones, label_image, index, len, int, int(0)
98 )
99
100 return area_lbl
101
102
103 def center_of_mass(image, label_image=None, index=None):
104 """
105 Find the center of mass over an image at specified subregions.
106
107 Parameters
108 ----------
109 image : ndarray
110 N-D image data
111 label_image : ndarray, optional
112 Image features noted by integers. If None (default), all values.
113 index : int or sequence of ints, optional
114 Labels to include in output. If None (default), all values where
115 non-zero ``label_image`` are used.
116
117 The ``index`` argument only works when ``label_image`` is specified.
118
119 Returns
120 -------
121 center_of_mass : ndarray
122 Coordinates of centers-of-mass of ``image`` over the ``index`` selected
123 regions from ``label_image``.
124 """
125
126 image, label_image, index = _utils._norm_input_labels_index(
127 image, label_image, index
128 )
129
130 # SciPy transposes these for some reason.
131 # So we do the same thing here.
132 # This only matters if index is some array.
133 index = index.T
134
135 out_dtype = np.dtype([("com", float, (image.ndim,))])
136 default_1d = np.full((1,), np.nan, dtype=out_dtype)
137
138 func = functools.partial(
139 _utils._center_of_mass, shape=image.shape, dtype=out_dtype
140 )
141 com_lbl = labeled_comprehension(
142 image, label_image, index,
143 func, out_dtype, default_1d[0], pass_positions=True
144 )
145 com_lbl = com_lbl["com"]
146
147 return com_lbl
148
149
150 def extrema(image, label_image=None, index=None):
151 """
152 Find the min and max with positions over an image at specified subregions.
153
154 Parameters
155 ----------
156 image : ndarray
157 N-D image data
158 label_image : ndarray, optional
159 Image features noted by integers. If None (default), all values.
160 index : int or sequence of ints, optional
161 Labels to include in output. If None (default), all values where
162 non-zero ``label_image`` are used.
163
164 The ``index`` argument only works when ``label_image`` is specified.
165
166 Returns
167 -------
168 minimums, maximums, min_positions, max_positions : tuple of ndarrays
169 Values and coordinates of minimums and maximums in each feature.
170 """
171
172 image, label_image, index = _utils._norm_input_labels_index(
173 image, label_image, index
174 )
175
176 out_dtype = np.dtype([
177 ("min_val", image.dtype),
178 ("max_val", image.dtype),
179 ("min_pos", np.dtype(int), image.ndim),
180 ("max_pos", np.dtype(int), image.ndim)
181 ])
182 default_1d = np.zeros((1,), dtype=out_dtype)
183
184 func = functools.partial(
185 _utils._extrema, shape=image.shape, dtype=out_dtype
186 )
187 extrema_lbl = labeled_comprehension(
188 image, label_image, index,
189 func, out_dtype, default_1d[0], pass_positions=True
190 )
191 extrema_lbl = collections.OrderedDict([
192 (k, extrema_lbl[k])
193 for k in ["min_val", "max_val", "min_pos", "max_pos"]
194 ])
195
196 for pos_key in ["min_pos", "max_pos"]:
197 pos_nd = extrema_lbl[pos_key]
198
199 if index.ndim == 0:
200 pos_nd = da.squeeze(pos_nd)
201 elif index.ndim > 1:
202 pos_nd = pos_nd.reshape(
203 (int(np.prod(pos_nd.shape[:-1])), pos_nd.shape[-1])
204 )
205
206 extrema_lbl[pos_key] = pos_nd
207
208 result = tuple(extrema_lbl.values())
209
210 return result
211
212
213 def find_objects(label_image):
214 """Return bounding box slices for each object labelled by integers.
215
216 Parameters
217 ----------
218 label_image : ndarray
219 Image features noted by integers.
220
221 Returns
222 -------
223 Dask dataframe
224 Each row represents an individual integer label. Columns contain the
225 slice information for the object boundaries in each dimension
226 (dimensions are named: 0, 1, ..., nd).
227
228 Notes
229 -----
230 You must have the optional dependencies ``dask[dataframe]`` and
231 ``pandas`` installed to use the ``find_objects`` function. They can
232 be installed together via the ``dataframe`` extras group:
233 ``pip install dask-image[dataframe]``.
234 """
235 try:
236 import pandas # noqa: F401 # used by the private helpers below
237 import dask.dataframe as dd
238 except ImportError as e:
239 raise ImportError(
240 "dask_image.ndmeasure.find_objects requires the optional "
241 "dependencies `dask[dataframe]` and `pandas`. Install them "
242 "with `pip install dask-image[dataframe]`."
243 ) from e
244
245 if label_image.dtype.char not in np.typecodes['AllInteger']:
246 raise ValueError("find_objects only accepts integer dtype arrays")
247
248 block_iter = zip(
249 np.ndindex(*label_image.numblocks),
250 map(functools.partial(operator.getitem, label_image),
251 da.core.slices_from_chunks(label_image.chunks))
252 )
253
254 arrays = []
255 for block_id, block in block_iter:
256 array_location = _array_chunk_location(block_id, label_image.chunks)
257 arrays.append(delayed(_find_bounding_boxes)(block, array_location))
258
259 bag = db.from_sequence(arrays)
260 result = bag.fold(
261 functools.partial(_find_objects, label_image.ndim), split_every=2
262 ).to_delayed()
263 meta = dd.utils.make_meta([(i, object) for i in range(label_image.ndim)])
264 # avoid the user having to call compute twice on result
265 result = delayed(compute)(result)[0]
266
267 with dask_config.set({'dataframe.convert-string': False}):
268 result = dd.from_delayed(
269 result, meta=meta, prefix="find-objects-", verify_meta=False
270 )
271
272 return result
273
274
275 def histogram(image,
276 min,
277 max,
278 bins,
279 label_image=None,
280 index=None):
281 """
282 Find the histogram over an image at specified subregions.
283
284 Histogram calculates the frequency of values in an array within bins
285 determined by ``min``, ``max``, and ``bins``. The ``label_image`` and
286 ``index`` keywords can limit the scope of the histogram to specified
287 sub-regions within the array.
288
289 Parameters
290 ----------
291 image : ndarray
292 N-D image data
293 min : int
294 Minimum value of range of histogram bins.
295 max : int
296 Maximum value of range of histogram bins.
297 bins : int
298 Number of bins.
299 label_image : ndarray, optional
300 Image features noted by integers. If None (default), all values.
301 index : int or sequence of ints, optional
302 Labels to include in output. If None (default), all values where
303 non-zero ``label_image`` are used.
304
305 The ``index`` argument only works when ``label_image`` is specified.
306
307 Returns
308 -------
309 histogram : ndarray
310 Histogram of ``image`` over the ``index`` selected regions from
311 ``label_image``.
312 """
313
314 image, label_image, index = _utils._norm_input_labels_index(
315 image, label_image, index
316 )
317 min = int(min)
318 max = int(max)
319 bins = int(bins)
320
321 func = functools.partial(_utils._histogram, min=min, max=max, bins=bins)
322 result = labeled_comprehension(
323 image, label_image, index, func, object, None
324 )
325
326 return result
327
328
329 def label(image, structure=None, wrap_axes=None):
330 """
331 Label features in an array.
332
333 Parameters
334 ----------
335 image : ndarray
336 An array-like object to be labeled. Any non-zero values in ``image``
337 are counted as features and zero values are considered the background.
338 structure : ndarray, optional
339 A structuring element that defines feature connections.
340 ``structure`` must be symmetric. If no structuring element is
341 provided, one is automatically generated with a squared connectivity
342 equal to one. That is, for a 2-D ``image`` array, the default
343 structuring element is::
344
345 [[0,1,0],
346 [1,1,1],
347 [0,1,0]]
348
349 wrap_axes : tuple of int, optional
350 Whether labels should be wrapped across array boundaries, and if so
351 which axes.
352 This feature is not present in `ndimage.label`.
353 Examples:
354 - (0,) only wrap across the 0th axis.
355 - (0, 1) wrap across the 0th and 1st axis.
356 - (0, 1, 3) wrap across 0th, 1st and 3rd axis.
357
358 Returns
359 -------
360 label : ndarray or int
361 An integer ndarray where each unique feature in ``image`` has a unique
362 label in the returned array.
363 num_features : int
364 How many objects were found.
365 """
366
367 image = da.asarray(image)
368
369 labeled_blocks = np.empty(image.numblocks, dtype=object)
370
371 # First, label each block independently, incrementing the labels in that
372 # block by the total number of labels from previous blocks. This way, each
373 # block's labels are globally unique.
374 block_iter = zip(
375 np.ndindex(*image.numblocks),
376 map(functools.partial(operator.getitem, image),
377 da.core.slices_from_chunks(image.chunks))
378 )
379 index, input_block = next(block_iter)
380 labeled_blocks[index], total = _label.block_ndi_label_delayed(input_block,
381 structure)
382 for index, input_block in block_iter:
383 labeled_block, n = _label.block_ndi_label_delayed(input_block,
384 structure)
385 block_label_offset = da.where(labeled_block > 0,
386 total,
387 _label.LABEL_DTYPE.type(0))
388 labeled_block += block_label_offset
389 labeled_blocks[index] = labeled_block
390 total += n
391
392 # Put all the blocks together
393 block_labeled = da.block(labeled_blocks.tolist())
394
395 # Now, build a label connectivity graph that groups labels across blocks.
396 # We use this graph to find connected components and then relabel each
397 # block according to those.
398 label_groups = _label.label_adjacency_graph(
399 block_labeled, structure, total, wrap_axes=wrap_axes
400 )
401 new_labeling = _label.connected_components_delayed(label_groups)
402 relabeled = _label.relabel_blocks(block_labeled, new_labeling)
403 n = da.max(relabeled)
404
405 return (relabeled, n)
406
407
408 def labeled_comprehension(image,
409 label_image,
410 index,
411 func,
412 out_dtype,
413 default,
414 pass_positions=False):
415 """
416 Compute a function over an image at specified subregions.
417
418 Roughly equivalent to [func(image[labels == i]) for i in index].
419
420 Sequentially applies an arbitrary function (that works on array_like image)
421 to subsets of an n-D image array specified by ``label_image`` and
422 ``index``. The option exists to provide the function with positional
423 parameters as the second argument.
424
425 Parameters
426 ----------
427 image : ndarray
428 N-D image data
429 label_image : ndarray, optional
430 Image features noted by integers. If None (default), all values.
431 index : int or sequence of ints, optional
432 Labels to include in output. If None (default), all values where
433 non-zero ``label_image`` are used.
434
435 The ``index`` argument only works when ``label_image`` is specified.
436
437 func : callable
438 Python function to apply to ``label_image`` from ``image``.
439 out_dtype : dtype
440 Dtype to use for ``result``.
441 default : int, float or None
442 Default return value when a element of ``index`` does not exist
443 in ``label_image``.
444 pass_positions : bool, optional
445 If True, pass linear indices to ``func`` as a second argument.
446 Default is False.
447
448 Returns
449 -------
450 result : ndarray
451 Result of applying ``func`` on ``image`` over the ``index`` selected
452 regions from ``label_image``.
453 """
454
455 image, label_image, index = _utils._norm_input_labels_index(
456 image, label_image, index
457 )
458
459 out_dtype = np.dtype(out_dtype)
460 default_1d = np.full((1,), default, dtype=out_dtype)
461
462 pass_positions = bool(pass_positions)
463
464 args = (image,)
465 if pass_positions:
466 positions = _utils._ravel_shape_indices(
467 image.shape, chunks=image.chunks
468 )
469 args = (image, positions)
470
471 result = np.empty(index.shape, dtype=object)
472 for i in np.ndindex(index.shape):
473 lbl_mtch_i = (label_image == index[i])
474 args_lbl_mtch_i = tuple(e[lbl_mtch_i] for e in args)
475 result[i] = _utils._labeled_comprehension_func(
476 func, out_dtype, default_1d, *args_lbl_mtch_i
477 )
478
479 for i in range(result.ndim - 1, -1, -1):
480 result2 = result[..., 0]
481 for j in np.ndindex(index.shape[:i]):
482 result2[j] = da.stack(result[j].tolist(), axis=0)
483 result = result2
484 result = result[()][..., 0]
485
486 return result
487
488
489 def maximum(image, label_image=None, index=None):
490 """
491 Find the maxima over an image at specified subregions.
492
493 Parameters
494 ----------
495 image : ndarray
496 N-D image data
497 label_image : ndarray, optional
498 Image features noted by integers. If None (default), all values.
499 index : int or sequence of ints, optional
500 Labels to include in output. If None (default), all values where
501 non-zero ``label_image`` are used.
502
503 The ``index`` argument only works when ``label_image`` is specified.
504
505 Returns
506 -------
507 maxima : ndarray
508 Maxima of ``image`` over the ``index`` selected regions from
509 ``label_image``.
510 """
511
512 image, label_image, index = _utils._norm_input_labels_index(
513 image, label_image, index
514 )
515
516 return labeled_comprehension(
517 image, label_image, index, np.max, image.dtype, image.dtype.type(0)
518 )
519
520
521 def maximum_position(image, label_image=None, index=None):
522 """
523 Find the positions of maxima over an image at specified subregions.
524
525 For each region specified by ``label_image``, the position of the maximum
526 value of ``image`` within the region is returned.
527
528 Parameters
529 ----------
530 image : ndarray
531 N-D image data
532 label_image : ndarray, optional
533 Image features noted by integers. If None (default), all values.
534 index : int or sequence of ints, optional
535 Labels to include in output. If None (default), all values where
536 non-zero ``label_image`` are used.
537
538 The ``index`` argument only works when ``label_image`` is specified.
539
540 Returns
541 -------
542 maxima_positions : ndarray
543 Maxima positions of ``image`` over the ``index`` selected regions from
544 ``label_image``.
545 """
546
547 image, label_image, index = _utils._norm_input_labels_index(
548 image, label_image, index
549 )
550
551 if index.shape:
552 index = index.flatten()
553
554 out_dtype = np.dtype([("pos", int, (image.ndim,))])
555 default_1d = np.zeros((1,), dtype=out_dtype)
556
557 func = functools.partial(
558 _utils._argmax, shape=image.shape, dtype=out_dtype
559 )
560 max_pos_lbl = labeled_comprehension(
561 image, label_image, index,
562 func, out_dtype, default_1d[0], pass_positions=True
563 )
564 max_pos_lbl = max_pos_lbl["pos"]
565
566 if index.shape == tuple():
567 max_pos_lbl = da.squeeze(max_pos_lbl)
568
569 return max_pos_lbl
570
571
572 def mean(image, label_image=None, index=None):
573 """
574 Find the mean over an image at specified subregions.
575
576 Parameters
577 ----------
578 image : ndarray
579 N-D image data
580 label_image : ndarray, optional
581 Image features noted by integers. If None (default), all values.
582 index : int or sequence of ints, optional
583 Labels to include in output. If None (default), all values where
584 non-zero ``label_image`` are used.
585
586 The ``index`` argument only works when ``label_image`` is specified.
587
588 Returns
589 -------
590 means : ndarray
591 Mean of ``image`` over the ``index`` selected regions from
592 ``label_image``.
593 """
594
595 image, label_image, index = _utils._norm_input_labels_index(
596 image, label_image, index
597 )
598
599 nan = np.float64(np.nan)
600
601 mean_lbl = labeled_comprehension(
602 image, label_image, index, np.mean, np.float64, nan
603 )
604
605 return mean_lbl
606
607
608 def median(image, label_image=None, index=None):
609 """
610 Find the median over an image at specified subregions.
611
612 Parameters
613 ----------
614 image : ndarray
615 N-D image data
616 label_image : ndarray, optional
617 Image features noted by integers. If None (default), all values.
618 index : int or sequence of ints, optional
619 Labels to include in output. If None (default), all values where
620 non-zero ``label_image`` are used.
621
622 The ``index`` argument only works when ``label_image`` is specified.
623
624 Returns
625 -------
626 medians : ndarray
627 Median of ``image`` over the ``index`` selected regions from
628 ``label_image``.
629 """
630
631 image, label_image, index = _utils._norm_input_labels_index(
632 image, label_image, index
633 )
634
635 nan = np.float64(np.nan)
636
637 return labeled_comprehension(
638 image, label_image, index, np.median, np.float64, nan
639 )
640
641
642 def minimum(image, label_image=None, index=None):
643 """
644 Find the minima over an image at specified subregions.
645
646 Parameters
647 ----------
648 image : ndarray
649 N-D image data
650 label_image : ndarray, optional
651 Image features noted by integers. If None (default), all values.
652 index : int or sequence of ints, optional
653 Labels to include in output. If None (default), all values where
654 non-zero ``label_image`` are used.
655
656 The ``index`` argument only works when ``label_image`` is specified.
657
658 Returns
659 -------
660 minima : ndarray
661 Minima of ``image`` over the ``index`` selected regions from
662 ``label_image``.
663 """
664
665 image, label_image, index = _utils._norm_input_labels_index(
666 image, label_image, index
667 )
668
669 return labeled_comprehension(
670 image, label_image, index, np.min, image.dtype, image.dtype.type(0)
671 )
672
673
674 def minimum_position(image, label_image=None, index=None):
675 """
676 Find the positions of minima over an image at specified subregions.
677
678 Parameters
679 ----------
680 image : ndarray
681 N-D image data
682 label_image : ndarray, optional
683 Image features noted by integers. If None (default), all values.
684 index : int or sequence of ints, optional
685 Labels to include in output. If None (default), all values where
686 non-zero ``label_image`` are used.
687
688 The ``index`` argument only works when ``label_image`` is specified.
689
690 Returns
691 -------
692 minima_positions : ndarray
693 Maxima positions of ``image`` over the ``index`` selected regions from
694 ``label_image``.
695 """
696
697 image, label_image, index = _utils._norm_input_labels_index(
698 image, label_image, index
699 )
700
701 if index.shape:
702 index = index.flatten()
703
704 out_dtype = np.dtype([("pos", int, (image.ndim,))])
705 default_1d = np.zeros((1,), dtype=out_dtype)
706
707 func = functools.partial(
708 _utils._argmin, shape=image.shape, dtype=out_dtype
709 )
710 min_pos_lbl = labeled_comprehension(
711 image, label_image, index,
712 func, out_dtype, default_1d[0], pass_positions=True
713 )
714 min_pos_lbl = min_pos_lbl["pos"]
715
716 if index.shape == tuple():
717 min_pos_lbl = da.squeeze(min_pos_lbl)
718
719 return min_pos_lbl
720
721
722 def standard_deviation(image, label_image=None, index=None):
723 """
724 Find the standard deviation over an image at specified subregions.
725
726 Parameters
727 ----------
728 image : ndarray
729 N-D image data
730 label_image : ndarray, optional
731 Image features noted by integers. If None (default), all values.
732 index : int or sequence of ints, optional
733 Labels to include in output. If None (default), all values where
734 non-zero ``label_image`` are used.
735
736 The ``index`` argument only works when ``label_image`` is specified.
737
738 Returns
739 -------
740 standard_deviation : ndarray
741 Standard deviation of ``image`` over the ``index`` selected regions
742 from ``label_image``.
743 """
744
745 image, label_image, index = _utils._norm_input_labels_index(
746 image, label_image, index
747 )
748
749 nan = np.float64(np.nan)
750
751 std_lbl = labeled_comprehension(
752 image, label_image, index, np.std, np.float64, nan
753 )
754
755 return std_lbl
756
757
758 def sum_labels(image, label_image=None, index=None):
759 """
760 Find the sum of all pixels over specified subregions of an image.
761
762 Parameters
763 ----------
764 image : ndarray
765 N-D image data
766 label_image : ndarray, optional
767 Image features noted by integers. If None (default), all values.
768 index : int or sequence of ints, optional
769 Labels to include in output. If None (default), all values where
770 non-zero ``label_image`` are used.
771
772 The ``index`` argument only works when ``label_image`` is specified.
773
774 Returns
775 -------
776 sum_lbl : ndarray
777 Sum of ``image`` over the ``index`` selected regions from
778 ``label_image``.
779 """
780
781 image, label_image, index = _utils._norm_input_labels_index(
782 image, label_image, index
783 )
784
785 sum_lbl = labeled_comprehension(
786 image, label_image, index, np.sum, np.float64, np.float64(0)
787 )
788
789 return sum_lbl
790
791
792 def sum(image, label_image=None, index=None):
793 """DEPRECATED FUNCTION. Use `sum_labels` instead."""
794 warnings.warn("DEPRECATED FUNCTION. Use `sum_labels` instead.",
795 DeprecationWarning)
796 return sum_labels(image, label_image=label_image, index=index)
797
798
799 def variance(image, label_image=None, index=None):
800 """
801 Find the variance over an image at specified subregions.
802
803 Parameters
804 ----------
805 image : ndarray
806 N-D image data
807 label_image : ndarray, optional
808 Image features noted by integers. If None (default), all values.
809 index : int or sequence of ints, optional
810 Labels to include in output. If None (default), all values where
811 non-zero ``label_image`` are used.
812
813 The ``index`` argument only works when ``label_image`` is specified.
814
815 Returns
816 -------
817 variance : ndarray
818 Variance of ``image`` over the ``index`` selected regions from
819 ``label_image``.
820 """
821
822 image, label_image, index = _utils._norm_input_labels_index(
823 image, label_image, index
824 )
825
826 nan = np.float64(np.nan)
827
828 var_lbl = labeled_comprehension(
829 image, label_image, index, np.var, np.float64, nan
830 )
831
832 return var_lbl