【发布时间】:2018-09-28 18:15:54
【问题描述】:
我正在尝试屏蔽一个图像,其中屏蔽值对应于列表中的多个值中的任何一个。
考虑以下“图像”和“像素值”
import numpy
img = numpy.arange(27).reshape(3,3,3) #something to represent an image
pixels = [numpy.array([0,1,2]), numpy.array([9,10,11])] #arbitrarily selected "pixel" values
我正在尝试提出一些程序,该程序将输出一个二维掩码数组,其中掩码值对应于列表中的像素值pixels
目标:
In [93]: mask
Out[93]:
array([[1, 0, 0],
[1, 0, 0],
[0, 0, 0]])
来自this answer的尝试1:
mask = numpy.zeros( img.shape[:2], dtype = "uint8" )
mask[numpy.in1d(img, pixels).reshape(mask.shape)] = 1
这导致ValueError: cannot reshape array of size 27 into shape (3,3)
我相信这个答案假设二维输入为img
尝试 2:
mask = numpy.zeros(img.shape[:2])
for x,y in [(x,y) for x in range(img.shape[0]) for y in range(img.shape[1])]:
if img[x,y,:] in pixels:
mask[x,y] = 1
这会产生ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(),但想象一下,有一种比循环遍历每个值更简洁的方法。
【问题讨论】: