在 python 中对具有三个内核 (x, y, z) 的 3D 数组进行卷积

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

我有一个 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') 

有更简单的方法吗?谢谢。

您可以使用 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')

您可以使用 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)