繁体   English   中英

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

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

我在 x、y 和 z 方向上有一个 3D 图像和三个内核 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.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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM