Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - Convolution of 3d array with 2d kernel for each channel separately

I have a matrix of size [c, n, m] where c is a number of channels; n and m are width and height. In the particular example I have a matrix that has 1000 channels. I want to make a convolution with a kernel of the size a x a for each channel separately. In my example the kernel size is 3 x 3. Is there any function in scipy or numpy that does that kind of operation without iterating through the channels with a loop?

I found scipy.ndimage.convolve function but I think that I can not apply that function on this problem without using a loop.

like image 784
Primoz Avatar asked Jun 01 '17 18:06

Primoz


2 Answers

I think you just need to make you kernel three-dimensional. Something like this ought to work:

kernel = kernel[:, :, None]

If scipy.ndimage.convolve doesn't work for 3D arrays, you could try scipy.signal.convolve.

like image 73
farenorth Avatar answered Oct 29 '22 22:10

farenorth


Treat your matrix as an image and use opencv. Change the shape of your array to be [height, width, num_channels]. Then run filter2D (convolution function for images) in opencv.

image = cv2.imread("some_image.jpg")
image.shape # (height, width, 3) # 3 is 3 channels for Red, Green, Blue
kernel = np.ones((3,3)) / 9.
image_blurred = cv2.filter2D(image, cv2.CV_64F, kernel) # will apply the kernel for each channel. You can have more than 3 channels.
like image 39
Andrew Cassidy Avatar answered Oct 29 '22 21:10

Andrew Cassidy