Skip to content Skip to sidebar Skip to footer

How To Perform Iterative 2d Operation On 4d Numpy Array

Let me preface this post by saying that I'm pretty new to Python and NumPy, so I'm sure I'm overlooking something simple. What I'm trying to do is image processing over a PGM (gra

Solution 1:

When you need to multiply element-wise, then reduce with addition, think np.dot or np.einsum:

from numpy.lib.stride_tricks import as_strided
arr = np.random.rand(256, 256)
mask = np.random.rand(3, 3)
arr_view = as_strided(arr, shape=(254, 254, 3, 3), strides=arr.strides*2)

arr[1:-1, 1:-1] = np.einsum('ijkl,kl->ij', arr_view, mask)

Solution 2:

Based on the example illustration:

In [1]: import numpy as np

In [2]: from scipy.signal import convolve2d

In [3]: image = np.array([[1,1,1,0,0],[0,1,1,1,0],[0,0,1,1,1],[0,0,1,1,0],[0,1,1,0,0]])

In [4]: m = np.array([[1,0,1],[0,1,0],[1,0,1]])

In [5]: convolve2d(image, m, mode='valid')
Out[5]:
array([[4, 3, 4],
       [2, 4, 3],
       [2, 3, 4]])

And putting it back where it came from:

In [6]: image[1:-1,1:-1] = convolve2d(image, m, mode='valid')

In [7]: image
Out[7]:
array([[1, 1, 1, 0, 0],
       [0, 4, 3, 4, 0],
       [0, 2, 4, 3, 1],
       [0, 2, 3, 4, 0],
       [0, 1, 1, 0, 0]])

Post a Comment for "How To Perform Iterative 2d Operation On 4d Numpy Array"