f. c.
f. c.

Reputation: 1135

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.

Upvotes: 3

Views: 10891

Answers (2)

Chris Mueller
Chris Mueller

Reputation: 6680

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)

Upvotes: 5

busybear
busybear

Reputation: 10580

You can use Scipy's convolve. However, the kernel is typically the same number of dimensions as the input. Rather than a vector for each dimension. Not sure how exactly that will play out with what you are trying to do, but I just provided a sample kernel for show:

# Sample kernel
n = 4
kern = np.ones((n+1, n+1, n+1))
vals = np.arange(n+1)
for i in vals:
    for j in vals:
        for k in vals:
            kern[i , j, k] = n/2 - np.sqrt((i-n/2)**2 + (j-n/2)**2 + (k-n/2)**2)

# 3d convolve
scipy.signal.convolve(img, kern, mode='same')

Upvotes: 3

Related Questions