【发布时间】:2021-04-17 01:47:39
【问题描述】:
我想用列表中的值创建图像的蒙版。例如,我有一个尺寸为 (2, 5) 的 RGB 图像:
a = (np.random.rand(2, 5, 3) * 10).astype(int)
array([[[0, 5, 8],
[9, 0, 2],
[2, 2, 9],
[9, 2, 4],
[2, 5, 3]],
[[7, 5, 7],
[1, 9, 3],
[4, 3, 3],
[9, 1, 1],
[9, 5, 5]]]
b = np.array([[0, 5, 8], [7, 5, 7], [4, 3, 3]])
array([[[0, 5, 8],
[7, 5, 7],
[4, 3, 3]]])
我想要做的是创建一个图像蒙版 a 保留像素值(每个像素值在列表 b 中的像素值列表中)跨 3 个 RGB 通道(第三维)。给定 a 和 b 的示例结果是:
array([[[True, True, True], # check if [0, 5, 8] is in b
[False, False, False], # check if [9, 0, 2] is in b
[False, False, False], # check if [2, 2, 9] is in b
[False, False, False], # check if [9, 2, 4] is in b
[False, False, False]], # check if [2, 5, 3] is in b
[[True, True, True],
[False, False, False],
[True, True, True],
[False, False, False],
[False, False, False]]]
或者输出可以是这样的,因为我们用像素值屏蔽了图像,因此可以省略第三维
array([[True,
False,
False,
False,
False],
[True,
False,
True,
False,
False]]
我已经尝试过这些,但它们对于我的需要来说太慢了:
# A naive way using list comprehension. Slowest I've tried
mask = [[True if np.any(b == a[r, c, :]) else False
for c in range(a.shape[1])] for r in range(a.shape[0])]
# I've tried this but it's probably a wrong solution since in1d flatten the array to compare
#them. I need the pixel to be compared across the 3rd dimension
mask = np.in1d(a[:, :, (?)], b, invert=True).reshape(image.shape[:2])
# Fastest I've tried. Took around 4 seconds on my machine on an image with dimension
# (3000, 3000, 3). But apparently it's not fast enough
mask = np.zeros(image.shape[:2], dtype=np.bool)
for val in b:
mask |= (a == b).all(-1)
感谢任何帮助:D
【问题讨论】:
-
请提供
a和b在真实环境中的实际预期尺寸。 -
@rayryeng 在我的用例中,a 的形状是 (3000, 3000, 3),而 b 的形状是 (16, 3)
标签: python numpy opencv image-processing matrix