简体   繁体   English

如何在Python中使用掩码对数组的数组进行卷积?

[英]How to convolve array of arrays with a mask in Python?

Given a t1xt2xn array and a m1xm2 mask, how to obtain the t1xt2xn array where the n-dim arrays are convolved with the mask? 给定一个t1xt2xn数组和一个m1xm2遮罩,如何获得n-dim数组与遮罩卷积的t1xt2xn数组?

The function scipy.signal.convolve is not able to handle this because it only accept inputs with same number of dimensions. 函数scipy.signal.convolve无法处理此问题,因为它仅接受具有相同维数的输入。

Example with the "same" logic: 具有“相同”逻辑的示例:

in1 =
[[[0,1,2],[3,4,5],[6,7,8]],
[[9,10,11],[12,13,14],[15,16,17]],
[[18,19,20],[21,22,23],[24,25,26]]]

in2 =
[[0,1,0],
[0,1,0],
[0,1,0]]

output =
[[[0,0,0],[15,17,19],[0,0,0]],
[[0,0,0],[36,39,42],[0,0,0]],
[[0,0,0],[33,35,37],[0,0,0]]]

I'm very sorry but I haven't strong math background, so my answer could be wrong. 非常抱歉,但是我没有很强的数学背景,所以我的答案可能是错误的。 Anyway, if you need to use mask for selecting you should convert it to bool type. 无论如何,如果需要使用遮罩进行选择,则应将其转换为布尔型。 For example: 例如:

in1 = np.array([[[0,1,2],    [3,4,5],    [6,7,8]],
                [[9,10,11],  [12,13,14], [15,16,17]],
                [[18,19,20], [21,22,23], [24,25,26]]])

in2 = np.array([[0, 1, 0],
                [0, 1, 0],
                [0, 1, 0]])

mask = in2.astype(bool)

print(in1[mask])
# [[ 3  4  5]
#  [12 13 14]
#  [21 22 23]]

in3 = np.zeros(in1.shape)

in3[mask] = np.convolve(in1[mask].ravel(), in2.ravel(), 'same').reshape(mask.shape)

print(in3)

# [[[  0.   0.   0.]
#   [ 15.  17.  19.]
#   [  0.   0.   0.]]
# 
#  [[  0.   0.   0.]
#   [ 36.  39.  42.]
#   [  0.   0.   0.]]
# 
#  [[  0.   0.   0.]
#   [ 33.  35.  37.]
#   [  0.   0.   0.]]]

I'm not very sure about last part, especially about reshaping but I hope you get an idea. 我不太确定最后一部分,特别是关于重塑,但希望您有个好主意。

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

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