scipy-doctest 1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2018 @@
1
+ Multidimensional image processing (`scipy.ndimage`)
2
+ ====================================================
3
+
4
+ .. moduleauthor:: Peter Verveer <verveer@users.sourceforge.net>
5
+
6
+ .. currentmodule:: scipy.ndimage
7
+
8
+ .. _ndimage-introduction:
9
+
10
+ Introduction
11
+ ------------
12
+
13
+ Image processing and analysis are generally seen as operations on
14
+ 2-D arrays of values. There are, however, a number of
15
+ fields where images of higher dimensionality must be analyzed. Good
16
+ examples of these are medical imaging and biological imaging.
17
+ :mod:`numpy` is suited very well for this type of applications due to
18
+ its inherent multidimensional nature. The :mod:`scipy.ndimage`
19
+ packages provides a number of general image processing and analysis
20
+ functions that are designed to operate with arrays of arbitrary
21
+ dimensionality. The packages currently includes: functions for
22
+ linear and non-linear filtering, binary morphology, B-spline
23
+ interpolation, and object measurements.
24
+
25
+ .. _ndimage-properties-shared-by-all-functions:
26
+
27
+ Properties shared by all functions
28
+ ----------------------------------
29
+
30
+ All functions share some common properties. Notably, all functions
31
+ allow the specification of an output array with the *output*
32
+ argument. With this argument, you can specify an array that will be
33
+ changed in-place with the result with the operation. In this case,
34
+ the result is not returned. Usually, using the *output* argument is
35
+ more efficient, since an existing array is used to store the
36
+ result.
37
+
38
+ The type of arrays returned is dependent on the type of operation,
39
+ but it is, in most cases, equal to the type of the input. If,
40
+ however, the *output* argument is used, the type of the result is
41
+ equal to the type of the specified output argument. If no output
42
+ argument is given, it is still possible to specify what the result
43
+ of the output should be. This is done by simply assigning the
44
+ desired `numpy` type object to the output argument. For example:
45
+
46
+ .. code:: python
47
+
48
+ >>> from scipy.ndimage import correlate
49
+ >>> import numpy as np
50
+ >>> correlate(np.arange(10), [1, 2.5])
51
+ array([ 0, 2, 6, 9, 13, 16, 20, 23, 27, 30])
52
+ >>> correlate(np.arange(10), [1, 2.5], output=np.float64)
53
+ array([ 0. , 2.5, 6. , 9.5, 13. , 16.5, 20. , 23.5, 27. , 30.5])
54
+
55
+ .. _ndimage-filter-functions:
56
+
57
+ Filter functions
58
+ ----------------
59
+
60
+ The functions described in this section all perform some type of spatial
61
+ filtering of the input array: the elements in the output are some function
62
+ of the values in the neighborhood of the corresponding input element. We refer
63
+ to this neighborhood of elements as the filter kernel, which is often
64
+ rectangular in shape but may also have an arbitrary footprint. Many
65
+ of the functions described below allow you to define the footprint
66
+ of the kernel by passing a mask through the *footprint* parameter.
67
+ For example, a cross-shaped kernel can be defined as follows:
68
+
69
+ .. code:: python
70
+
71
+ >>> footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
72
+ >>> footprint
73
+ array([[0, 1, 0],
74
+ [1, 1, 1],
75
+ [0, 1, 0]])
76
+
77
+ Usually, the origin of the kernel is at the center calculated by
78
+ dividing the dimensions of the kernel shape by two. For instance,
79
+ the origin of a 1-D kernel of length three is at the
80
+ second element. Take, for example, the correlation of a
81
+ 1-D array with a filter of length 3 consisting of
82
+ ones:
83
+
84
+ .. code:: python
85
+
86
+ >>> from scipy.ndimage import correlate1d
87
+ >>> a = [0, 0, 0, 1, 0, 0, 0]
88
+ >>> correlate1d(a, [1, 1, 1])
89
+ array([0, 0, 1, 1, 1, 0, 0])
90
+
91
+ Sometimes, it is convenient to choose a different origin for the
92
+ kernel. For this reason, most functions support the *origin*
93
+ parameter, which gives the origin of the filter relative to its
94
+ center. For example:
95
+
96
+ .. code:: python
97
+
98
+ >>> a = [0, 0, 0, 1, 0, 0, 0]
99
+ >>> correlate1d(a, [1, 1, 1], origin = -1)
100
+ array([0, 1, 1, 1, 0, 0, 0])
101
+
102
+ The effect is a shift of the result towards the left. This feature
103
+ will not be needed very often, but it may be useful, especially for
104
+ filters that have an even size. A good example is the calculation
105
+ of backward and forward differences:
106
+
107
+ .. code:: python
108
+
109
+ >>> a = [0, 0, 1, 1, 1, 0, 0]
110
+ >>> correlate1d(a, [-1, 1]) # backward difference
111
+ array([ 0, 0, 1, 0, 0, -1, 0])
112
+ >>> correlate1d(a, [-1, 1], origin = -1) # forward difference
113
+ array([ 0, 1, 0, 0, -1, 0, 0])
114
+
115
+ We could also have calculated the forward difference as follows:
116
+
117
+ .. code:: python
118
+
119
+ >>> correlate1d(a, [0, -1, 1])
120
+ array([ 0, 1, 0, 0, -1, 0, 0])
121
+
122
+ However, using the origin parameter instead of a larger kernel is
123
+ more efficient. For multidimensional kernels, *origin* can be a
124
+ number, in which case the origin is assumed to be equal along all
125
+ axes, or a sequence giving the origin along each axis.
126
+
127
+ Since the output elements are a function of elements in the
128
+ neighborhood of the input elements, the borders of the array need to
129
+ be dealt with appropriately by providing the values outside the
130
+ borders. This is done by assuming that the arrays are extended beyond
131
+ their boundaries according to certain boundary conditions. In the
132
+ functions described below, the boundary conditions can be selected
133
+ using the *mode* parameter, which must be a string with the name of the
134
+ boundary condition. The following boundary conditions are currently
135
+ supported:
136
+
137
+ ========== ==================================== ====================
138
+ **mode** **description** **example**
139
+ ========== ==================================== ====================
140
+ "nearest" use the value at the boundary [1 2 3]->[1 1 2 3 3]
141
+ "wrap" periodically replicate the array [1 2 3]->[3 1 2 3 1]
142
+ "reflect" reflect the array at the boundary [1 2 3]->[1 1 2 3 3]
143
+ "mirror" mirror the array at the boundary [1 2 3]->[2 1 2 3 2]
144
+ "constant" use a constant value, default is 0.0 [1 2 3]->[0 1 2 3 0]
145
+ ========== ==================================== ====================
146
+
147
+ The following synonyms are also supported for consistency with the
148
+ interpolation routines:
149
+
150
+ =============== =========================
151
+ **mode** **description**
152
+ =============== =========================
153
+ "grid-constant" equivalent to "constant"*
154
+ "grid-mirror" equivalent to "reflect"
155
+ "grid-wrap" equivalent to "wrap"
156
+ =============== =========================
157
+
158
+ \* "grid-constant" and "constant" are equivalent for filtering operations, but
159
+ have different behavior in interpolation functions. For API consistency, the
160
+ filtering functions accept either name.
161
+
162
+ The "constant" mode is special since it needs an additional parameter to
163
+ specify the constant value that should be used.
164
+
165
+ Note that modes mirror and reflect differ only in whether the sample at the
166
+ boundary is repeated upon reflection. For mode mirror, the point of symmetry is
167
+ exactly at the final sample, so that value is not repeated. This mode is also
168
+ known as whole-sample symmetric since the point of symmetry falls on the final
169
+ sample. Similarly, reflect is often referred to as half-sample symmetric as the
170
+ point of symmetry is half a sample beyond the array boundary.
171
+
172
+ .. note::
173
+
174
+ The easiest way to implement such boundary conditions would be to
175
+ copy the data to a larger array and extend the data at the borders
176
+ according to the boundary conditions. For large arrays and large
177
+ filter kernels, this would be very memory consuming, and the
178
+ functions described below, therefore, use a different approach that
179
+ does not require allocating large temporary buffers.
180
+
181
+ Correlation and convolution
182
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^
183
+
184
+ - The :func:`correlate1d` function calculates a 1-D
185
+ correlation along the given axis. The lines of the array along the
186
+ given axis are correlated with the given *weights*. The *weights*
187
+ parameter must be a 1-D sequence of numbers.
188
+
189
+ - The function :func:`correlate` implements multidimensional
190
+ correlation of the input array with a given kernel.
191
+
192
+ - The :func:`convolve1d` function calculates a 1-D
193
+ convolution along the given axis. The lines of the array along the
194
+ given axis are convoluted with the given *weights*. The *weights*
195
+ parameter must be a 1-D sequence of numbers.
196
+
197
+ - The function :func:`convolve` implements multidimensional
198
+ convolution of the input array with a given kernel.
199
+
200
+ .. note::
201
+
202
+ A convolution is essentially a correlation after mirroring the
203
+ kernel. As a result, the *origin* parameter behaves differently
204
+ than in the case of a correlation: the results is shifted in the
205
+ opposite direction.
206
+
207
+ .. _ndimage-filter-functions-smoothing:
208
+
209
+ Smoothing filters
210
+ ^^^^^^^^^^^^^^^^^
211
+
212
+ - The :func:`gaussian_filter1d` function implements a 1-D
213
+ Gaussian filter. The standard deviation of the Gaussian filter is
214
+ passed through the parameter *sigma*. Setting *order* = 0
215
+ corresponds to convolution with a Gaussian kernel. An order of 1, 2,
216
+ or 3 corresponds to convolution with the first, second, or third
217
+ derivatives of a Gaussian. Higher-order derivatives are not
218
+ implemented.
219
+
220
+
221
+
222
+ - The :func:`gaussian_filter` function implements a multidimensional
223
+ Gaussian filter. The standard deviations of the Gaussian filter
224
+ along each axis are passed through the parameter *sigma* as a
225
+ sequence or numbers. If *sigma* is not a sequence but a single
226
+ number, the standard deviation of the filter is equal along all
227
+ directions. The order of the filter can be specified separately for
228
+ each axis. An order of 0 corresponds to convolution with a Gaussian
229
+ kernel. An order of 1, 2, or 3 corresponds to convolution with the
230
+ first, second, or third derivatives of a Gaussian. Higher-order
231
+ derivatives are not implemented. The *order* parameter must be a
232
+ number, to specify the same order for all axes, or a sequence of
233
+ numbers to specify a different order for each axis. The example below
234
+ shows the filter applied on test data with different values of *sigma*.
235
+ The *order* parameter is kept at 0.
236
+
237
+ .. plot:: tutorial/examples/gaussian_filter_plot1.py
238
+ :align: center
239
+ :alt: " "
240
+ :include-source: 0
241
+
242
+ .. note::
243
+
244
+ The multidimensional filter is implemented as a sequence of
245
+ 1-D Gaussian filters. The intermediate arrays are
246
+ stored in the same data type as the output. Therefore, for
247
+ output types with a lower precision, the results may be imprecise
248
+ because intermediate results may be stored with insufficient
249
+ precision. This can be prevented by specifying a more precise
250
+ output type.
251
+
252
+ - The :func:`uniform_filter1d` function calculates a 1-D
253
+ uniform filter of the given *size* along the given axis.
254
+
255
+ - The :func:`uniform_filter` implements a multidimensional uniform
256
+ filter. The sizes of the uniform filter are given for each axis as a
257
+ sequence of integers by the *size* parameter. If *size* is not a
258
+ sequence, but a single number, the sizes along all axes are assumed
259
+ to be equal.
260
+
261
+ .. note::
262
+
263
+ The multidimensional filter is implemented as a sequence of
264
+ 1-D uniform filters. The intermediate arrays are
265
+ stored in the same data type as the output. Therefore, for output
266
+ types with a lower precision, the results may be imprecise
267
+ because intermediate results may be stored with insufficient
268
+ precision. This can be prevented by specifying a more precise
269
+ output type.
270
+
271
+ Filters based on order statistics
272
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
273
+
274
+ - The :func:`minimum_filter1d` function calculates a 1-D
275
+ minimum filter of the given *size* along the given axis.
276
+
277
+ - The :func:`maximum_filter1d` function calculates a 1-D
278
+ maximum filter of the given *size* along the given axis.
279
+
280
+ - The :func:`minimum_filter` function calculates a multidimensional
281
+ minimum filter. Either the sizes of a rectangular kernel or the
282
+ footprint of the kernel must be provided. The *size* parameter, if
283
+ provided, must be a sequence of sizes or a single number, in which
284
+ case the size of the filter is assumed to be equal along each axis.
285
+ The *footprint*, if provided, must be an array that defines the
286
+ shape of the kernel by its non-zero elements.
287
+
288
+ - The :func:`maximum_filter` function calculates a multidimensional
289
+ maximum filter. Either the sizes of a rectangular kernel or the
290
+ footprint of the kernel must be provided. The *size* parameter, if
291
+ provided, must be a sequence of sizes or a single number, in which
292
+ case the size of the filter is assumed to be equal along each axis.
293
+ The *footprint*, if provided, must be an array that defines the
294
+ shape of the kernel by its non-zero elements.
295
+
296
+ - The :func:`rank_filter` function calculates a multidimensional rank
297
+ filter. The *rank* may be less than zero, i.e., *rank* = -1
298
+ indicates the largest element. Either the sizes of a rectangular
299
+ kernel or the footprint of the kernel must be provided. The *size*
300
+ parameter, if provided, must be a sequence of sizes or a single
301
+ number, in which case the size of the filter is assumed to be equal
302
+ along each axis. The *footprint*, if provided, must be an array that
303
+ defines the shape of the kernel by its non-zero elements.
304
+
305
+ - The :func:`percentile_filter` function calculates a multidimensional
306
+ percentile filter. The *percentile* may be less than zero, i.e.,
307
+ *percentile* = -20 equals *percentile* = 80. Either the sizes of a
308
+ rectangular kernel or the footprint of the kernel must be provided.
309
+ The *size* parameter, if provided, must be a sequence of sizes or a
310
+ single number, in which case the size of the filter is assumed to be
311
+ equal along each axis. The *footprint*, if provided, must be an
312
+ array that defines the shape of the kernel by its non-zero elements.
313
+
314
+ - The :func:`median_filter` function calculates a multidimensional
315
+ median filter. Either the sizes of a rectangular kernel or the
316
+ footprint of the kernel must be provided. The *size* parameter, if
317
+ provided, must be a sequence of sizes or a single number, in which
318
+ case the size of the filter is assumed to be equal along each
319
+ axis. The *footprint* if provided, must be an array that defines the
320
+ shape of the kernel by its non-zero elements.
321
+
322
+ Derivatives
323
+ ^^^^^^^^^^^
324
+
325
+ Derivative filters can be constructed in several ways. The function
326
+ :func:`gaussian_filter1d`, described in
327
+ :ref:`ndimage-filter-functions-smoothing`, can be used to calculate
328
+ derivatives along a given axis using the *order* parameter. Other
329
+ derivative filters are the Prewitt and Sobel filters:
330
+
331
+ - The :func:`prewitt` function calculates a derivative along the given
332
+ axis.
333
+ - The :func:`sobel` function calculates a derivative along the given
334
+ axis.
335
+
336
+ The Laplace filter is calculated by the sum of the second derivatives
337
+ along all axes. Thus, different Laplace filters can be constructed
338
+ using different second-derivative functions. Therefore, we provide a
339
+ general function that takes a function argument to calculate the
340
+ second derivative along a given direction.
341
+
342
+ - The function :func:`generic_laplace` calculates a Laplace filter
343
+ using the function passed through ``derivative2`` to calculate
344
+ second derivatives. The function ``derivative2`` should have the
345
+ following signature
346
+
347
+ .. code:: python
348
+
349
+ derivative2(input, axis, output, mode, cval, *extra_arguments, **extra_keywords)
350
+
351
+ It should calculate the second derivative along the dimension
352
+ *axis*. If *output* is not ``None``, it should use that for the
353
+ output and return ``None``, otherwise it should return the
354
+ result. *mode*, *cval* have the usual meaning.
355
+
356
+ The *extra_arguments* and *extra_keywords* arguments can be used
357
+ to pass a tuple of extra arguments and a dictionary of named
358
+ arguments that are passed to ``derivative2`` at each call.
359
+
360
+ For example
361
+
362
+ .. code:: python
363
+
364
+ >>> def d2(input, axis, output, mode, cval):
365
+ ... return correlate1d(input, [1, -2, 1], axis, output, mode, cval, 0)
366
+ ...
367
+ >>> a = np.zeros((5, 5))
368
+ >>> a[2, 2] = 1
369
+ >>> from scipy.ndimage import generic_laplace
370
+ >>> generic_laplace(a, d2)
371
+ array([[ 0., 0., 0., 0., 0.],
372
+ [ 0., 0., 1., 0., 0.],
373
+ [ 0., 1., -4., 1., 0.],
374
+ [ 0., 0., 1., 0., 0.],
375
+ [ 0., 0., 0., 0., 0.]])
376
+
377
+ To demonstrate the use of the *extra_arguments* argument, we could do
378
+
379
+ .. code:: python
380
+
381
+ >>> def d2(input, axis, output, mode, cval, weights):
382
+ ... return correlate1d(input, weights, axis, output, mode, cval, 0,)
383
+ ...
384
+ >>> a = np.zeros((5, 5))
385
+ >>> a[2, 2] = 1
386
+ >>> generic_laplace(a, d2, extra_arguments = ([1, -2, 1],))
387
+ array([[ 0., 0., 0., 0., 0.],
388
+ [ 0., 0., 1., 0., 0.],
389
+ [ 0., 1., -4., 1., 0.],
390
+ [ 0., 0., 1., 0., 0.],
391
+ [ 0., 0., 0., 0., 0.]])
392
+
393
+ or
394
+
395
+ .. code:: python
396
+
397
+ >>> generic_laplace(a, d2, extra_keywords = {'weights': [1, -2, 1]})
398
+ array([[ 0., 0., 0., 0., 0.],
399
+ [ 0., 0., 1., 0., 0.],
400
+ [ 0., 1., -4., 1., 0.],
401
+ [ 0., 0., 1., 0., 0.],
402
+ [ 0., 0., 0., 0., 0.]])
403
+
404
+ The following two functions are implemented using
405
+ :func:`generic_laplace` by providing appropriate functions for the
406
+ second-derivative function:
407
+
408
+ - The function :func:`laplace` calculates the Laplace using discrete
409
+ differentiation for the second derivative (i.e., convolution with
410
+ ``[1, -2, 1]``).
411
+
412
+ - The function :func:`gaussian_laplace` calculates the Laplace filter
413
+ using :func:`gaussian_filter` to calculate the second
414
+ derivatives. The standard deviations of the Gaussian filter along
415
+ each axis are passed through the parameter *sigma* as a sequence or
416
+ numbers. If *sigma* is not a sequence but a single number, the
417
+ standard deviation of the filter is equal along all directions.
418
+
419
+ The gradient magnitude is defined as the square root of the sum of the
420
+ squares of the gradients in all directions. Similar to the generic
421
+ Laplace function, there is a :func:`generic_gradient_magnitude`
422
+ function that calculates the gradient magnitude of an array.
423
+
424
+ - The function :func:`generic_gradient_magnitude` calculates a
425
+ gradient magnitude using the function passed through
426
+ ``derivative`` to calculate first derivatives. The function
427
+ ``derivative`` should have the following signature
428
+
429
+ .. code:: python
430
+
431
+ derivative(input, axis, output, mode, cval, *extra_arguments, **extra_keywords)
432
+
433
+ It should calculate the derivative along the dimension *axis*. If
434
+ *output* is not ``None``, it should use that for the output and return
435
+ ``None``, otherwise it should return the result. *mode*, *cval* have the
436
+ usual meaning.
437
+
438
+ The *extra_arguments* and *extra_keywords* arguments can be used to
439
+ pass a tuple of extra arguments and a dictionary of named arguments
440
+ that are passed to *derivative* at each call.
441
+
442
+ For example, the :func:`sobel` function fits the required signature
443
+
444
+ .. code:: python
445
+
446
+ >>> a = np.zeros((5, 5))
447
+ >>> a[2, 2] = 1
448
+ >>> from scipy.ndimage import sobel, generic_gradient_magnitude
449
+ >>> generic_gradient_magnitude(a, sobel)
450
+ array([[ 0. , 0. , 0. , 0. , 0. ],
451
+ [ 0. , 1.41421356, 2. , 1.41421356, 0. ],
452
+ [ 0. , 2. , 0. , 2. , 0. ],
453
+ [ 0. , 1.41421356, 2. , 1.41421356, 0. ],
454
+ [ 0. , 0. , 0. , 0. , 0. ]])
455
+
456
+ See the documentation of :func:`generic_laplace` for examples of
457
+ using the *extra_arguments* and *extra_keywords* arguments.
458
+
459
+ The :func:`sobel` and :func:`prewitt` functions fit the required
460
+ signature and can, therefore, be used directly with
461
+ :func:`generic_gradient_magnitude`.
462
+
463
+ - The function :func:`gaussian_gradient_magnitude` calculates the
464
+ gradient magnitude using :func:`gaussian_filter` to calculate the
465
+ first derivatives. The standard deviations of the Gaussian filter
466
+ along each axis are passed through the parameter *sigma* as a
467
+ sequence or numbers. If *sigma* is not a sequence but a single
468
+ number, the standard deviation of the filter is equal along all
469
+ directions.
470
+
471
+ .. _ndimage-genericfilters:
472
+
473
+ Generic filter functions
474
+ ^^^^^^^^^^^^^^^^^^^^^^^^
475
+
476
+ To implement filter functions, generic functions can be used that
477
+ accept a callable object that implements the filtering operation. The
478
+ iteration over the input and output arrays is handled by these generic
479
+ functions, along with such details as the implementation of the
480
+ boundary conditions. Only a callable object implementing a callback
481
+ function that does the actual filtering work must be provided. The
482
+ callback function can also be written in C and passed using a
483
+ :c:type:`PyCapsule` (see :ref:`ndimage-ccallbacks` for more
484
+ information).
485
+
486
+ - The :func:`generic_filter1d` function implements a generic
487
+ 1-D filter function, where the actual filtering
488
+ operation must be supplied as a python function (or other callable
489
+ object). The :func:`generic_filter1d` function iterates over the
490
+ lines of an array and calls ``function`` at each line. The
491
+ arguments that are passed to ``function`` are 1-D
492
+ arrays of the ``numpy.float64`` type. The first contains the values
493
+ of the current line. It is extended at the beginning and the end,
494
+ according to the *filter_size* and *origin* arguments. The second
495
+ array should be modified in-place to provide the output values of
496
+ the line. For example, consider a correlation along one dimension:
497
+
498
+ .. code:: python
499
+
500
+ >>> a = np.arange(12).reshape(3,4)
501
+ >>> correlate1d(a, [1, 2, 3])
502
+ array([[ 3, 8, 14, 17],
503
+ [27, 32, 38, 41],
504
+ [51, 56, 62, 65]])
505
+
506
+ The same operation can be implemented using :func:`generic_filter1d`,
507
+ as follows:
508
+
509
+ .. code:: python
510
+
511
+ >>> def fnc(iline, oline):
512
+ ... oline[...] = iline[:-2] + 2 * iline[1:-1] + 3 * iline[2:]
513
+ ...
514
+ >>> from scipy.ndimage import generic_filter1d
515
+ >>> generic_filter1d(a, fnc, 3)
516
+ array([[ 3, 8, 14, 17],
517
+ [27, 32, 38, 41],
518
+ [51, 56, 62, 65]])
519
+
520
+ Here, the origin of the kernel was (by default) assumed to be in the
521
+ middle of the filter of length 3. Therefore, each input line had been
522
+ extended by one value at the beginning and at the end, before the
523
+ function was called.
524
+
525
+ Optionally, extra arguments can be defined and passed to the filter
526
+ function. The *extra_arguments* and *extra_keywords* arguments can
527
+ be used to pass a tuple of extra arguments and/or a dictionary of
528
+ named arguments that are passed to derivative at each call. For
529
+ example, we can pass the parameters of our filter as an argument
530
+
531
+ .. code:: python
532
+
533
+ >>> def fnc(iline, oline, a, b):
534
+ ... oline[...] = iline[:-2] + a * iline[1:-1] + b * iline[2:]
535
+ ...
536
+ >>> generic_filter1d(a, fnc, 3, extra_arguments = (2, 3))
537
+ array([[ 3, 8, 14, 17],
538
+ [27, 32, 38, 41],
539
+ [51, 56, 62, 65]])
540
+
541
+ or
542
+
543
+ .. code:: python
544
+
545
+ >>> generic_filter1d(a, fnc, 3, extra_keywords = {'a':2, 'b':3})
546
+ array([[ 3, 8, 14, 17],
547
+ [27, 32, 38, 41],
548
+ [51, 56, 62, 65]])
549
+
550
+ - The :func:`generic_filter` function implements a generic filter
551
+ function, where the actual filtering operation must be supplied as a
552
+ python function (or other callable object). The
553
+ :func:`generic_filter` function iterates over the array and calls
554
+ ``function`` at each element. The argument of ``function``
555
+ is a 1-D array of the ``numpy.float64`` type that
556
+ contains the values around the current element that are within the
557
+ footprint of the filter. The function should return a single value
558
+ that can be converted to a double precision number. For example,
559
+ consider a correlation:
560
+
561
+ .. code:: python
562
+
563
+ >>> a = np.arange(12).reshape(3,4)
564
+ >>> correlate(a, [[1, 0], [0, 3]])
565
+ array([[ 0, 3, 7, 11],
566
+ [12, 15, 19, 23],
567
+ [28, 31, 35, 39]])
568
+
569
+ The same operation can be implemented using *generic_filter*, as
570
+ follows:
571
+
572
+ .. code:: python
573
+
574
+ >>> def fnc(buffer):
575
+ ... return (buffer * np.array([1, 3])).sum()
576
+ ...
577
+ >>> from scipy.ndimage import generic_filter
578
+ >>> generic_filter(a, fnc, footprint = [[1, 0], [0, 1]])
579
+ array([[ 0, 3, 7, 11],
580
+ [12, 15, 19, 23],
581
+ [28, 31, 35, 39]])
582
+
583
+ Here, a kernel footprint was specified that contains only two
584
+ elements. Therefore, the filter function receives a buffer of length
585
+ equal to two, which was multiplied with the proper weights and the
586
+ result summed.
587
+
588
+ When calling :func:`generic_filter`, either the sizes of a
589
+ rectangular kernel or the footprint of the kernel must be
590
+ provided. The *size* parameter, if provided, must be a sequence of
591
+ sizes or a single number, in which case the size of the filter is
592
+ assumed to be equal along each axis. The *footprint*, if provided,
593
+ must be an array that defines the shape of the kernel by its
594
+ non-zero elements.
595
+
596
+ Optionally, extra arguments can be defined and passed to the filter
597
+ function. The *extra_arguments* and *extra_keywords* arguments can
598
+ be used to pass a tuple of extra arguments and/or a dictionary of
599
+ named arguments that are passed to derivative at each call. For
600
+ example, we can pass the parameters of our filter as an argument
601
+
602
+ .. code:: python
603
+
604
+ >>> def fnc(buffer, weights):
605
+ ... weights = np.asarray(weights)
606
+ ... return (buffer * weights).sum()
607
+ ...
608
+ >>> generic_filter(a, fnc, footprint = [[1, 0], [0, 1]], extra_arguments = ([1, 3],))
609
+ array([[ 0, 3, 7, 11],
610
+ [12, 15, 19, 23],
611
+ [28, 31, 35, 39]])
612
+
613
+ or
614
+
615
+ .. code:: python
616
+
617
+ >>> generic_filter(a, fnc, footprint = [[1, 0], [0, 1]], extra_keywords= {'weights': [1, 3]})
618
+ array([[ 0, 3, 7, 11],
619
+ [12, 15, 19, 23],
620
+ [28, 31, 35, 39]])
621
+
622
+ These functions iterate over the lines or elements starting at the
623
+ last axis, i.e., the last index changes the fastest. This order of
624
+ iteration is guaranteed for the case that it is important to adapt the
625
+ filter depending on spatial location. Here is an example of using a
626
+ class that implements the filter and keeps track of the current
627
+ coordinates while iterating. It performs the same filter operation as
628
+ described above for :func:`generic_filter`, but additionally prints
629
+ the current coordinates:
630
+
631
+ .. code:: python
632
+
633
+ >>> a = np.arange(12).reshape(3,4)
634
+ >>>
635
+ >>> class fnc_class:
636
+ ... def __init__(self, shape):
637
+ ... # store the shape:
638
+ ... self.shape = shape
639
+ ... # initialize the coordinates:
640
+ ... self.coordinates = [0] * len(shape)
641
+ ...
642
+ ... def filter(self, buffer):
643
+ ... result = (buffer * np.array([1, 3])).sum()
644
+ ... print(self.coordinates)
645
+ ... # calculate the next coordinates:
646
+ ... axes = list(range(len(self.shape)))
647
+ ... axes.reverse()
648
+ ... for jj in axes:
649
+ ... if self.coordinates[jj] < self.shape[jj] - 1:
650
+ ... self.coordinates[jj] += 1
651
+ ... break
652
+ ... else:
653
+ ... self.coordinates[jj] = 0
654
+ ... return result
655
+ ...
656
+ >>> fnc = fnc_class(shape = (3,4))
657
+ >>> generic_filter(a, fnc.filter, footprint = [[1, 0], [0, 1]])
658
+ [0, 0]
659
+ [0, 1]
660
+ [0, 2]
661
+ [0, 3]
662
+ [1, 0]
663
+ [1, 1]
664
+ [1, 2]
665
+ [1, 3]
666
+ [2, 0]
667
+ [2, 1]
668
+ [2, 2]
669
+ [2, 3]
670
+ array([[ 0, 3, 7, 11],
671
+ [12, 15, 19, 23],
672
+ [28, 31, 35, 39]])
673
+
674
+ For the :func:`generic_filter1d` function, the same approach works,
675
+ except that this function does not iterate over the axis that is being
676
+ filtered. The example for :func:`generic_filter1d` then becomes this:
677
+
678
+ .. code:: python
679
+
680
+ >>> a = np.arange(12).reshape(3,4)
681
+ >>>
682
+ >>> class fnc1d_class:
683
+ ... def __init__(self, shape, axis = -1):
684
+ ... # store the filter axis:
685
+ ... self.axis = axis
686
+ ... # store the shape:
687
+ ... self.shape = shape
688
+ ... # initialize the coordinates:
689
+ ... self.coordinates = [0] * len(shape)
690
+ ...
691
+ ... def filter(self, iline, oline):
692
+ ... oline[...] = iline[:-2] + 2 * iline[1:-1] + 3 * iline[2:]
693
+ ... print(self.coordinates)
694
+ ... # calculate the next coordinates:
695
+ ... axes = list(range(len(self.shape)))
696
+ ... # skip the filter axis:
697
+ ... del axes[self.axis]
698
+ ... axes.reverse()
699
+ ... for jj in axes:
700
+ ... if self.coordinates[jj] < self.shape[jj] - 1:
701
+ ... self.coordinates[jj] += 1
702
+ ... break
703
+ ... else:
704
+ ... self.coordinates[jj] = 0
705
+ ...
706
+ >>> fnc = fnc1d_class(shape = (3,4))
707
+ >>> generic_filter1d(a, fnc.filter, 3)
708
+ [0, 0]
709
+ [1, 0]
710
+ [2, 0]
711
+ array([[ 3, 8, 14, 17],
712
+ [27, 32, 38, 41],
713
+ [51, 56, 62, 65]])
714
+
715
+ Fourier domain filters
716
+ ^^^^^^^^^^^^^^^^^^^^^^
717
+
718
+ The functions described in this section perform filtering
719
+ operations in the Fourier domain. Thus, the input array of such a
720
+ function should be compatible with an inverse Fourier transform
721
+ function, such as the functions from the :mod:`numpy.fft` module. We,
722
+ therefore, have to deal with arrays that may be the result of a real
723
+ or a complex Fourier transform. In the case of a real Fourier
724
+ transform, only half of the of the symmetric complex transform is
725
+ stored. Additionally, it needs to be known what the length of the
726
+ axis was that was transformed by the real fft. The functions
727
+ described here provide a parameter *n* that, in the case of a real
728
+ transform, must be equal to the length of the real transform axis
729
+ before transformation. If this parameter is less than zero, it is
730
+ assumed that the input array was the result of a complex Fourier
731
+ transform. The parameter *axis* can be used to indicate along which
732
+ axis the real transform was executed.
733
+
734
+ - The :func:`fourier_shift` function multiplies the input array with
735
+ the multidimensional Fourier transform of a shift operation for the
736
+ given shift. The *shift* parameter is a sequence of shifts for each
737
+ dimension or a single value for all dimensions.
738
+
739
+ - The :func:`fourier_gaussian` function multiplies the input array
740
+ with the multidimensional Fourier transform of a Gaussian filter
741
+ with given standard deviations *sigma*. The *sigma* parameter is a
742
+ sequence of values for each dimension or a single value for all
743
+ dimensions.
744
+
745
+ - The :func:`fourier_uniform` function multiplies the input array with
746
+ the multidimensional Fourier transform of a uniform filter with
747
+ given sizes *size*. The *size* parameter is a sequence of values
748
+ for each dimension or a single value for all dimensions.
749
+
750
+ - The :func:`fourier_ellipsoid` function multiplies the input array
751
+ with the multidimensional Fourier transform of an elliptically-shaped
752
+ filter with given sizes *size*. The *size* parameter is a sequence
753
+ of values for each dimension or a single value for all dimensions.
754
+ This function is only implemented for dimensions 1, 2, and 3.
755
+
756
+ .. _ndimage-interpolation:
757
+
758
+ Interpolation functions
759
+ -----------------------
760
+
761
+ This section describes various interpolation functions that are based
762
+ on B-spline theory. A good introduction to B-splines can be found
763
+ in [1]_ with detailed algorithms for image interpolation given in [5]_.
764
+
765
+ Spline pre-filters
766
+ ^^^^^^^^^^^^^^^^^^
767
+
768
+ Interpolation using splines of an order larger than 1 requires a
769
+ pre-filtering step. The interpolation functions described in section
770
+ :ref:`ndimage-interpolation` apply pre-filtering by calling
771
+ :func:`spline_filter`, but they can be instructed not to do this by
772
+ setting the *prefilter* keyword equal to False. This is useful if more
773
+ than one interpolation operation is done on the same array. In this
774
+ case, it is more efficient to do the pre-filtering only once and use a
775
+ pre-filtered array as the input of the interpolation functions. The
776
+ following two functions implement the pre-filtering:
777
+
778
+ - The :func:`spline_filter1d` function calculates a 1-D
779
+ spline filter along the given axis. An output array can optionally
780
+ be provided. The order of the spline must be larger than 1 and less
781
+ than 6.
782
+
783
+ - The :func:`spline_filter` function calculates a multidimensional
784
+ spline filter.
785
+
786
+ .. note::
787
+
788
+ The multidimensional filter is implemented as a sequence of
789
+ 1-D spline filters. The intermediate arrays are
790
+ stored in the same data type as the output. Therefore, if an
791
+ output with a limited precision is requested, the results may be
792
+ imprecise because intermediate results may be stored with
793
+ insufficient precision. This can be prevented by specifying a
794
+ output type of high precision.
795
+
796
+ .. _ndimage-interpolation-modes:
797
+
798
+ Interpolation boundary handling
799
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
800
+
801
+ The interpolation functions all employ spline interpolation to effect some
802
+ type of geometric transformation of the input array. This requires a
803
+ mapping of the output coordinates to the input coordinates, and
804
+ therefore, the possibility arises that input values outside the
805
+ boundaries may be needed. This problem is solved in the same way as
806
+ described in :ref:`ndimage-filter-functions` for the multidimensional
807
+ filter functions. Therefore, these functions all support a *mode*
808
+ parameter that determines how the boundaries are handled, and a *cval*
809
+ parameter that gives a constant value in case that the 'constant' mode
810
+ is used. The behavior of all modes, including at non-integer locations is
811
+ illustrated below. Note the boundaries are not handled the same for all modes;
812
+ `reflect` (aka `grid-mirror`) and `grid-wrap` involve symmetry or repetition
813
+ about a point that is half way between image samples (dashed vertical lines)
814
+ while modes `mirror` and `wrap` treat the image as if it's extent ends exactly
815
+ at the first and last sample point rather than 0.5 samples past it.
816
+
817
+ .. plot:: tutorial/examples/plot_boundary_modes.py
818
+ :alt: " "
819
+ :include-source: False
820
+
821
+ The coordinates of image samples fall on integer sampling locations
822
+ in the range from 0 to ``shape[i] - 1`` along each axis, ``i``. The figure
823
+ below illustrates the interpolation of a point at location ``(3.7, 3.3)``
824
+ within an image of shape ``(7, 7)``. For an interpolation of order ``n``,
825
+ ``n + 1`` samples are involved along each axis. The filled circles
826
+ illustrate the sampling locations involved in the interpolation of the value at
827
+ the location of the red x.
828
+
829
+ .. plot:: tutorial/examples/plot_interp_grid.py
830
+ :alt: " "
831
+ :include-source: False
832
+
833
+
834
+ Interpolation functions
835
+ ^^^^^^^^^^^^^^^^^^^^^^^
836
+
837
+ - The :func:`geometric_transform` function applies an arbitrary
838
+ geometric transform to the input. The given *mapping* function is
839
+ called at each point in the output to find the corresponding
840
+ coordinates in the input. *mapping* must be a callable object that
841
+ accepts a tuple of length equal to the output array rank and returns
842
+ the corresponding input coordinates as a tuple of length equal to
843
+ the input array rank. The output shape and output type can
844
+ optionally be provided. If not given, they are equal to the input
845
+ shape and type.
846
+
847
+ For example:
848
+
849
+ .. code:: python
850
+
851
+ >>> a = np.arange(12).reshape(4,3).astype(np.float64)
852
+ >>> def shift_func(output_coordinates):
853
+ ... return (output_coordinates[0] - 0.5, output_coordinates[1] - 0.5)
854
+ ...
855
+ >>> from scipy.ndimage import geometric_transform
856
+ >>> geometric_transform(a, shift_func)
857
+ array([[ 0. , 0. , 0. ],
858
+ [ 0. , 1.3625, 2.7375],
859
+ [ 0. , 4.8125, 6.1875],
860
+ [ 0. , 8.2625, 9.6375]])
861
+
862
+ Optionally, extra arguments can be defined and passed to the filter
863
+ function. The *extra_arguments* and *extra_keywords* arguments can
864
+ be used to pass a tuple of extra arguments and/or a dictionary of
865
+ named arguments that are passed to derivative at each call. For
866
+ example, we can pass the shifts in our example as arguments
867
+
868
+ .. code:: python
869
+
870
+ >>> def shift_func(output_coordinates, s0, s1):
871
+ ... return (output_coordinates[0] - s0, output_coordinates[1] - s1)
872
+ ...
873
+ >>> geometric_transform(a, shift_func, extra_arguments = (0.5, 0.5))
874
+ array([[ 0. , 0. , 0. ],
875
+ [ 0. , 1.3625, 2.7375],
876
+ [ 0. , 4.8125, 6.1875],
877
+ [ 0. , 8.2625, 9.6375]])
878
+
879
+ or
880
+
881
+ .. code:: python
882
+
883
+ >>> geometric_transform(a, shift_func, extra_keywords = {'s0': 0.5, 's1': 0.5})
884
+ array([[ 0. , 0. , 0. ],
885
+ [ 0. , 1.3625, 2.7375],
886
+ [ 0. , 4.8125, 6.1875],
887
+ [ 0. , 8.2625, 9.6375]])
888
+
889
+ .. note::
890
+
891
+ The mapping function can also be written in C and passed using a
892
+ `scipy.LowLevelCallable`. See :ref:`ndimage-ccallbacks` for more
893
+ information.
894
+
895
+ - The function :func:`map_coordinates` applies an arbitrary coordinate
896
+ transformation using the given array of coordinates. The shape of
897
+ the output is derived from that of the coordinate array by dropping
898
+ the first axis. The parameter *coordinates* is used to find for each
899
+ point in the output the corresponding coordinates in the input. The
900
+ values of *coordinates* along the first axis are the coordinates in
901
+ the input array at which the output value is found. (See also the
902
+ numarray `coordinates` function.) Since the coordinates may be non-
903
+ integer coordinates, the value of the input at these coordinates is
904
+ determined by spline interpolation of the requested order.
905
+
906
+ Here is an example that interpolates a 2D array at ``(0.5, 0.5)`` and
907
+ ``(1, 2)``:
908
+
909
+ .. code:: python
910
+
911
+ >>> a = np.arange(12).reshape(4,3).astype(np.float64)
912
+ >>> a
913
+ array([[ 0., 1., 2.],
914
+ [ 3., 4., 5.],
915
+ [ 6., 7., 8.],
916
+ [ 9., 10., 11.]])
917
+ >>> from scipy.ndimage import map_coordinates
918
+ >>> map_coordinates(a, [[0.5, 2], [0.5, 1]])
919
+ array([ 1.3625, 7.])
920
+
921
+ - The :func:`affine_transform` function applies an affine
922
+ transformation to the input array. The given transformation *matrix*
923
+ and *offset* are used to find for each point in the output the
924
+ corresponding coordinates in the input. The value of the input at
925
+ the calculated coordinates is determined by spline interpolation of
926
+ the requested order. The transformation *matrix* must be
927
+ 2-D or can also be given as a 1-D sequence
928
+ or array. In the latter case, it is assumed that the matrix is
929
+ diagonal. A more efficient interpolation algorithm is then applied
930
+ that exploits the separability of the problem. The output shape and
931
+ output type can optionally be provided. If not given, they are equal
932
+ to the input shape and type.
933
+
934
+ - The :func:`shift` function returns a shifted version of the input,
935
+ using spline interpolation of the requested *order*.
936
+
937
+ - The :func:`zoom` function returns a rescaled version of the input,
938
+ using spline interpolation of the requested *order*.
939
+
940
+ - The :func:`rotate` function returns the input array rotated in the
941
+ plane defined by the two axes given by the parameter *axes*, using
942
+ spline interpolation of the requested *order*. The angle must be
943
+ given in degrees. If *reshape* is true, then the size of the output
944
+ array is adapted to contain the rotated input.
945
+
946
+ .. _ndimage-morphology:
947
+
948
+ Morphology
949
+ ----------
950
+
951
+ .. _ndimage-binary-morphology:
952
+
953
+ Binary morphology
954
+ ^^^^^^^^^^^^^^^^^
955
+
956
+ - The :func:`generate_binary_structure` functions generates a binary
957
+ structuring element for use in binary morphology operations. The
958
+ *rank* of the structure must be provided. The size of the structure
959
+ that is returned is equal to three in each direction. The value of
960
+ each element is equal to one if the square of the Euclidean distance
961
+ from the element to the center is less than or equal to
962
+ *connectivity*. For instance, 2-D 4-connected and
963
+ 8-connected structures are generated as follows:
964
+
965
+ .. code:: python
966
+
967
+ >>> from scipy.ndimage import generate_binary_structure
968
+ >>> generate_binary_structure(2, 1)
969
+ array([[False, True, False],
970
+ [ True, True, True],
971
+ [False, True, False]], dtype=bool)
972
+ >>> generate_binary_structure(2, 2)
973
+ array([[ True, True, True],
974
+ [ True, True, True],
975
+ [ True, True, True]], dtype=bool)
976
+
977
+ This is a visual presentation of `generate_binary_structure` in 3D:
978
+
979
+ .. plot:: tutorial/examples/ndimage/3D_binary_structure.py
980
+ :align: center
981
+ :alt: " "
982
+ :include-source: 0
983
+
984
+ Most binary morphology functions can be expressed in terms of the
985
+ basic operations erosion and dilation, which can be seen here:
986
+
987
+ .. plot:: tutorial/examples/morphology_binary_dilation_erosion.py
988
+ :align: center
989
+ :alt: " "
990
+ :include-source: 0
991
+
992
+ - The :func:`binary_erosion` function implements binary erosion of
993
+ arrays of arbitrary rank with the given structuring element. The
994
+ origin parameter controls the placement of the structuring element,
995
+ as described in :ref:`ndimage-filter-functions`. If no structuring
996
+ element is provided, an element with connectivity equal to one is
997
+ generated using :func:`generate_binary_structure`. The
998
+ *border_value* parameter gives the value of the array outside
999
+ boundaries. The erosion is repeated *iterations* times. If
1000
+ *iterations* is less than one, the erosion is repeated until the
1001
+ result does not change anymore. If a *mask* array is given, only
1002
+ those elements with a true value at the corresponding mask element
1003
+ are modified at each iteration.
1004
+
1005
+ - The :func:`binary_dilation` function implements binary dilation of
1006
+ arrays of arbitrary rank with the given structuring element. The
1007
+ origin parameter controls the placement of the structuring element,
1008
+ as described in :ref:`ndimage-filter-functions`. If no structuring
1009
+ element is provided, an element with connectivity equal to one is
1010
+ generated using :func:`generate_binary_structure`. The
1011
+ *border_value* parameter gives the value of the array outside
1012
+ boundaries. The dilation is repeated *iterations* times. If
1013
+ *iterations* is less than one, the dilation is repeated until the
1014
+ result does not change anymore. If a *mask* array is given, only
1015
+ those elements with a true value at the corresponding mask element
1016
+ are modified at each iteration.
1017
+
1018
+ Here is an example of using :func:`binary_dilation` to find all elements
1019
+ that touch the border, by repeatedly dilating an empty array from
1020
+ the border using the data array as the mask:
1021
+
1022
+ .. code:: python
1023
+
1024
+ >>> struct = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
1025
+ >>> a = np.array([[1,0,0,0,0], [1,1,0,1,0], [0,0,1,1,0], [0,0,0,0,0]])
1026
+ >>> a
1027
+ array([[1, 0, 0, 0, 0],
1028
+ [1, 1, 0, 1, 0],
1029
+ [0, 0, 1, 1, 0],
1030
+ [0, 0, 0, 0, 0]])
1031
+ >>> from scipy.ndimage import binary_dilation
1032
+ >>> binary_dilation(np.zeros(a.shape), struct, -1, a, border_value=1)
1033
+ array([[ True, False, False, False, False],
1034
+ [ True, True, False, False, False],
1035
+ [False, False, False, False, False],
1036
+ [False, False, False, False, False]], dtype=bool)
1037
+
1038
+ The :func:`binary_erosion` and :func:`binary_dilation` functions both
1039
+ have an *iterations* parameter, which allows the erosion or dilation to
1040
+ be repeated a number of times. Repeating an erosion or a dilation with
1041
+ a given structure *n* times is equivalent to an erosion or a dilation
1042
+ with a structure that is *n-1* times dilated with itself. A function
1043
+ is provided that allows the calculation of a structure that is dilated
1044
+ a number of times with itself:
1045
+
1046
+ - The :func:`iterate_structure` function returns a structure by dilation
1047
+ of the input structure *iteration* - 1 times with itself.
1048
+
1049
+ For instance:
1050
+
1051
+ .. code:: python
1052
+
1053
+ >>> struct = generate_binary_structure(2, 1)
1054
+ >>> struct
1055
+ array([[False, True, False],
1056
+ [ True, True, True],
1057
+ [False, True, False]], dtype=bool)
1058
+ >>> from scipy.ndimage import iterate_structure
1059
+ >>> iterate_structure(struct, 2)
1060
+ array([[False, False, True, False, False],
1061
+ [False, True, True, True, False],
1062
+ [ True, True, True, True, True],
1063
+ [False, True, True, True, False],
1064
+ [False, False, True, False, False]], dtype=bool)
1065
+
1066
+ If the origin of the original structure is equal to 0, then it is
1067
+ also equal to 0 for the iterated structure. If not, the origin
1068
+ must also be adapted if the equivalent of the *iterations*
1069
+ erosions or dilations must be achieved with the iterated
1070
+ structure. The adapted origin is simply obtained by multiplying
1071
+ with the number of iterations. For convenience, the
1072
+ :func:`iterate_structure` also returns the adapted origin if the
1073
+ *origin* parameter is not ``None``:
1074
+
1075
+ .. code:: python
1076
+
1077
+ >>> iterate_structure(struct, 2, -1)
1078
+ (array([[False, False, True, False, False],
1079
+ [False, True, True, True, False],
1080
+ [ True, True, True, True, True],
1081
+ [False, True, True, True, False],
1082
+ [False, False, True, False, False]], dtype=bool), [-2, -2])
1083
+
1084
+ Other morphology operations can be defined in terms of erosion and
1085
+ dilation. The following functions provide a few of these operations
1086
+ for convenience:
1087
+
1088
+ - The :func:`binary_opening` function implements binary opening of
1089
+ arrays of arbitrary rank with the given structuring element. Binary
1090
+ opening is equivalent to a binary erosion followed by a binary
1091
+ dilation with the same structuring element. The origin parameter
1092
+ controls the placement of the structuring element, as described in
1093
+ :ref:`ndimage-filter-functions`. If no structuring element is
1094
+ provided, an element with connectivity equal to one is generated
1095
+ using :func:`generate_binary_structure`. The *iterations* parameter
1096
+ gives the number of erosions that is performed followed by the same
1097
+ number of dilations.
1098
+
1099
+ - The :func:`binary_closing` function implements binary closing of
1100
+ arrays of arbitrary rank with the given structuring element. Binary
1101
+ closing is equivalent to a binary dilation followed by a binary
1102
+ erosion with the same structuring element. The origin parameter
1103
+ controls the placement of the structuring element, as described in
1104
+ :ref:`ndimage-filter-functions`. If no structuring element is
1105
+ provided, an element with connectivity equal to one is generated
1106
+ using :func:`generate_binary_structure`. The *iterations* parameter
1107
+ gives the number of dilations that is performed followed by the same
1108
+ number of erosions.
1109
+
1110
+ - The :func:`binary_fill_holes` function is used to close holes in
1111
+ objects in a binary image, where the structure defines the
1112
+ connectivity of the holes. The origin parameter controls the
1113
+ placement of the structuring element, as described in
1114
+ :ref:`ndimage-filter-functions`. If no structuring element is
1115
+ provided, an element with connectivity equal to one is generated
1116
+ using :func:`generate_binary_structure`.
1117
+
1118
+ - The :func:`binary_hit_or_miss` function implements a binary
1119
+ hit-or-miss transform of arrays of arbitrary rank with the given
1120
+ structuring elements. The hit-or-miss transform is calculated by
1121
+ erosion of the input with the first structure, erosion of the
1122
+ logical *not* of the input with the second structure, followed by
1123
+ the logical *and* of these two erosions. The origin parameters
1124
+ control the placement of the structuring elements, as described in
1125
+ :ref:`ndimage-filter-functions`. If *origin2* equals ``None``, it is set
1126
+ equal to the *origin1* parameter. If the first structuring element
1127
+ is not provided, a structuring element with connectivity equal to
1128
+ one is generated using :func:`generate_binary_structure`. If
1129
+ *structure2* is not provided, it is set equal to the logical *not*
1130
+ of *structure1*.
1131
+
1132
+ .. _ndimage-grey-morphology:
1133
+
1134
+ Grey-scale morphology
1135
+ ^^^^^^^^^^^^^^^^^^^^^
1136
+
1137
+ Grey-scale morphology operations are the equivalents of binary
1138
+ morphology operations that operate on arrays with arbitrary values.
1139
+ Below, we describe the grey-scale equivalents of erosion, dilation,
1140
+ opening and closing. These operations are implemented in a similar
1141
+ fashion as the filters described in :ref:`ndimage-filter-functions`,
1142
+ and we refer to this section for the description of filter kernels and
1143
+ footprints, and the handling of array borders. The grey-scale
1144
+ morphology operations optionally take a *structure* parameter that
1145
+ gives the values of the structuring element. If this parameter is not
1146
+ given, the structuring element is assumed to be flat with a value equal
1147
+ to zero. The shape of the structure can optionally be defined by the
1148
+ *footprint* parameter. If this parameter is not given, the structure
1149
+ is assumed to be rectangular, with sizes equal to the dimensions of
1150
+ the *structure* array, or by the *size* parameter if *structure* is
1151
+ not given. The *size* parameter is only used if both *structure* and
1152
+ *footprint* are not given, in which case the structuring element is
1153
+ assumed to be rectangular and flat with the dimensions given by
1154
+ *size*. The *size* parameter, if provided, must be a sequence of sizes
1155
+ or a single number in which case the size of the filter is assumed to
1156
+ be equal along each axis. The *footprint* parameter, if provided, must
1157
+ be an array that defines the shape of the kernel by its non-zero
1158
+ elements.
1159
+
1160
+ Similarly to binary erosion and dilation, there are operations for
1161
+ grey-scale erosion and dilation:
1162
+
1163
+ - The :func:`grey_erosion` function calculates a multidimensional
1164
+ grey-scale erosion.
1165
+
1166
+ - The :func:`grey_dilation` function calculates a multidimensional
1167
+ grey-scale dilation.
1168
+
1169
+ Grey-scale opening and closing operations can be defined similarly to
1170
+ their binary counterparts:
1171
+
1172
+ - The :func:`grey_opening` function implements grey-scale opening of
1173
+ arrays of arbitrary rank. Grey-scale opening is equivalent to a
1174
+ grey-scale erosion followed by a grey-scale dilation.
1175
+
1176
+ - The :func:`grey_closing` function implements grey-scale closing of
1177
+ arrays of arbitrary rank. Grey-scale opening is equivalent to a
1178
+ grey-scale dilation followed by a grey-scale erosion.
1179
+
1180
+ - The :func:`morphological_gradient` function implements a grey-scale
1181
+ morphological gradient of arrays of arbitrary rank. The grey-scale
1182
+ morphological gradient is equal to the difference of a grey-scale
1183
+ dilation and a grey-scale erosion.
1184
+
1185
+ - The :func:`morphological_laplace` function implements a grey-scale
1186
+ morphological laplace of arrays of arbitrary rank. The grey-scale
1187
+ morphological laplace is equal to the sum of a grey-scale dilation
1188
+ and a grey-scale erosion minus twice the input.
1189
+
1190
+ - The :func:`white_tophat` function implements a white top-hat filter
1191
+ of arrays of arbitrary rank. The white top-hat is equal to the
1192
+ difference of the input and a grey-scale opening.
1193
+
1194
+ - The :func:`black_tophat` function implements a black top-hat filter
1195
+ of arrays of arbitrary rank. The black top-hat is equal to the
1196
+ difference of a grey-scale closing and the input.
1197
+
1198
+ .. _ndimage-distance-transforms:
1199
+
1200
+ Distance transforms
1201
+ -------------------
1202
+
1203
+ Distance transforms are used to calculate the minimum distance from
1204
+ each element of an object to the background. The following functions
1205
+ implement distance transforms for three different distance metrics:
1206
+ Euclidean, city block, and chessboard distances.
1207
+
1208
+ - The function :func:`distance_transform_cdt` uses a chamfer type
1209
+ algorithm to calculate the distance transform of the input, by
1210
+ replacing each object element (defined by values larger than zero)
1211
+ with the shortest distance to the background (all non-object
1212
+ elements). The structure determines the type of chamfering that is
1213
+ done. If the structure is equal to 'cityblock', a structure is
1214
+ generated using :func:`generate_binary_structure` with a squared
1215
+ distance equal to 1. If the structure is equal to 'chessboard', a
1216
+ structure is generated using :func:`generate_binary_structure` with
1217
+ a squared distance equal to the rank of the array. These choices
1218
+ correspond to the common interpretations of the city block and the
1219
+ chessboard distance metrics in two dimensions.
1220
+
1221
+ In addition to the distance transform, the feature transform can be
1222
+ calculated. In this case, the index of the closest background element
1223
+ is returned along the first axis of the result. The
1224
+ *return_distances*, and *return_indices* flags can be used to
1225
+ indicate if the distance transform, the feature transform, or both
1226
+ must be returned.
1227
+
1228
+ The *distances* and *indices* arguments can be used to give optional
1229
+ output arrays that must be of the correct size and type (both
1230
+ ``numpy.int32``). The basics of the algorithm used to implement this
1231
+ function are described in [2]_.
1232
+
1233
+ - The function :func:`distance_transform_edt` calculates the exact
1234
+ Euclidean distance transform of the input, by replacing each object
1235
+ element (defined by values larger than zero) with the shortest
1236
+ Euclidean distance to the background (all non-object elements).
1237
+
1238
+ In addition to the distance transform, the feature transform can be
1239
+ calculated. In this case, the index of the closest background element
1240
+ is returned along the first axis of the result. The
1241
+ *return_distances* and *return_indices* flags can be used to
1242
+ indicate if the distance transform, the feature transform, or both
1243
+ must be returned.
1244
+
1245
+ Optionally, the sampling along each axis can be given by the
1246
+ *sampling* parameter, which should be a sequence of length equal to
1247
+ the input rank, or a single number in which the sampling is assumed
1248
+ to be equal along all axes.
1249
+
1250
+ The *distances* and *indices* arguments can be used to give optional
1251
+ output arrays that must be of the correct size and type
1252
+ (``numpy.float64`` and ``numpy.int32``).The algorithm used to
1253
+ implement this function is described in [3]_.
1254
+
1255
+ - The function :func:`distance_transform_bf` uses a brute-force
1256
+ algorithm to calculate the distance transform of the input, by
1257
+ replacing each object element (defined by values larger than zero)
1258
+ with the shortest distance to the background (all non-object
1259
+ elements). The metric must be one of "euclidean", "cityblock", or
1260
+ "chessboard".
1261
+
1262
+ In addition to the distance transform, the feature transform can be
1263
+ calculated. In this case, the index of the closest background element
1264
+ is returned along the first axis of the result. The
1265
+ *return_distances* and *return_indices* flags can be used to
1266
+ indicate if the distance transform, the feature transform, or both
1267
+ must be returned.
1268
+
1269
+ Optionally, the sampling along each axis can be given by the
1270
+ *sampling* parameter, which should be a sequence of length equal to
1271
+ the input rank, or a single number in which the sampling is assumed
1272
+ to be equal along all axes. This parameter is only used in the case
1273
+ of the Euclidean distance transform.
1274
+
1275
+ The *distances* and *indices* arguments can be used to give optional
1276
+ output arrays that must be of the correct size and type
1277
+ (``numpy.float64`` and ``numpy.int32``).
1278
+
1279
+ .. note::
1280
+
1281
+ This function uses a slow brute-force algorithm, the function
1282
+ :func:`distance_transform_cdt` can be used to more efficiently
1283
+ calculate city block and chessboard distance transforms. The
1284
+ function :func:`distance_transform_edt` can be used to more
1285
+ efficiently calculate the exact Euclidean distance transform.
1286
+
1287
+ Segmentation and labeling
1288
+ -------------------------
1289
+
1290
+ Segmentation is the process of separating objects of interest from
1291
+ the background. The most simple approach is, probably, intensity
1292
+ thresholding, which is easily done with :mod:`numpy` functions:
1293
+
1294
+ .. code:: python
1295
+
1296
+ >>> a = np.array([[1,2,2,1,1,0],
1297
+ ... [0,2,3,1,2,0],
1298
+ ... [1,1,1,3,3,2],
1299
+ ... [1,1,1,1,2,1]])
1300
+ >>> np.where(a > 1, 1, 0)
1301
+ array([[0, 1, 1, 0, 0, 0],
1302
+ [0, 1, 1, 0, 1, 0],
1303
+ [0, 0, 0, 1, 1, 1],
1304
+ [0, 0, 0, 0, 1, 0]])
1305
+
1306
+ The result is a binary image, in which the individual objects still
1307
+ need to be identified and labeled. The function :func:`label`
1308
+ generates an array where each object is assigned a unique number:
1309
+
1310
+ - The :func:`label` function generates an array where the objects in
1311
+ the input are labeled with an integer index. It returns a tuple
1312
+ consisting of the array of object labels and the number of objects
1313
+ found, unless the *output* parameter is given, in which case only
1314
+ the number of objects is returned. The connectivity of the objects
1315
+ is defined by a structuring element. For instance, in 2D
1316
+ using a 4-connected structuring element gives:
1317
+
1318
+ .. code:: python
1319
+
1320
+ >>> a = np.array([[0,1,1,0,0,0],[0,1,1,0,1,0],[0,0,0,1,1,1],[0,0,0,0,1,0]])
1321
+ >>> s = [[0, 1, 0], [1,1,1], [0,1,0]]
1322
+ >>> from scipy.ndimage import label
1323
+ >>> label(a, s)
1324
+ (array([[0, 1, 1, 0, 0, 0],
1325
+ [0, 1, 1, 0, 2, 0],
1326
+ [0, 0, 0, 2, 2, 2],
1327
+ [0, 0, 0, 0, 2, 0]]), 2)
1328
+
1329
+ These two objects are not connected because there is no way in which
1330
+ we can place the structuring element, such that it overlaps with both
1331
+ objects. However, an 8-connected structuring element results in only
1332
+ a single object:
1333
+
1334
+ .. code:: python
1335
+
1336
+ >>> a = np.array([[0,1,1,0,0,0],[0,1,1,0,1,0],[0,0,0,1,1,1],[0,0,0,0,1,0]])
1337
+ >>> s = [[1,1,1], [1,1,1], [1,1,1]]
1338
+ >>> label(a, s)[0]
1339
+ array([[0, 1, 1, 0, 0, 0],
1340
+ [0, 1, 1, 0, 1, 0],
1341
+ [0, 0, 0, 1, 1, 1],
1342
+ [0, 0, 0, 0, 1, 0]])
1343
+
1344
+ If no structuring element is provided, one is generated by calling
1345
+ :func:`generate_binary_structure` (see
1346
+ :ref:`ndimage-binary-morphology`) using a connectivity of one (which
1347
+ in 2D is the 4-connected structure of the first example). The input
1348
+ can be of any type, any value not equal to zero is taken to be part
1349
+ of an object. This is useful if you need to 're-label' an array of
1350
+ object indices, for instance, after removing unwanted objects. Just
1351
+ apply the label function again to the index array. For instance:
1352
+
1353
+ .. code:: python
1354
+
1355
+ >>> l, n = label([1, 0, 1, 0, 1])
1356
+ >>> l
1357
+ array([1, 0, 2, 0, 3])
1358
+ >>> l = np.where(l != 2, l, 0)
1359
+ >>> l
1360
+ array([1, 0, 0, 0, 3])
1361
+ >>> label(l)[0]
1362
+ array([1, 0, 0, 0, 2])
1363
+
1364
+ .. note::
1365
+
1366
+ The structuring element used by :func:`label` is assumed to be
1367
+ symmetric.
1368
+
1369
+ There is a large number of other approaches for segmentation, for
1370
+ instance, from an estimation of the borders of the objects that can be
1371
+ obtained by derivative filters. One such approach is
1372
+ watershed segmentation. The function :func:`watershed_ift` generates
1373
+ an array where each object is assigned a unique label, from an array
1374
+ that localizes the object borders, generated, for instance, by a
1375
+ gradient magnitude filter. It uses an array containing initial markers
1376
+ for the objects:
1377
+
1378
+ - The :func:`watershed_ift` function applies a watershed from markers
1379
+ algorithm, using Image Foresting Transform, as described in
1380
+ [4]_.
1381
+
1382
+ - The inputs of this function are the array to which the transform is
1383
+ applied, and an array of markers that designate the objects by a
1384
+ unique label, where any non-zero value is a marker. For instance:
1385
+
1386
+ .. code:: python
1387
+
1388
+ >>> input = np.array([[0, 0, 0, 0, 0, 0, 0],
1389
+ ... [0, 1, 1, 1, 1, 1, 0],
1390
+ ... [0, 1, 0, 0, 0, 1, 0],
1391
+ ... [0, 1, 0, 0, 0, 1, 0],
1392
+ ... [0, 1, 0, 0, 0, 1, 0],
1393
+ ... [0, 1, 1, 1, 1, 1, 0],
1394
+ ... [0, 0, 0, 0, 0, 0, 0]], np.uint8)
1395
+ >>> markers = np.array([[1, 0, 0, 0, 0, 0, 0],
1396
+ ... [0, 0, 0, 0, 0, 0, 0],
1397
+ ... [0, 0, 0, 0, 0, 0, 0],
1398
+ ... [0, 0, 0, 2, 0, 0, 0],
1399
+ ... [0, 0, 0, 0, 0, 0, 0],
1400
+ ... [0, 0, 0, 0, 0, 0, 0],
1401
+ ... [0, 0, 0, 0, 0, 0, 0]], np.int8)
1402
+ >>> from scipy.ndimage import watershed_ift
1403
+ >>> watershed_ift(input, markers)
1404
+ array([[1, 1, 1, 1, 1, 1, 1],
1405
+ [1, 1, 2, 2, 2, 1, 1],
1406
+ [1, 2, 2, 2, 2, 2, 1],
1407
+ [1, 2, 2, 2, 2, 2, 1],
1408
+ [1, 2, 2, 2, 2, 2, 1],
1409
+ [1, 1, 2, 2, 2, 1, 1],
1410
+ [1, 1, 1, 1, 1, 1, 1]], dtype=int8)
1411
+
1412
+ Here, two markers were used to designate an object (*marker* = 2) and
1413
+ the background (*marker* = 1). The order in which these are
1414
+ processed is arbitrary: moving the marker for the background to the
1415
+ lower-right corner of the array yields a different result:
1416
+
1417
+ .. code:: python
1418
+
1419
+ >>> markers = np.array([[0, 0, 0, 0, 0, 0, 0],
1420
+ ... [0, 0, 0, 0, 0, 0, 0],
1421
+ ... [0, 0, 0, 0, 0, 0, 0],
1422
+ ... [0, 0, 0, 2, 0, 0, 0],
1423
+ ... [0, 0, 0, 0, 0, 0, 0],
1424
+ ... [0, 0, 0, 0, 0, 0, 0],
1425
+ ... [0, 0, 0, 0, 0, 0, 1]], np.int8)
1426
+ >>> watershed_ift(input, markers)
1427
+ array([[1, 1, 1, 1, 1, 1, 1],
1428
+ [1, 1, 1, 1, 1, 1, 1],
1429
+ [1, 1, 2, 2, 2, 1, 1],
1430
+ [1, 1, 2, 2, 2, 1, 1],
1431
+ [1, 1, 2, 2, 2, 1, 1],
1432
+ [1, 1, 1, 1, 1, 1, 1],
1433
+ [1, 1, 1, 1, 1, 1, 1]], dtype=int8)
1434
+
1435
+ The result is that the object (*marker* = 2) is smaller because the
1436
+ second marker was processed earlier. This may not be the desired
1437
+ effect if the first marker was supposed to designate a background
1438
+ object. Therefore, :func:`watershed_ift` treats markers with a
1439
+ negative value explicitly as background markers and processes them
1440
+ after the normal markers. For instance, replacing the first marker
1441
+ by a negative marker gives a result similar to the first example:
1442
+
1443
+ .. code:: python
1444
+
1445
+ >>> markers = np.array([[0, 0, 0, 0, 0, 0, 0],
1446
+ ... [0, 0, 0, 0, 0, 0, 0],
1447
+ ... [0, 0, 0, 0, 0, 0, 0],
1448
+ ... [0, 0, 0, 2, 0, 0, 0],
1449
+ ... [0, 0, 0, 0, 0, 0, 0],
1450
+ ... [0, 0, 0, 0, 0, 0, 0],
1451
+ ... [0, 0, 0, 0, 0, 0, -1]], np.int8)
1452
+ >>> watershed_ift(input, markers)
1453
+ array([[-1, -1, -1, -1, -1, -1, -1],
1454
+ [-1, -1, 2, 2, 2, -1, -1],
1455
+ [-1, 2, 2, 2, 2, 2, -1],
1456
+ [-1, 2, 2, 2, 2, 2, -1],
1457
+ [-1, 2, 2, 2, 2, 2, -1],
1458
+ [-1, -1, 2, 2, 2, -1, -1],
1459
+ [-1, -1, -1, -1, -1, -1, -1]], dtype=int8)
1460
+
1461
+ The connectivity of the objects is defined by a structuring
1462
+ element. If no structuring element is provided, one is generated by
1463
+ calling :func:`generate_binary_structure` (see
1464
+ :ref:`ndimage-binary-morphology`) using a connectivity of one (which
1465
+ in 2D is a 4-connected structure.) For example, using an 8-connected
1466
+ structure with the last example yields a different object:
1467
+
1468
+ .. code:: python
1469
+
1470
+ >>> watershed_ift(input, markers,
1471
+ ... structure = [[1,1,1], [1,1,1], [1,1,1]])
1472
+ array([[-1, -1, -1, -1, -1, -1, -1],
1473
+ [-1, 2, 2, 2, 2, 2, -1],
1474
+ [-1, 2, 2, 2, 2, 2, -1],
1475
+ [-1, 2, 2, 2, 2, 2, -1],
1476
+ [-1, 2, 2, 2, 2, 2, -1],
1477
+ [-1, 2, 2, 2, 2, 2, -1],
1478
+ [-1, -1, -1, -1, -1, -1, -1]], dtype=int8)
1479
+
1480
+ .. note::
1481
+
1482
+ The implementation of :func:`watershed_ift` limits the data types
1483
+ of the input to ``numpy.uint8`` and ``numpy.uint16``.
1484
+
1485
+ .. _ndimage-object-measurements:
1486
+
1487
+ Object measurements
1488
+ -------------------
1489
+
1490
+ Given an array of labeled objects, the properties of the individual
1491
+ objects can be measured. The :func:`find_objects` function can be used
1492
+ to generate a list of slices that for each object, give the
1493
+ smallest sub-array that fully contains the object:
1494
+
1495
+ - The :func:`find_objects` function finds all objects in a labeled
1496
+ array and returns a list of slices that correspond to the smallest
1497
+ regions in the array that contains the object.
1498
+
1499
+ For instance:
1500
+
1501
+ .. code:: python
1502
+
1503
+ >>> a = np.array([[0,1,1,0,0,0],[0,1,1,0,1,0],[0,0,0,1,1,1],[0,0,0,0,1,0]])
1504
+ >>> l, n = label(a)
1505
+ >>> from scipy.ndimage import find_objects
1506
+ >>> f = find_objects(l)
1507
+ >>> a[f[0]]
1508
+ array([[1, 1],
1509
+ [1, 1]])
1510
+ >>> a[f[1]]
1511
+ array([[0, 1, 0],
1512
+ [1, 1, 1],
1513
+ [0, 1, 0]])
1514
+
1515
+ The function :func:`find_objects` returns slices for all objects,
1516
+ unless the *max_label* parameter is larger then zero, in which case
1517
+ only the first *max_label* objects are returned. If an index is
1518
+ missing in the *label* array, ``None`` is return instead of a
1519
+ slice. For example:
1520
+
1521
+ .. code:: python
1522
+
1523
+ >>> from scipy.ndimage import find_objects
1524
+ >>> find_objects([1, 0, 3, 4], max_label = 3)
1525
+ [(slice(0, 1, None),), None, (slice(2, 3, None),)]
1526
+
1527
+ The list of slices generated by :func:`find_objects` is useful to find
1528
+ the position and dimensions of the objects in the array, but can also
1529
+ be used to perform measurements on the individual objects. Say, we want
1530
+ to find the sum of the intensities of an object in image:
1531
+
1532
+ .. code:: python
1533
+
1534
+ >>> image = np.arange(4 * 6).reshape(4, 6)
1535
+ >>> mask = np.array([[0,1,1,0,0,0],[0,1,1,0,1,0],[0,0,0,1,1,1],[0,0,0,0,1,0]])
1536
+ >>> labels = label(mask)[0]
1537
+ >>> slices = find_objects(labels)
1538
+
1539
+ Then we can calculate the sum of the elements in the second object:
1540
+
1541
+ .. code:: python
1542
+
1543
+ >>> np.where(labels[slices[1]] == 2, image[slices[1]], 0).sum()
1544
+ 80
1545
+
1546
+ That is, however, not particularly efficient and may also be more
1547
+ complicated for other types of measurements. Therefore, a few
1548
+ measurements functions are defined that accept the array of object
1549
+ labels and the index of the object to be measured. For instance,
1550
+ calculating the sum of the intensities can be done by:
1551
+
1552
+ .. code:: python
1553
+
1554
+ >>> from scipy.ndimage import sum as ndi_sum
1555
+ >>> ndi_sum(image, labels, 2)
1556
+ 80
1557
+
1558
+ For large arrays and small objects, it is more efficient to call the
1559
+ measurement functions after slicing the array:
1560
+
1561
+ .. code:: python
1562
+
1563
+ >>> ndi_sum(image[slices[1]], labels[slices[1]], 2)
1564
+ 80
1565
+
1566
+ Alternatively, we can do the measurements for a number of labels with
1567
+ a single function call, returning a list of results. For instance, to
1568
+ measure the sum of the values of the background and the second object
1569
+ in our example, we give a list of labels:
1570
+
1571
+ .. code:: python
1572
+
1573
+ >>> ndi_sum(image, labels, [0, 2])
1574
+ array([178.0, 80.0])
1575
+
1576
+ The measurement functions described below all support the *index*
1577
+ parameter to indicate which object(s) should be measured. The default
1578
+ value of *index* is ``None``. This indicates that all elements where the
1579
+ label is larger than zero should be treated as a single object and
1580
+ measured. Thus, in this case the *labels* array is treated as a mask
1581
+ defined by the elements that are larger than zero. If *index* is a
1582
+ number or a sequence of numbers it gives the labels of the objects
1583
+ that are measured. If *index* is a sequence, a list of the results is
1584
+ returned. Functions that return more than one result return their
1585
+ result as a tuple if *index* is a single number, or as a tuple of
1586
+ lists if *index* is a sequence.
1587
+
1588
+ - The :func:`sum` function calculates the sum of the elements of the
1589
+ object with label(s) given by *index*, using the *labels* array for
1590
+ the object labels. If *index* is ``None``, all elements with a
1591
+ non-zero label value are treated as a single object. If *label* is
1592
+ ``None``, all elements of *input* are used in the calculation.
1593
+
1594
+ - The :func:`mean` function calculates the mean of the elements of the
1595
+ object with label(s) given by *index*, using the *labels* array for
1596
+ the object labels. If *index* is ``None``, all elements with a
1597
+ non-zero label value are treated as a single object. If *label* is
1598
+ ``None``, all elements of *input* are used in the calculation.
1599
+
1600
+ - The :func:`variance` function calculates the variance of the
1601
+ elements of the object with label(s) given by *index*, using the
1602
+ *labels* array for the object labels. If *index* is ``None``, all
1603
+ elements with a non-zero label value are treated as a single
1604
+ object. If *label* is ``None``, all elements of *input* are used in
1605
+ the calculation.
1606
+
1607
+ - The :func:`standard_deviation` function calculates the standard
1608
+ deviation of the elements of the object with label(s) given by
1609
+ *index*, using the *labels* array for the object labels. If *index*
1610
+ is ``None``, all elements with a non-zero label value are treated as
1611
+ a single object. If *label* is ``None``, all elements of *input* are
1612
+ used in the calculation.
1613
+
1614
+ - The :func:`minimum` function calculates the minimum of the elements
1615
+ of the object with label(s) given by *index*, using the *labels*
1616
+ array for the object labels. If *index* is ``None``, all elements
1617
+ with a non-zero label value are treated as a single object. If
1618
+ *label* is ``None``, all elements of *input* are used in the
1619
+ calculation.
1620
+
1621
+ - The :func:`maximum` function calculates the maximum of the elements
1622
+ of the object with label(s) given by *index*, using the *labels*
1623
+ array for the object labels. If *index* is ``None``, all elements
1624
+ with a non-zero label value are treated as a single object. If
1625
+ *label* is ``None``, all elements of *input* are used in the
1626
+ calculation.
1627
+
1628
+ - The :func:`minimum_position` function calculates the position of the
1629
+ minimum of the elements of the object with label(s) given by
1630
+ *index*, using the *labels* array for the object labels. If *index*
1631
+ is ``None``, all elements with a non-zero label value are treated as
1632
+ a single object. If *label* is ``None``, all elements of *input* are
1633
+ used in the calculation.
1634
+
1635
+ - The :func:`maximum_position` function calculates the position of the
1636
+ maximum of the elements of the object with label(s) given by
1637
+ *index*, using the *labels* array for the object labels. If *index*
1638
+ is ``None``, all elements with a non-zero label value are treated as
1639
+ a single object. If *label* is ``None``, all elements of *input* are
1640
+ used in the calculation.
1641
+
1642
+ - The :func:`extrema` function calculates the minimum, the maximum,
1643
+ and their positions, of the elements of the object with label(s)
1644
+ given by *index*, using the *labels* array for the object labels. If
1645
+ *index* is ``None``, all elements with a non-zero label value are
1646
+ treated as a single object. If *label* is ``None``, all elements of
1647
+ *input* are used in the calculation. The result is a tuple giving
1648
+ the minimum, the maximum, the position of the minimum, and the
1649
+ position of the maximum. The result is the same as a tuple formed by
1650
+ the results of the functions *minimum*, *maximum*,
1651
+ *minimum_position*, and *maximum_position* that are described above.
1652
+
1653
+ - The :func:`center_of_mass` function calculates the center of mass of
1654
+ the object with label(s) given by *index*, using the *labels*
1655
+ array for the object labels. If *index* is ``None``, all elements
1656
+ with a non-zero label value are treated as a single object. If
1657
+ *label* is ``None``, all elements of *input* are used in the
1658
+ calculation.
1659
+
1660
+ - The :func:`histogram` function calculates a histogram of the
1661
+ object with label(s) given by *index*, using the *labels* array for
1662
+ the object labels. If *index* is ``None``, all elements with a
1663
+ non-zero label value are treated as a single object. If *label* is
1664
+ ``None``, all elements of *input* are used in the calculation.
1665
+ Histograms are defined by their minimum (*min*), maximum (*max*), and
1666
+ the number of bins (*bins*). They are returned as 1-D
1667
+ arrays of type ``numpy.int32``.
1668
+
1669
+ .. _ndimage-ccallbacks:
1670
+
1671
+ Extending :mod:`scipy.ndimage` in C
1672
+ -----------------------------------
1673
+
1674
+ A few functions in :mod:`scipy.ndimage` take a callback argument. This
1675
+ can be either a python function or a `scipy.LowLevelCallable` containing a
1676
+ pointer to a C function. Using a C function will generally be more
1677
+ efficient, since it avoids the overhead of calling a python function on
1678
+ many elements of an array. To use a C function, you must write a C
1679
+ extension that contains the callback function and a Python function
1680
+ that returns a `scipy.LowLevelCallable` containing a pointer to the
1681
+ callback.
1682
+
1683
+ An example of a function that supports callbacks is
1684
+ :func:`geometric_transform`, which accepts a callback function that
1685
+ defines a mapping from all output coordinates to corresponding
1686
+ coordinates in the input array. Consider the following python example,
1687
+ which uses :func:`geometric_transform` to implement a shift function.
1688
+
1689
+ .. code:: python
1690
+
1691
+ from scipy import ndimage
1692
+
1693
+ def transform(output_coordinates, shift):
1694
+ input_coordinates = output_coordinates[0] - shift, output_coordinates[1] - shift
1695
+ return input_coordinates
1696
+
1697
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
1698
+ shift = 0.5
1699
+ print(ndimage.geometric_transform(im, transform, extra_arguments=(shift,)))
1700
+
1701
+ We can also implement the callback function with the following C code:
1702
+
1703
+ .. code:: c
1704
+
1705
+ /* example.c */
1706
+
1707
+ #include <Python.h>
1708
+ #include <numpy/npy_common.h>
1709
+
1710
+ static int
1711
+ _transform(npy_intp *output_coordinates, double *input_coordinates,
1712
+ int output_rank, int input_rank, void *user_data)
1713
+ {
1714
+ npy_intp i;
1715
+ double shift = *(double *)user_data;
1716
+
1717
+ for (i = 0; i < input_rank; i++) {
1718
+ input_coordinates[i] = output_coordinates[i] - shift;
1719
+ }
1720
+ return 1;
1721
+ }
1722
+
1723
+ static char *transform_signature = "int (npy_intp *, double *, int, int, void *)";
1724
+
1725
+ static PyObject *
1726
+ py_get_transform(PyObject *obj, PyObject *args)
1727
+ {
1728
+ if (!PyArg_ParseTuple(args, "")) return NULL;
1729
+ return PyCapsule_New(_transform, transform_signature, NULL);
1730
+ }
1731
+
1732
+ static PyMethodDef ExampleMethods[] = {
1733
+ {"get_transform", (PyCFunction)py_get_transform, METH_VARARGS, ""},
1734
+ {NULL, NULL, 0, NULL}
1735
+ };
1736
+
1737
+ /* Initialize the module */
1738
+ static struct PyModuleDef example = {
1739
+ PyModuleDef_HEAD_INIT,
1740
+ "example",
1741
+ NULL,
1742
+ -1,
1743
+ ExampleMethods,
1744
+ NULL,
1745
+ NULL,
1746
+ NULL,
1747
+ NULL
1748
+ };
1749
+
1750
+ PyMODINIT_FUNC
1751
+ PyInit_example(void)
1752
+ {
1753
+ return PyModule_Create(&example);
1754
+ }
1755
+
1756
+ More information on writing Python extension modules can be found
1757
+ `here`__. If the C code is in the file ``example.c``, then it can be
1758
+ compiled after adding it to ``meson.build`` (see examples inside
1759
+ ``meson.build`` files) and follow what's there. After that is done,
1760
+ running the script:
1761
+
1762
+ __ https://docs.python.org/3/extending/index.html
1763
+
1764
+ .. code:: python
1765
+
1766
+ import ctypes
1767
+ import numpy as np
1768
+ from scipy import ndimage, LowLevelCallable
1769
+
1770
+ from example import get_transform
1771
+
1772
+ shift = 0.5
1773
+
1774
+ user_data = ctypes.c_double(shift)
1775
+ ptr = ctypes.cast(ctypes.pointer(user_data), ctypes.c_void_p)
1776
+ callback = LowLevelCallable(get_transform(), ptr)
1777
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
1778
+ print(ndimage.geometric_transform(im, callback))
1779
+
1780
+ produces the same result as the original python script.
1781
+
1782
+ In the C version, ``_transform`` is the callback function and the
1783
+ parameters ``output_coordinates`` and ``input_coordinates`` play the
1784
+ same role as they do in the python version, while ``output_rank`` and
1785
+ ``input_rank`` provide the equivalents of ``len(output_coordinates)``
1786
+ and ``len(input_coordinates)``. The variable ``shift`` is passed
1787
+ through ``user_data`` instead of
1788
+ ``extra_arguments``. Finally, the C callback function returns an integer
1789
+ status, which is one upon success and zero otherwise.
1790
+
1791
+ The function ``py_transform`` wraps the callback function in a
1792
+ :c:type:`PyCapsule`. The main steps are:
1793
+
1794
+ - Initialize a :c:type:`PyCapsule`. The first argument is a pointer to
1795
+ the callback function.
1796
+
1797
+ - The second argument is the function signature, which must match exactly
1798
+ the one expected by :mod:`~scipy.ndimage`.
1799
+
1800
+ - Above, we used `scipy.LowLevelCallable` to specify ``user_data``
1801
+ that we generated with `ctypes`.
1802
+
1803
+ A different approach would be to supply the data in the capsule context,
1804
+ that can be set by `PyCapsule_SetContext` and omit specifying
1805
+ ``user_data`` in `scipy.LowLevelCallable`. However, in this approach we would
1806
+ need to deal with allocation/freeing of the data --- freeing the data
1807
+ after the capsule has been destroyed can be done by specifying a non-NULL
1808
+ callback function in the third argument of `PyCapsule_New`.
1809
+
1810
+ C callback functions for :mod:`~scipy.ndimage` all follow this scheme. The
1811
+ next section lists the :mod:`~scipy.ndimage` functions that accept a C
1812
+ callback function and gives the prototype of the function.
1813
+
1814
+ .. seealso::
1815
+
1816
+ The functions that support low-level callback arguments are:
1817
+
1818
+ `generic_filter`, `generic_filter1d`, `geometric_transform`
1819
+
1820
+ Below, we show alternative ways to write the code, using Numba_, Cython_,
1821
+ ctypes_, or cffi_ instead of writing wrapper code in C.
1822
+
1823
+ .. _Numba: https://numba.pydata.org/
1824
+ .. _Cython: https://cython.org/
1825
+ .. _ctypes: https://docs.python.org/3/library/ctypes.html
1826
+ .. _cffi: https://cffi.readthedocs.io/
1827
+
1828
+ .. rubric:: Numba
1829
+
1830
+ Numba_ provides a way to write low-level functions easily in Python.
1831
+ We can write the above using Numba as:
1832
+
1833
+ .. code:: python
1834
+
1835
+ # example.py
1836
+ import numpy as np
1837
+ import ctypes
1838
+ from scipy import ndimage, LowLevelCallable
1839
+ from numba import cfunc, types, carray
1840
+
1841
+ @cfunc(types.intc(types.CPointer(types.intp),
1842
+ types.CPointer(types.double),
1843
+ types.intc,
1844
+ types.intc,
1845
+ types.voidptr))
1846
+ def transform(output_coordinates_ptr, input_coordinates_ptr,
1847
+ output_rank, input_rank, user_data):
1848
+ input_coordinates = carray(input_coordinates_ptr, (input_rank,))
1849
+ output_coordinates = carray(output_coordinates_ptr, (output_rank,))
1850
+ shift = carray(user_data, (1,), types.double)[0]
1851
+
1852
+ for i in range(input_rank):
1853
+ input_coordinates[i] = output_coordinates[i] - shift
1854
+
1855
+ return 1
1856
+
1857
+ shift = 0.5
1858
+
1859
+ # Then call the function
1860
+ user_data = ctypes.c_double(shift)
1861
+ ptr = ctypes.cast(ctypes.pointer(user_data), ctypes.c_void_p)
1862
+ callback = LowLevelCallable(transform.ctypes, ptr)
1863
+
1864
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
1865
+ print(ndimage.geometric_transform(im, callback))
1866
+
1867
+
1868
+ .. rubric:: Cython
1869
+
1870
+ Functionally the same code as above can be written in Cython with
1871
+ somewhat less boilerplate as follows:
1872
+
1873
+ .. code:: cython
1874
+
1875
+ # example.pyx
1876
+
1877
+ from numpy cimport npy_intp as intp
1878
+
1879
+ cdef api int transform(intp *output_coordinates, double *input_coordinates,
1880
+ int output_rank, int input_rank, void *user_data):
1881
+ cdef intp i
1882
+ cdef double shift = (<double *>user_data)[0]
1883
+
1884
+ for i in range(input_rank):
1885
+ input_coordinates[i] = output_coordinates[i] - shift
1886
+ return 1
1887
+
1888
+ .. code:: python
1889
+
1890
+ # script.py
1891
+
1892
+ import ctypes
1893
+ import numpy as np
1894
+ from scipy import ndimage, LowLevelCallable
1895
+
1896
+ import example
1897
+
1898
+ shift = 0.5
1899
+
1900
+ user_data = ctypes.c_double(shift)
1901
+ ptr = ctypes.cast(ctypes.pointer(user_data), ctypes.c_void_p)
1902
+ callback = LowLevelCallable.from_cython(example, "transform", ptr)
1903
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
1904
+ print(ndimage.geometric_transform(im, callback))
1905
+
1906
+
1907
+ .. rubric:: cffi
1908
+
1909
+ With cffi_, you can interface with a C function residing in a shared
1910
+ library (DLL). First, we need to write the shared library, which we do
1911
+ in C --- this example is for Linux/OSX:
1912
+
1913
+ .. code:: c
1914
+
1915
+ /*
1916
+ example.c
1917
+ Needs to be compiled with "gcc -std=c99 -shared -fPIC -o example.so example.c"
1918
+ or similar
1919
+ */
1920
+
1921
+ #include <stdint.h>
1922
+
1923
+ int
1924
+ _transform(intptr_t *output_coordinates, double *input_coordinates,
1925
+ int output_rank, int input_rank, void *user_data)
1926
+ {
1927
+ int i;
1928
+ double shift = *(double *)user_data;
1929
+
1930
+ for (i = 0; i < input_rank; i++) {
1931
+ input_coordinates[i] = output_coordinates[i] - shift;
1932
+ }
1933
+ return 1;
1934
+ }
1935
+
1936
+ The Python code calling the library is:
1937
+
1938
+ .. code:: python
1939
+
1940
+ import os
1941
+ import numpy as np
1942
+ from scipy import ndimage, LowLevelCallable
1943
+ import cffi
1944
+
1945
+ # Construct the FFI object, and copypaste the function declaration
1946
+ ffi = cffi.FFI()
1947
+ ffi.cdef("""
1948
+ int _transform(intptr_t *output_coordinates, double *input_coordinates,
1949
+ int output_rank, int input_rank, void *user_data);
1950
+ """)
1951
+
1952
+ # Open library
1953
+ lib = ffi.dlopen(os.path.abspath("example.so"))
1954
+
1955
+ # Do the function call
1956
+ user_data = ffi.new('double *', 0.5)
1957
+ callback = LowLevelCallable(lib._transform, user_data)
1958
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
1959
+ print(ndimage.geometric_transform(im, callback))
1960
+
1961
+ You can find more information in the cffi_ documentation.
1962
+
1963
+ .. rubric:: ctypes
1964
+
1965
+ With *ctypes*, the C code and the compilation of the so/DLL is as for
1966
+ cffi above. The Python code is different:
1967
+
1968
+ .. code:: python
1969
+
1970
+ # script.py
1971
+
1972
+ import os
1973
+ import ctypes
1974
+ import numpy as np
1975
+ from scipy import ndimage, LowLevelCallable
1976
+
1977
+ lib = ctypes.CDLL(os.path.abspath('example.so'))
1978
+
1979
+ shift = 0.5
1980
+
1981
+ user_data = ctypes.c_double(shift)
1982
+ ptr = ctypes.cast(ctypes.pointer(user_data), ctypes.c_void_p)
1983
+
1984
+ # Ctypes has no built-in intptr type, so override the signature
1985
+ # instead of trying to get it via ctypes
1986
+ callback = LowLevelCallable(lib._transform, ptr,
1987
+ "int _transform(intptr_t *, double *, int, int, void *)")
1988
+
1989
+ # Perform the call
1990
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
1991
+ print(ndimage.geometric_transform(im, callback))
1992
+
1993
+ You can find more information in the ctypes_ documentation.
1994
+
1995
+
1996
+ References
1997
+ ----------
1998
+
1999
+ .. [1] M. Unser, "Splines: A Perfect Fit for Signal and Image
2000
+ Processing," IEEE Signal Processing Magazine, vol. 16, no. 6, pp.
2001
+ 22-38, November 1999.
2002
+
2003
+ .. [2] G. Borgefors, "Distance transformations in arbitrary
2004
+ dimensions.", Computer Vision, Graphics, and Image Processing,
2005
+ 27:321-345, 1984.
2006
+
2007
+ .. [3] C. R. Maurer, Jr., R. Qi, and V. Raghavan, "A linear time
2008
+ algorithm for computing exact euclidean distance transforms of
2009
+ binary images in arbitrary dimensions." IEEE Trans. PAMI 25,
2010
+ 265-270, 2003.
2011
+
2012
+ .. [4] A. X. Falcão, J. Stolfi, and R. A. Lotufo. "The image foresting
2013
+ transform: Theory, algorithms, and applications." IEEE Trans.
2014
+ PAMI 26, 19-29. 2004.
2015
+
2016
+ .. [5] T. Briand and P. Monasse, "Theory and Practice of Image B-Spline
2017
+ Interpolation", Image Processing On Line, 8, pp. 99–141, 2018.
2018
+ https://doi.org/10.5201/ipol.2018.221