gpt4 book ai didi

python - Numpy 逻辑和

转载 作者:行者123 更新时间:2023-11-28 17:16:21 26 4
gpt4 key购买 nike

我有 bool 数组 A 和 B,想得到 C。C 就像 A 和 B 的逻辑与,但在匹配索引时有一些回旋余地。也就是说,逻辑 AND 将执行 A[r, c] AND B[r, c],但我想要的是 A[r +/- 1, c +/- 1] AND B[r +/- 1 , c +/- 1]。有没有一种好的方法可以做到这一点,最好不要遍历每个索引?

>>> import numpy as np
>>> A
np.ndarray([[True, False, False, True],
[False, False, False, False],
[False, False, True, False],
[False, False, False, False])
>>> B
np.ndarray([[False, True, False, False],
[False, False, False, False],
[True, True, True, False],
[False, False, False, False])
>>> np.logical_and(A, B) # only (2,2) is True
np.ndarray([[False, False, False, False],
[False, False, False, False],
[False, False, True, False],
[False, False, False, False])
>>> C # (0,0), (1,0), and (2,1) also become True
np.ndarray([[True, False, False, False],
[True, False, False, False],
[False, True, True, False],
[False, False, False, False])

最佳答案

如果我理解正确,A[r +/- 1, c +/- 1] AND B[r +/- 1, c +/- 1] 将产生以下结果,正如@AetherUnbound 所复制的那样。

[[ True  True  True False]
[ True True True True]
[False True True True]
[False True True True]]

如果这是所需的输出,我们可以对 a 和 b 使用卷积运算,最后进行逻辑与。

解决方案

from scipy import ndimage
#define a convolution filter with size 3*3
f = np.full((3,3),True, dtype=bool)

#Convolve A and B using a 3*3 filter and then do a logical and in the end.
np.logical_and(ndimage.convolve(A,f,mode='constant', cval=False),ndimage.convolve(B,f,mode='constant', cval=False))
Out[766]:
array([[ True, True, True, False],
[ True, True, True, True],
[False, True, True, True],
[False, True, True, True]], dtype=bool)

关于python - Numpy 逻辑和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43903626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com