我有一个3D图像,并且在x,y和z方向上有三个内核k1,k2,k3。
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
我可以迭代地使用numpy.convolve
来计算卷积,如下所示:
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')
有更简单的方法吗?谢谢。
答案 0 :(得分:2)
您可以使用scipy.ndimage.convolve1d来指定axis
参数。
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)
答案 1 :(得分:1)
您可以使用Scipy的convolve
。但是,内核的维数通常与输入的维数相同。而不是每个维度的向量。不知道将如何精确地显示您要执行的操作,但我只是提供了一个示例内核来显示:
# 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')