Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convolving a periodic image with python

I want to convolve an n-dimensional image which is conceptually periodic.

What I mean is the following: if I have a 2D image

>>> image2d = [[0,0,0,0],
...            [0,0,0,1],
...            [0,0,0,0]]

and I want to convolve it with this kernel:

>>> kernel = [[ 1,1,1],
...           [ 1,1,1],
...           [ 1,1,1]]

then I want the result to be:

>>> result = [[1,0,1,1],
...           [1,0,1,1],
...           [1,0,1,1]]

How to do this in python/numpy/scipy?

Note that I am not interested in creating the kernel, but mainly the periodicity of the convolution, i.e. the three leftmost ones in the resulting image (if that makes sense).

like image 493
ABDreverhaven Avatar asked Feb 16 '23 14:02

ABDreverhaven


1 Answers

This is already built in, with scipy.signal.convolve2d's optional boundary='wrap' which gives periodic boundary conditions as padding for the convolution. The mode option here is 'same' to make the output size match the input size.

In [1]: image2d = [[0,0,0,0],
    ...            [0,0,0,1],
    ...            [0,0,0,0]]

In [2]: kernel = [[ 1,1,1],
    ...           [ 1,1,1],
    ...           [ 1,1,1]]

In [3]: from scipy.signal import convolve2d

In [4]: convolve2d(image2d, kernel, mode='same', boundary='wrap')
Out[4]: 
array([[1, 0, 1, 1],
       [1, 0, 1, 1],
       [1, 0, 1, 1]])

The only disadvantage here is that you cannot use scipy.signal.fftconvolve which is often faster.

like image 134
askewchan Avatar answered Feb 27 '23 09:02

askewchan