This article mainly introduces Python’s understanding of convolution. There are detailed code examples in the article, which have good reference value. I hope it will be helpful to everyone.
convolution function
python
Provides a variety of convolution schemes. In comparison, the convolution function defined in is slightly more complex ndimage
in function than the convolution in numpy
and . This can be glimpsed just from the number of input parameters.signal
1 2 3 4 5 |
|
The first two are 1-dimensional convolution functions, and ndimage can perform convolution operations on multi-dimensional arrays along a single coordinate axis, and the latter two are multi-dimensional convolutions.
The convolution functions in numpy and signal have three modes, which are used to adjust the edge characteristics after convolution. If the dimensions of the two input convolution objects are N NN and M MM respectively, then the output of these three modes The result is
full
: The output dimension is N + M − 1 N+M-1N+M−1. The signals at the last point do not overlap at all, so the edge effect is obvious.same
: Output dimension max ( M , N ) \max(M,N)max(M,N), edge effects are still visiblevalid
: Output dimension ∣ M − N ∣ |MN|∣M−N∣, only returns completely overlapping areas, which is equivalent to eliminating all points with edge effects.
ndimage
In convolve
view of the edge effect, the image is expanded, and what it mode
determines is the filling format after expansion. Assume that the array to be filtered is a b c d
, then in different modes, the edges are filled as follows
left padding | data | right padding | |
---|---|---|---|
reflect |
d c b a | a b c d | d c b a |
constant |
k k k k | a b c d | k k k k |
nearest |
a a a a | a b c d | d d d d |
mirror |
d c b | a b c d | c b a |
wrap |
a b c d | a b c d | a b c d |
Among them, it is set k
through parameters cval
.
These five methods of modifying boundaries scipy.ndimage
are very common in functions, especially filter functions involving convolution, which are standard.
comparison test
Next, do a performance test for these different convolution functions. Use a 5 × 5 convolution template to perform convolution calculations on a 1000 × 1000 matrix. Let’s take a look at the speed of convolution in different implementations.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
In comparison, ndimage
the convolution in is obviously more efficient.
接下来测试一下一维卷积的表现
1 2 3 4 5 6 7 8 9 10 11 |
|
相比之下,convolve1d
不愧是写明了1d
的卷积函数,速度最快,而numpy
中提供的函数速度最慢。