我想在仅仅的特定位置上应用简单的卷积,没什么花哨。我知道我可以计算整个计算结果,只将结果保留在所需的位置,但是有什么办法我可以不做不必要的计算?
这是示例代码:
import numpy as np
from scipy.ndimage.filters import convolve
mat_shape = (40,40)
# input matrix that will be convolved
input_mat = np.random.randint(2, size=mat_shape).astype(np.float32)
# array([[1., 1., 0., ..., 0., 0., 0.],
# [0., 1., 1., ..., 1., 0., 0.],
# [0., 1., 1., ..., 0., 1., 1.],
# ...,
# [0., 0., 0., ..., 1., 1., 0.],
# [0., 0., 0., ..., 0., 0., 0.],
# [0., 0., 1., ..., 1., 0., 0.]], dtype=float32)
# create a random matrix for the convolution
bool_mat = np.random.randint(2, size=mat_shape) == 1
# array([[ True, False, False, ..., True, True, False],
# [ True, True, True, ..., True, False, True],
# [ True, False, False, ..., True, True, False],
# ...,
# [ True, True, True, ..., True, False, True],
# [ True, False, False, ..., True, False, False],
# [ True, True, False, ..., False, False, False]])
kernel_shape = (5, 5)
kernel_mat = np.random.random(size=kernel_shape)
# array([[0.70641424, 0.39223595, 0.68945359, 0.17829957, 0.89733021],
# [0.58014976, 0.1798463 , 0.36159475, 0.15709205, 0.9330952 ],
# [0.73937093, 0.34720608, 0.1095671 , 0.87423794, 0.58166474],
# [0.18155221, 0.99321004, 0.40209741, 0.82267676, 0.59944673],
# [0.2937129 , 0.88619991, 0.7936567 , 0.88069129, 0.67562886]])
rslt_mat = convolve(input_mat, kernel_mat, mode='constant')
# array([[1.4857752 , 2.528183 , 3.863519 , ..., 0.81740016, 0.34470913, 0.9813053 ],
# [2.544829 , 3.702742 , 4.2559624 , ..., 1.6619489 , 1.0067129 , 0.6005618 ],
# [3.4930434 , 5.8310647 , 6.3238297 , ..., 3.208856 , 2.236349 , 1.3885077 ],
# ...,
# [2.9012854 , 4.524009 , 6.7244134 , ..., 5.1134896 , 5.108649 , 4.004656 ],
# [2.4392862 , 5.1577754 , 6.400248 , ..., 5.9179497 , 4.807929 , 3.7523596 ],
# [4.450597 , 5.131026 , 7.211094 , ..., 4.230295 , 4.0098715 , 2.2621353 ]], dtype=float32)
我的目标是使用包含布尔值且形状与bool_mat
相同的布尔值矩阵input_mat
并应用卷积并计算卷积运算的结果仅在位置bool_mat == True
上。
顺便说一句。我可以非常简单地从头实现卷积运算,我宁愿不必重新发明轮子。