/
_filters.py
1255 lines (1059 loc) · 54.7 KB
/
_filters.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 numpy
import cupy
from cupy import _core
from cupy._core import internal
from cupyx.scipy.ndimage import _util
from cupyx.scipy.ndimage import _filters_core
from cupyx.scipy.ndimage import _filters_generic
def correlate(input, weights, output=None, mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional correlate.
The array is correlated with the given kernel.
Args:
input (cupy.ndarray): The input array.
weights (cupy.ndarray): Array of weights, same number of dimensions as
input
output (cupy.ndarray, dtype or None): The array in which to place the
output.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``constant``. Default is ``0.0``.
origin (scalar or tuple of scalar): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of correlate.
.. seealso:: :func:`scipy.ndimage.correlate`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
return _correlate_or_convolve(input, weights, output, mode, cval, origin)
def convolve(input, weights, output=None, mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional convolution.
The array is convolved with the given kernel.
Args:
input (cupy.ndarray): The input array.
weights (cupy.ndarray): Array of weights, same number of dimensions as
input
output (cupy.ndarray, dtype or None): The array in which to place the
output.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``constant``. Default is ``0.0``.
origin (scalar or tuple of scalar): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of convolution.
.. seealso:: :func:`scipy.ndimage.convolve`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
return _correlate_or_convolve(input, weights, output, mode, cval, origin,
True)
def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0,
origin=0):
"""One-dimensional correlate.
The array is correlated with the given kernel.
Args:
input (cupy.ndarray): The input array.
weights (cupy.ndarray): One-dimensional array of weights
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the 1D correlation.
.. seealso:: :func:`scipy.ndimage.correlate1d`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
weights, origins = _filters_core._convert_1d_args(input.ndim, weights,
origin, axis)
return _correlate_or_convolve(input, weights, output, mode, cval, origins)
def convolve1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0,
origin=0):
"""One-dimensional convolution.
The array is convolved with the given kernel.
Args:
input (cupy.ndarray): The input array.
weights (cupy.ndarray): One-dimensional array of weights
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the 1D convolution.
.. seealso:: :func:`scipy.ndimage.convolve1d`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
weights, origins = _filters_core._convert_1d_args(input.ndim, weights,
origin, axis)
return _correlate_or_convolve(input, weights, output, mode, cval, origins,
True)
def _correlate_or_convolve(input, weights, output, mode, cval, origin,
convolution=False):
origins, int_type = _filters_core._check_nd_args(input, weights,
mode, origin)
if weights.size == 0:
return cupy.zeros_like(input)
_util._check_cval(mode, cval, _util._is_integer_output(output, input))
if convolution:
weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
origins = list(origins)
for i, wsize in enumerate(weights.shape):
origins[i] = -origins[i]
if wsize % 2 == 0:
origins[i] -= 1
origins = tuple(origins)
elif weights.dtype.kind == "c":
# numpy.correlate conjugates weights rather than input.
weights = weights.conj()
weights_dtype = _util._get_weights_dtype(input, weights)
offsets = _filters_core._origins_to_offsets(origins, weights.shape)
kernel = _get_correlate_kernel(mode, weights.shape, int_type,
offsets, cval)
output = _filters_core._call_kernel(kernel, input, weights, output,
weights_dtype=weights_dtype)
return output
@cupy._util.memoize(for_each_device=True)
def _get_correlate_kernel(mode, w_shape, int_type, offsets, cval):
return _filters_core._generate_nd_kernel(
'correlate',
'W sum = (W)0;',
'sum += cast<W>({value}) * wval;',
'y = cast<Y>(sum);',
mode, w_shape, int_type, offsets, cval, ctype='W')
def _run_1d_correlates(input, params, get_weights, output, mode, cval,
origin=0):
"""
Enhanced version of _run_1d_filters that uses correlate1d as the filter
function. The params are a list of values to pass to the get_weights
callable given. If duplicate param values are found, the weights are
reused from the first invocation of get_weights. The get_weights callable
must return a 1D array of weights to give to correlate1d.
"""
wghts = {}
for param in params:
if param not in wghts:
wghts[param] = get_weights(param)
wghts = [wghts[param] for param in params]
return _filters_core._run_1d_filters(
[None if w is None else correlate1d for w in wghts],
input, wghts, output, mode, cval, origin)
def uniform_filter1d(input, size, axis=-1, output=None, mode="reflect",
cval=0.0, origin=0):
"""One-dimensional uniform filter along the given axis.
The lines of the array along the given axis are filtered with a uniform
filter of the given size.
Args:
input (cupy.ndarray): The input array.
size (int): Length of the uniform filter.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.uniform_filter1d`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
weights_dtype = _util._init_weights_dtype(input)
weights = cupy.full(size, 1 / size, dtype=weights_dtype)
return correlate1d(input, weights, axis, output, mode, cval, origin)
def uniform_filter(input, size=3, output=None, mode="reflect", cval=0.0,
origin=0):
"""Multi-dimensional uniform filter.
Args:
input (cupy.ndarray): The input array.
size (int or sequence of int): Lengths of the uniform filter for each
dimension. A single value applies to all axes.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int or sequence of int): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of ``0`` is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.uniform_filter`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
sizes = _util._fix_sequence_arg(size, input.ndim, 'size', int)
weights_dtype = _util._init_weights_dtype(input)
def get(size, dtype=weights_dtype):
return None if size <= 1 else cupy.full(size, 1 / size, dtype=dtype)
return _run_1d_correlates(input, sizes, get, output, mode, cval, origin)
def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
mode="reflect", cval=0.0, truncate=4.0):
"""One-dimensional Gaussian filter along the given axis.
The lines of the array along the given axis are filtered with a Gaussian
filter of the given standard deviation.
Args:
input (cupy.ndarray): The input array.
sigma (scalar): Standard deviation for Gaussian kernel.
axis (int): The axis of input along which to calculate. Default is -1.
order (int): An order of ``0``, the default, corresponds to convolution
with a Gaussian kernel. A positive order corresponds to convolution
with that derivative of a Gaussian.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
truncate (float): Truncate the filter at this many standard deviations.
Default is ``4.0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.gaussian_filter1d`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
radius = int(float(truncate) * float(sigma) + 0.5)
weights_dtype = _util._init_weights_dtype(input)
weights = _gaussian_kernel1d(
sigma, int(order), radius, dtype=weights_dtype
)
return correlate1d(input, weights, axis, output, mode, cval)
def gaussian_filter(input, sigma, order=0, output=None, mode="reflect",
cval=0.0, truncate=4.0):
"""Multi-dimensional Gaussian filter.
Args:
input (cupy.ndarray): The input array.
sigma (scalar or sequence of scalar): Standard deviations for each axis
of Gaussian kernel. A single value applies to all axes.
order (int or sequence of scalar): An order of ``0``, the default,
corresponds to convolution with a Gaussian kernel. A positive order
corresponds to convolution with that derivative of a Gaussian. A
single value applies to all axes.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
truncate (float): Truncate the filter at this many standard deviations.
Default is ``4.0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.gaussian_filter`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
sigmas = _util._fix_sequence_arg(sigma, input.ndim, 'sigma', float)
orders = _util._fix_sequence_arg(order, input.ndim, 'order', int)
truncate = float(truncate)
weights_dtype = _util._init_weights_dtype(input)
def get(param):
sigma, order = param
radius = int(truncate * float(sigma) + 0.5)
if radius <= 0:
return None
return _gaussian_kernel1d(sigma, order, radius, dtype=weights_dtype)
return _run_1d_correlates(input, list(zip(sigmas, orders)), get, output,
mode, cval, 0)
def _gaussian_kernel1d(sigma, order, radius, dtype=cupy.float64):
"""
Computes a 1-D Gaussian correlation kernel.
"""
if order < 0:
raise ValueError('order must be non-negative')
sigma2 = sigma * sigma
x = numpy.arange(-radius, radius+1)
phi_x = numpy.exp(-0.5 / sigma2 * x ** 2)
phi_x /= phi_x.sum()
if order == 0:
return cupy.asarray(phi_x)
# f(x) = q(x) * phi(x) = q(x) * exp(p(x))
# f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
# p'(x) = -1 / sigma ** 2
# Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
# coefficients of q(x)
exponent_range = numpy.arange(order + 1)
q = numpy.zeros(order + 1)
q[0] = 1
D = numpy.diag(exponent_range[1:], 1) # D @ q(x) = q'(x)
P = numpy.diag(numpy.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x)
Q_deriv = D + P
for _ in range(order):
q = Q_deriv.dot(q)
q = (x[:, None] ** exponent_range).dot(q)
return cupy.asarray((q * phi_x)[::-1], dtype=dtype)
def prewitt(input, axis=-1, output=None, mode="reflect", cval=0.0):
"""Compute a Prewitt filter along the given axis.
Args:
input (cupy.ndarray): The input array.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.prewitt`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
weights_dtype = _util._init_weights_dtype(input)
weights = cupy.ones(3, dtype=weights_dtype)
return _prewitt_or_sobel(input, axis, output, mode, cval, weights)
def sobel(input, axis=-1, output=None, mode="reflect", cval=0.0):
"""Compute a Sobel filter along the given axis.
Args:
input (cupy.ndarray): The input array.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.sobel`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
weights_dtype = _util._init_weights_dtype(input)
return _prewitt_or_sobel(input, axis, output, mode, cval,
cupy.array([1, 2, 1], dtype=weights_dtype))
def _prewitt_or_sobel(input, axis, output, mode, cval, weights):
axis = internal._normalize_axis_index(axis, input.ndim)
def get(is_diff):
return cupy.array([-1, 0, 1], dtype=weights.dtype) if is_diff else weights # noqa
return _run_1d_correlates(input, [a == axis for a in range(input.ndim)],
get, output, mode, cval)
def generic_laplace(input, derivative2, output=None, mode="reflect",
cval=0.0, extra_arguments=(), extra_keywords=None):
"""Multi-dimensional Laplace filter using a provided second derivative
function.
Args:
input (cupy.ndarray): The input array.
derivative2 (callable): Function or other callable with the following
signature that is called once per axis::
derivative2(input, axis, output, mode, cval,
*extra_arguments, **extra_keywords)
where ``input`` and ``output`` are ``cupy.ndarray``, ``axis`` is an
``int`` from ``0`` to the number of dimensions, and ``mode``,
``cval``, ``extra_arguments``, ``extra_keywords`` are the values
given to this function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
extra_arguments (sequence, optional):
Sequence of extra positional arguments to pass to ``derivative2``.
extra_keywords (dict, optional):
dict of extra keyword arguments to pass ``derivative2``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.generic_laplace`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
if extra_keywords is None:
extra_keywords = {}
ndim = input.ndim
modes = _util._fix_sequence_arg(mode, ndim, 'mode',
_util._check_mode)
output = _util._get_output(output, input)
if ndim == 0:
_core.elementwise_copy(input, output)
return output
derivative2(input, 0, output, modes[0], cval,
*extra_arguments, **extra_keywords)
if ndim > 1:
tmp = _util._get_output(output.dtype, input)
for i in range(1, ndim):
derivative2(input, i, tmp, modes[i], cval,
*extra_arguments, **extra_keywords)
output += tmp
return output
def laplace(input, output=None, mode="reflect", cval=0.0):
"""Multi-dimensional Laplace filter based on approximate second
derivatives.
Args:
input (cupy.ndarray): The input array.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.laplace`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
weights_dtype = _util._init_weights_dtype(input)
weights = cupy.array([1, -2, 1], dtype=weights_dtype)
def derivative2(input, axis, output, mode, cval):
return correlate1d(input, weights, axis, output, mode, cval)
return generic_laplace(input, derivative2, output, mode, cval)
def gaussian_laplace(input, sigma, output=None, mode="reflect",
cval=0.0, **kwargs):
"""Multi-dimensional Laplace filter using Gaussian second derivatives.
Args:
input (cupy.ndarray): The input array.
sigma (scalar or sequence of scalar): Standard deviations for each axis
of Gaussian kernel. A single value applies to all axes.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
kwargs (dict, optional):
dict of extra keyword arguments to pass ``gaussian_filter()``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.gaussian_laplace`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
def derivative2(input, axis, output, mode, cval):
order = [0] * input.ndim
order[axis] = 2
return gaussian_filter(input, sigma, order, output, mode, cval,
**kwargs)
return generic_laplace(input, derivative2, output, mode, cval)
def generic_gradient_magnitude(input, derivative, output=None,
mode="reflect", cval=0.0,
extra_arguments=(), extra_keywords=None):
"""Multi-dimensional gradient magnitude filter using a provided derivative
function.
Args:
input (cupy.ndarray): The input array.
derivative (callable): Function or other callable with the following
signature that is called once per axis::
derivative(input, axis, output, mode, cval,
*extra_arguments, **extra_keywords)
where ``input`` and ``output`` are ``cupy.ndarray``, ``axis`` is an
``int`` from ``0`` to the number of dimensions, and ``mode``,
``cval``, ``extra_arguments``, ``extra_keywords`` are the values
given to this function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
extra_arguments (sequence, optional):
Sequence of extra positional arguments to pass to ``derivative2``.
extra_keywords (dict, optional):
dict of extra keyword arguments to pass ``derivative2``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.generic_gradient_magnitude`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
if extra_keywords is None:
extra_keywords = {}
ndim = input.ndim
modes = _util._fix_sequence_arg(mode, ndim, 'mode',
_util._check_mode)
output = _util._get_output(output, input)
if ndim == 0:
_core.elementwise_copy(input, output)
return output
derivative(input, 0, output, modes[0], cval,
*extra_arguments, **extra_keywords)
output *= output
if ndim > 1:
tmp = _util._get_output(output.dtype, input)
for i in range(1, ndim):
derivative(input, i, tmp, modes[i], cval,
*extra_arguments, **extra_keywords)
tmp *= tmp
output += tmp
return cupy.sqrt(output, output, casting='unsafe')
def gaussian_gradient_magnitude(input, sigma, output=None, mode="reflect",
cval=0.0, **kwargs):
"""Multi-dimensional gradient magnitude using Gaussian derivatives.
Args:
input (cupy.ndarray): The input array.
sigma (scalar or sequence of scalar): Standard deviations for each axis
of Gaussian kernel. A single value applies to all axes.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
kwargs (dict, optional):
dict of extra keyword arguments to pass ``gaussian_filter()``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.gaussian_gradient_magnitude`
.. note::
When the output data type is integral (or when no output is provided
and input is integral) the results may not perfectly match the results
from SciPy due to floating-point rounding of intermediate results.
"""
def derivative(input, axis, output, mode, cval):
order = [0] * input.ndim
order[axis] = 1
return gaussian_filter(input, sigma, order, output, mode, cval,
**kwargs)
return generic_gradient_magnitude(input, derivative, output, mode, cval)
def minimum_filter(input, size=None, footprint=None, output=None,
mode="reflect", cval=0.0, origin=0):
"""Multi-dimensional minimum filter.
Args:
input (cupy.ndarray): The input array.
size (int or sequence of int): One of ``size`` or ``footprint`` must be
provided. If ``footprint`` is given, ``size`` is ignored. Otherwise
``footprint = cupy.ones(size)`` with ``size`` automatically made to
match the number of dimensions in ``input``.
footprint (cupy.ndarray): a boolean array which specifies which of the
elements within this shape will get passed to the filter function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int or sequence of int): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.minimum_filter`
"""
return _min_or_max_filter(input, size, footprint, None, output, mode,
cval, origin, 'min')
def maximum_filter(input, size=None, footprint=None, output=None,
mode="reflect", cval=0.0, origin=0):
"""Multi-dimensional maximum filter.
Args:
input (cupy.ndarray): The input array.
size (int or sequence of int): One of ``size`` or ``footprint`` must be
provided. If ``footprint`` is given, ``size`` is ignored. Otherwise
``footprint = cupy.ones(size)`` with ``size`` automatically made to
match the number of dimensions in ``input``.
footprint (cupy.ndarray): a boolean array which specifies which of the
elements within this shape will get passed to the filter function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int or sequence of int): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.maximum_filter`
"""
return _min_or_max_filter(input, size, footprint, None, output, mode,
cval, origin, 'max')
def _min_or_max_filter(input, size, ftprnt, structure, output, mode, cval,
origin, func):
# structure is used by morphology.grey_erosion() and grey_dilation()
# and not by the regular min/max filters
sizes, ftprnt, structure = _filters_core._check_size_footprint_structure(
input.ndim, size, ftprnt, structure)
if cval is cupy.nan:
raise NotImplementedError("NaN cval is unsupported")
if sizes is not None:
# Seperable filter, run as a series of 1D filters
fltr = minimum_filter1d if func == 'min' else maximum_filter1d
return _filters_core._run_1d_filters(
[fltr if size > 1 else None for size in sizes],
input, sizes, output, mode, cval, origin)
origins, int_type = _filters_core._check_nd_args(input, ftprnt,
mode, origin, 'footprint')
if structure is not None and structure.ndim != input.ndim:
raise RuntimeError('structure array has incorrect shape')
if ftprnt.size == 0:
return cupy.zeros_like(input)
offsets = _filters_core._origins_to_offsets(origins, ftprnt.shape)
kernel = _get_min_or_max_kernel(mode, ftprnt.shape, func,
offsets, float(cval), int_type,
has_structure=structure is not None,
has_central_value=bool(ftprnt[offsets]))
return _filters_core._call_kernel(kernel, input, ftprnt, output,
structure, weights_dtype=bool)
def minimum_filter1d(input, size, axis=-1, output=None, mode="reflect",
cval=0.0, origin=0):
"""Compute the minimum filter along a single axis.
Args:
input (cupy.ndarray): The input array.
size (int): Length of the minimum filter.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.minimum_filter1d`
"""
return _min_or_max_1d(input, size, axis, output, mode, cval, origin, 'min')
def maximum_filter1d(input, size, axis=-1, output=None, mode="reflect",
cval=0.0, origin=0):
"""Compute the maximum filter along a single axis.
Args:
input (cupy.ndarray): The input array.
size (int): Length of the maximum filter.
axis (int): The axis of input along which to calculate. Default is -1.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int): The origin parameter controls the placement of the
filter, relative to the center of the current element of the
input. Default is ``0``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.maximum_filter1d`
"""
return _min_or_max_1d(input, size, axis, output, mode, cval, origin, 'max')
def _min_or_max_1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0,
origin=0, func='min'):
ftprnt = cupy.ones(size, dtype=bool)
ftprnt, origin = _filters_core._convert_1d_args(input.ndim, ftprnt,
origin, axis)
origins, int_type = _filters_core._check_nd_args(input, ftprnt,
mode, origin, 'footprint')
offsets = _filters_core._origins_to_offsets(origins, ftprnt.shape)
kernel = _get_min_or_max_kernel(mode, ftprnt.shape, func, offsets,
float(cval), int_type, has_weights=False)
return _filters_core._call_kernel(kernel, input, None, output,
weights_dtype=bool)
@cupy._util.memoize(for_each_device=True)
def _get_min_or_max_kernel(mode, w_shape, func, offsets, cval, int_type,
has_weights=True, has_structure=False,
has_central_value=True):
# When there are no 'weights' (the footprint, for the 1D variants) then
# we need to make sure intermediate results are stored as doubles for
# consistent results with scipy.
ctype = 'X' if has_weights else 'double'
value = '{value}'
if not has_weights:
value = 'cast<double>({})'.format(value)
# Having a non-flat structure biases the values
if has_structure:
value += ('-' if func == 'min' else '+') + 'cast<X>(sval)'
if has_central_value:
pre = '{} value = x[i];'
found = 'value = {func}({value}, value);'
else:
# If the central pixel is not included in the footprint we cannot
# assume `x[i]` is not below the min or above the max and thus cannot
# seed with that value. Instead we keep track of having set `value`.
pre = '{} value; bool set = false;'
found = 'value = set ? {func}({value}, value) : {value}; set=true;'
return _filters_core._generate_nd_kernel(
func, pre.format(ctype),
found.format(func=func, value=value), 'y = cast<Y>(value);',
mode, w_shape, int_type, offsets, cval, ctype=ctype,
has_weights=has_weights, has_structure=has_structure)
def rank_filter(input, rank, size=None, footprint=None, output=None,
mode="reflect", cval=0.0, origin=0):
"""Multi-dimensional rank filter.
Args:
input (cupy.ndarray): The input array.
rank (int): The rank of the element to get. Can be negative to count
from the largest value, e.g. ``-1`` indicates the largest value.
size (int or sequence of int): One of ``size`` or ``footprint`` must be
provided. If ``footprint`` is given, ``size`` is ignored. Otherwise
``footprint = cupy.ones(size)`` with ``size`` automatically made to
match the number of dimensions in ``input``.
footprint (cupy.ndarray): a boolean array which specifies which of the
elements within this shape will get passed to the filter function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int or sequence of int): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.rank_filter`
"""
rank = int(rank)
return _rank_filter(input, lambda fs: rank+fs if rank < 0 else rank,
size, footprint, output, mode, cval, origin)
def median_filter(input, size=None, footprint=None, output=None,
mode="reflect", cval=0.0, origin=0):
"""Multi-dimensional median filter.
Args:
input (cupy.ndarray): The input array.
size (int or sequence of int): One of ``size`` or ``footprint`` must be
provided. If ``footprint`` is given, ``size`` is ignored. Otherwise
``footprint = cupy.ones(size)`` with ``size`` automatically made to
match the number of dimensions in ``input``.
footprint (cupy.ndarray): a boolean array which specifies which of the
elements within this shape will get passed to the filter function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int or sequence of int): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.median_filter`
"""
return _rank_filter(input, lambda fs: fs//2,
size, footprint, output, mode, cval, origin)
def percentile_filter(input, percentile, size=None, footprint=None,
output=None, mode="reflect", cval=0.0, origin=0):
"""Multi-dimensional percentile filter.
Args:
input (cupy.ndarray): The input array.
percentile (scalar): The percentile of the element to get (from ``0``
to ``100``). Can be negative, thus ``-20`` equals ``80``.
size (int or sequence of int): One of ``size`` or ``footprint`` must be
provided. If ``footprint`` is given, ``size`` is ignored. Otherwise
``footprint = cupy.ones(size)`` with ``size`` automatically made to
match the number of dimensions in ``input``.
footprint (cupy.ndarray): a boolean array which specifies which of the
elements within this shape will get passed to the filter function.
output (cupy.ndarray, dtype or None): The array in which to place the
output. Default is is same dtype as the input.
mode (str): The array borders are handled according to the given mode
(``'reflect'``, ``'constant'``, ``'nearest'``, ``'mirror'``,
``'wrap'``). Default is ``'reflect'``.
cval (scalar): Value to fill past edges of input if mode is
``'constant'``. Default is ``0.0``.
origin (int or sequence of int): The origin parameter controls the
placement of the filter, relative to the center of the current
element of the input. Default of 0 is equivalent to
``(0,)*input.ndim``.
Returns:
cupy.ndarray: The result of the filtering.
.. seealso:: :func:`scipy.ndimage.percentile_filter`
"""