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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With