Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convolve a 3D array with three kernels (x, y, z) in python

I have a 3D image and three kernels k1, k2, k3 in the x, y and z direction.

img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension

I can use numpy.convolve iteratively to calculate the convolution like this:

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[1])
      oneline=img[i,j,:]
      img[i,j,:]=np.convolve(oneline, k1, mode='same')

for i in np.arange(img.shape[1])
   for j in np.arange(img.shape[2])
      oneline=img[:,i,j]
      img[:,i,j]=np.convolve(oneline, k2, mode='same') 

for i in np.arange(img.shape[0])
   for j in np.arange(img.shape[2])
      oneline=img[i,:,j]
      img[i,:,j]=np.convolve(oneline, k3, mode='same') 

Is there an easier way to do it? Thanks.

like image 323
f. c. Avatar asked Aug 08 '26 00:08

f. c.


1 Answers

You can use scipy.ndimage.convolve1d which allows you to specify an axis argument.

import numpy as np
import scipy

img = np.random.rand(64, 64, 54) #three dimensional image
k1 = np.array([0.114, 0.141, 0.161, 0.168, 0.161, 0.141, 0.114]) #the kernel along the 1st dimension
k2 = k1 #the kernel along the 2nd dimension
k3 = k1 #the kernel along the 3nd dimension

# Convolve over all three axes in a for loop
out = img.copy()
for i, k in enumerate((k1, k2, k3)):
    out = scipy.ndimage.convolve1d(out, k, axis=i)
like image 158
Chris Mueller Avatar answered Aug 09 '26 12:08

Chris Mueller