/
generic.py
1752 lines (1535 loc) · 54.6 KB
/
generic.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
"""
General Description
-------------------
These filters compute the local histogram at each pixel, using a sliding window
similar to the method described in [1]_. A histogram is built using a moving
window in order to limit redundant computation. The moving window follows a
snake-like path:
...------------------------↘
↙--------------------------↙
↘--------------------------...
The local histogram is updated at each pixel as the footprint window
moves by, i.e. only those pixels entering and leaving the footprint
update the local histogram. The histogram size is 8-bit (256 bins) for 8-bit
images and 2- to 16-bit for 16-bit images depending on the maximum value of the
image.
The filter is applied up to the image border, the neighborhood used is
adjusted accordingly. The user may provide a mask image (same size as input
image) where non zero values are the part of the image participating in the
histogram computation. By default the entire image is filtered.
This implementation outperforms :func:`skimage.morphology.dilation`
for large footprints.
Input images will be cast in unsigned 8-bit integer or unsigned 16-bit integer
if necessary. The number of histogram bins is then determined from the maximum
value present in the image. Eventually, the output image is cast in the input
dtype, or the `output_dtype` if set.
To do
-----
* add simple examples, adapt documentation on existing examples
* add/check existing doc
* adapting tests for each type of filter
References
----------
.. [1] Huang, T. ,Yang, G. ; Tang, G.. "A fast two-dimensional
median filtering algorithm", IEEE Transactions on Acoustics, Speech and
Signal Processing, Feb 1979. Volume: 27 , Issue: 1, Page(s): 13 - 18.
"""
import numpy as np
from scipy import ndimage as ndi
from ..._shared.utils import check_nD, warn
from ...morphology.footprints import _footprint_is_sequence
from ...util import img_as_ubyte
from . import generic_cy
__all__ = [
'autolevel',
'equalize',
'gradient',
'maximum',
'mean',
'geometric_mean',
'subtract_mean',
'median',
'minimum',
'modal',
'enhance_contrast',
'pop',
'threshold',
'noise_filter',
'entropy',
'otsu',
]
def _preprocess_input(
image,
footprint=None,
out=None,
mask=None,
out_dtype=None,
pixel_size=1,
shift_x=None,
shift_y=None,
):
"""Preprocess and verify input for filters.rank methods.
Parameters
----------
image : 2-D array (integer or float)
Input image.
footprint : 2-D array (integer or float), optional
The neighborhood expressed as a 2-D array of 1's and 0's.
out : 2-D array (integer or float), optional
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
out_dtype : data-type, optional
Desired output data-type. Default is None, which means we cast output
in input dtype.
pixel_size : int, optional
Dimension of each pixel. Default value is 1.
shift_x, shift_y : int, optional
Offset added to the footprint center point. Shift is bounded to the
footprint size (center must be inside of the given footprint).
Returns
-------
image : 2-D array (np.uint8 or np.uint16)
footprint : 2-D array (np.uint8)
The neighborhood expressed as a binary 2-D array.
out : 3-D array (same dtype out_dtype or as input)
Output array. The two first dimensions are the spatial ones, the third
one is the pixel vector (length 1 by default).
mask : 2-D array (np.uint8)
Mask array that defines (>0) area of the image included in the local
neighborhood.
n_bins : int
Number of histogram bins.
"""
check_nD(image, 2)
input_dtype = image.dtype
if input_dtype in (bool, bool) or out_dtype in (bool, bool):
raise ValueError('dtype cannot be bool.')
if input_dtype not in (np.uint8, np.uint16):
message = (
f'Possible precision loss converting image of type '
f'{input_dtype} to uint8 as required by rank filters. '
f'Convert manually using skimage.util.img_as_ubyte to '
f'silence this warning.'
)
warn(message, stacklevel=5)
image = img_as_ubyte(image)
if _footprint_is_sequence(footprint):
raise ValueError(
"footprint sequences are not currently supported by rank filters"
)
footprint = np.ascontiguousarray(img_as_ubyte(footprint > 0))
if footprint.ndim != image.ndim:
raise ValueError('Image dimensions and neighborhood dimensions' 'do not match')
image = np.ascontiguousarray(image)
if mask is not None:
mask = img_as_ubyte(mask)
mask = np.ascontiguousarray(mask)
if image is out:
raise NotImplementedError("Cannot perform rank operation in place.")
if out is None:
if out_dtype is None:
out_dtype = image.dtype
out = np.empty(image.shape + (pixel_size,), dtype=out_dtype)
else:
if len(out.shape) == 2:
out = out.reshape(out.shape + (pixel_size,))
if image.dtype in (np.uint8, np.int8):
n_bins = 256
else:
# Convert to a Python int to avoid the potential overflow when we add
# 1 to the maximum of the image.
n_bins = int(max(3, image.max())) + 1
if n_bins > 2**10:
warn(
f'Bad rank filter performance is expected due to a '
f'large number of bins ({n_bins}), equivalent to an approximate '
f'bitdepth of {np.log2(n_bins):.1f}.',
stacklevel=2,
)
for name, value in zip(("shift_x", "shift_y"), (shift_x, shift_y)):
if np.dtype(type(value)) == bool:
warn(
f"Paramter `{name}` is boolean and will be interpreted as int. "
"This is not officially supported, use int instead.",
category=UserWarning,
stacklevel=4,
)
return image, footprint, out, mask, n_bins
def _handle_input_3D(
image,
footprint=None,
out=None,
mask=None,
out_dtype=None,
pixel_size=1,
shift_x=None,
shift_y=None,
shift_z=None,
):
"""Preprocess and verify input for filters.rank methods.
Parameters
----------
image : 3-D array (integer or float)
Input image.
footprint : 3-D array (integer or float), optional
The neighborhood expressed as a 3-D array of 1's and 0's.
out : 3-D array (integer or float), optional
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
out_dtype : data-type, optional
Desired output data-type. Default is None, which means we cast output
in input dtype.
pixel_size : int, optional
Dimension of each pixel. Default value is 1.
shift_x, shift_y, shift_z : int, optional
Offset added to the footprint center point. Shift is bounded to the
footprint size (center must be inside of the given footprint).
Returns
-------
image : 3-D array (np.uint8 or np.uint16)
footprint : 3-D array (np.uint8)
The neighborhood expressed as a binary 3-D array.
out : 3-D array (same dtype out_dtype or as input)
Output array. The two first dimensions are the spatial ones, the third
one is the pixel vector (length 1 by default).
mask : 3-D array (np.uint8)
Mask array that defines (>0) area of the image included in the local
neighborhood.
n_bins : int
Number of histogram bins.
"""
check_nD(image, 3)
if image.dtype not in (np.uint8, np.uint16):
message = (
f'Possible precision loss converting image of type '
f'{image.dtype} to uint8 as required by rank filters. '
f'Convert manually using skimage.util.img_as_ubyte to '
f'silence this warning.'
)
warn(message, stacklevel=2)
image = img_as_ubyte(image)
footprint = np.ascontiguousarray(img_as_ubyte(footprint > 0))
if footprint.ndim != image.ndim:
raise ValueError('Image dimensions and neighborhood dimensions' 'do not match')
image = np.ascontiguousarray(image)
if mask is None:
mask = np.ones(image.shape, dtype=np.uint8)
else:
mask = img_as_ubyte(mask)
mask = np.ascontiguousarray(mask)
if image is out:
raise NotImplementedError("Cannot perform rank operation in place.")
if out is None:
if out_dtype is None:
out_dtype = image.dtype
out = np.empty(image.shape + (pixel_size,), dtype=out_dtype)
else:
out = out.reshape(out.shape + (pixel_size,))
is_8bit = image.dtype in (np.uint8, np.int8)
if is_8bit:
n_bins = 256
else:
# Convert to a Python int to avoid the potential overflow when we add
# 1 to the maximum of the image.
n_bins = int(max(3, image.max())) + 1
if n_bins > 2**10:
warn(
f'Bad rank filter performance is expected due to a '
f'large number of bins ({n_bins}), equivalent to an approximate '
f'bitdepth of {np.log2(n_bins):.1f}.',
stacklevel=2,
)
for name, value in zip(
("shift_x", "shift_y", "shift_z"), (shift_x, shift_y, shift_z)
):
if np.dtype(type(value)) == bool:
warn(
f"Parameter `{name}` is boolean and will be interpreted as int. "
"This is not officially supported, use int instead.",
category=UserWarning,
stacklevel=4,
)
return image, footprint, out, mask, n_bins
def _apply_scalar_per_pixel(
func, image, footprint, out, mask, shift_x, shift_y, out_dtype=None
):
"""Process the specific cython function to the image.
Parameters
----------
func : function
Cython function to apply.
image : 2-D array (integer or float)
Input image.
footprint : 2-D array (integer or float)
The neighborhood expressed as a 2-D array of 1's and 0's.
out : 2-D array (integer or float)
If None, a new array is allocated.
mask : ndarray (integer or float)
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
out_dtype : data-type, optional
Desired output data-type. Default is None, which means we cast output
in input dtype.
"""
# preprocess and verify the input
image, footprint, out, mask, n_bins = _preprocess_input(
image, footprint, out, mask, out_dtype, shift_x=shift_x, shift_y=shift_y
)
# apply cython function
func(
image,
footprint,
shift_x=shift_x,
shift_y=shift_y,
mask=mask,
out=out,
n_bins=n_bins,
)
return np.squeeze(out, axis=-1)
def _apply_scalar_per_pixel_3D(
func, image, footprint, out, mask, shift_x, shift_y, shift_z, out_dtype=None
):
image, footprint, out, mask, n_bins = _handle_input_3D(
image,
footprint,
out,
mask,
out_dtype,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
func(
image,
footprint,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
mask=mask,
out=out,
n_bins=n_bins,
)
return out.reshape(out.shape[:3])
def _apply_vector_per_pixel(
func, image, footprint, out, mask, shift_x, shift_y, out_dtype=None, pixel_size=1
):
"""
Parameters
----------
func : function
Cython function to apply.
image : 2-D array (integer or float)
Input image.
footprint : 2-D array (integer or float)
The neighborhood expressed as a 2-D array of 1's and 0's.
out : 2-D array (integer or float)
If None, a new array is allocated.
mask : ndarray (integer or float)
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
out_dtype : data-type, optional
Desired output data-type. Default is None, which means we cast output
in input dtype.
pixel_size : int, optional
Dimension of each pixel.
Returns
-------
out : 3-D array with float dtype of dimensions (H,W,N), where (H,W) are
the dimensions of the input image and N is n_bins or
``image.max() + 1`` if no value is provided as a parameter.
Effectively, each pixel is a N-D feature vector that is the histogram.
The sum of the elements in the feature vector will be 1, unless no
pixels in the window were covered by both footprint and mask, in which
case all elements will be 0.
"""
# preprocess and verify the input
image, footprint, out, mask, n_bins = _preprocess_input(
image,
footprint,
out,
mask,
out_dtype,
pixel_size,
shift_x=shift_x,
shift_y=shift_y,
)
# apply cython function
func(
image,
footprint,
shift_x=shift_x,
shift_y=shift_y,
mask=mask,
out=out,
n_bins=n_bins,
)
return out
def autolevel(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0):
"""Auto-level image using local histogram.
This filter locally stretches the histogram of gray values to cover the
entire range of values from "white" to "black".
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import autolevel
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> auto = autolevel(img, disk(5))
>>> auto_vol = autolevel(volume, ball(5))
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._autolevel,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._autolevel_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def equalize(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0):
"""Equalize image using local histogram.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import equalize
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> equ = equalize(img, disk(5))
>>> equ_vol = equalize(volume, ball(5))
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._equalize,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._equalize_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def gradient(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0):
"""Return local gradient of an image (i.e. local maximum - local minimum).
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import gradient
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = gradient(img, disk(5))
>>> out_vol = gradient(volume, ball(5))
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._gradient,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._gradient_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def maximum(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0):
"""Return local maximum of an image.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
See also
--------
skimage.morphology.dilation
Notes
-----
The lower algorithm complexity makes `skimage.filters.rank.maximum`
more efficient for larger images and footprints.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import maximum
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = maximum(img, disk(5))
>>> out_vol = maximum(volume, ball(5))
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._maximum,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._maximum_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def mean(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0):
"""Return local mean of an image.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import mean
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> avg = mean(img, disk(5))
>>> avg_vol = mean(volume, ball(5))
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._mean,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._mean_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def geometric_mean(
image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0
):
"""Return local geometric mean of an image.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import mean
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> avg = geometric_mean(img, disk(5))
>>> avg_vol = geometric_mean(volume, ball(5))
References
----------
.. [1] Gonzalez, R. C. and Woods, R. E. "Digital Image Processing
(3rd Edition)." Prentice-Hall Inc, 2006.
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._geometric_mean,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._geometric_mean_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def subtract_mean(
image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0
):
"""Return image subtracted from its local mean.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
Notes
-----
Subtracting the mean value may introduce underflow. To compensate
this potential underflow, the obtained difference is downscaled by
a factor of 2 and shifted by `n_bins / 2 - 1`, the median value of
the local histogram (`n_bins = max(3, image.max()) +1` for 16-bits
images and 256 otherwise).
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import subtract_mean
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> out = subtract_mean(img, disk(5))
>>> out_vol = subtract_mean(volume, ball(5))
"""
np_image = np.asanyarray(image)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._subtract_mean,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._subtract_mean_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def median(
image,
footprint=None,
out=None,
mask=None,
shift_x=0,
shift_y=0,
shift_z=0,
):
"""Return local median of an image.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's. If None, a
full square of size 3 is used.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).
Returns
-------
out : ([P,] M, N) ndarray (same dtype as input image)
Output image.
See also
--------
skimage.filters.median : Implementation of a median filtering which handles
images with floating precision.
Examples
--------
>>> from skimage import data
>>> from skimage.morphology import disk, ball
>>> from skimage.filters.rank import median
>>> import numpy as np
>>> img = data.camera()
>>> rng = np.random.default_rng()
>>> volume = rng.integers(0, 255, size=(10,10,10), dtype=np.uint8)
>>> med = median(img, disk(5))
>>> med_vol = median(volume, ball(5))
"""
np_image = np.asanyarray(image)
if footprint is None:
footprint = ndi.generate_binary_structure(image.ndim, image.ndim)
if np_image.ndim == 2:
return _apply_scalar_per_pixel(
generic_cy._median,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
)
elif np_image.ndim == 3:
return _apply_scalar_per_pixel_3D(
generic_cy._median_3D,
image,
footprint,
out=out,
mask=mask,
shift_x=shift_x,
shift_y=shift_y,
shift_z=shift_z,
)
raise ValueError(f'`image` must have 2 or 3 dimensions, got {np_image.ndim}.')
def minimum(image, footprint, out=None, mask=None, shift_x=0, shift_y=0, shift_z=0):
"""Return local minimum of an image.
Parameters
----------
image : ([P,] M, N) ndarray (uint8, uint16)
Input image.
footprint : ndarray
The neighborhood expressed as an ndarray of 1's and 0's.
out : ([P,] M, N) array (same dtype as input)
If None, a new array is allocated.
mask : ndarray (integer or float), optional
Mask array that defines (>0) area of the image included in the local
neighborhood. If None, the complete image is used (default).
shift_x, shift_y, shift_z : int
Offset added to the footprint center point. Shift is bounded to the
footprint sizes (center must be inside the given footprint).