gpt4 book ai didi

python - 具有像素值列表的图像掩码

转载 作者:行者123 更新时间:2023-12-05 09:35:41 25 4
gpt4 key购买 nike

我想用列表中的值创建一个图像蒙版。例如,我有一个尺寸为 (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 channel (三维)。给定 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

最佳答案

您可以尝试将每个 RGB 像素与 [1,256,65536] 的点积“展平”为一个 24 位整数,然后您可以使用np.in1d():

# Get some deterministic randomness ;-)
np.random.seed(42)

# Synthesize (hopefully) representative image and 16 colours
a = np.random.randint(0,256,(3000, 3000, 3), np.uint8)
b = np.random.randint(0,256,(16, 3), np.uint8)

# "Flatten" third dimension to single 24-bit number
a24 = np.dot(a.astype(np.uint32),[1,256,65536])
b24 = np.dot(b.astype(np.uint32),[1,256,65536])

# Now use np.in1d()
mask = np.in1d(a24,b24)

在我的 Mac 上,时间如下:

%timeit a24 = np.dot(a.astype(np.uint32),[1,256,65536])
153 ms ± 1.43 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

%timeit mask = np.in1d(a24,b24)
93.4 ms ± 400 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

关于python - 具有像素值列表的图像掩码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65678363/

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