Python 3.x 更改ndarray的维度并将内容相乘

Python 3.x 更改ndarray的维度并将内容相乘,python-3.x,numpy,python-imaging-library,Python 3.x,Numpy,Python Imaging Library,我有一个MxN ndarray,在这些数组中包含真值和假值,并希望将它们绘制为图像。 目标是将数组转换为枕头图像,每个真值作为恒定颜色。我可以通过循环每个像素并通过比较分别更改它们,然后在空白图像上绘制像素来让它工作,但这种方法太慢了 # img is a PIL image result # image is the MxN ndarray pix = img.load() for x in range(image.shape[0]): for y in range(image.shap

我有一个MxN ndarray,在这些数组中包含真值和假值,并希望将它们绘制为图像。 目标是将数组转换为枕头图像,每个真值作为恒定颜色。我可以通过循环每个像素并通过比较分别更改它们,然后在空白图像上绘制像素来让它工作,但这种方法太慢了

# img is a PIL image result
# image is the MxN ndarray

pix = img.load()
for x in range(image.shape[0]):
  for y in range(image.shape[1]):
     if image[x, y]:
       pix[y, x] = (255, 0, 0)

有没有办法通过将元组直接替换为真值来将ndarray更改为MxNx3?

如果您有真/假2D数组和颜色标签,例如
[255255255]
,以下操作将有效:

colored = np.expand_dims(bool_array_2d,axis=-1)*np.array([255,255,255])
用一个虚拟的例子来说明:在下面的代码中,我创建了一个0和1的随机矩阵,然后将1变成白色([255255])


希望这有助于

找到另一种解决方案,先转换为图像,然后转换为RGB,然后再转换回单独的3个通道。当我尝试将多个布尔数组组合在一起时,这种方法要快得多

img = Image.fromarray(image * 1, 'L').convert('RGB')
data = np.array(img)
red, green, blue = data.T
area = (red == 1)
data[...][area.T] = (255, 255, 255)
img = Image.fromarray(data)

我认为你可以这样简单快速地完成:

# Make a 2 row by 3 column image of True/False values
im = np.random.choice((True,False),(2,3))                                                             
array([[False, False,  True],
       [ True,  True,  True]])
我的看起来像这样:

# Make a 2 row by 3 column image of True/False values
im = np.random.choice((True,False),(2,3))                                                             
array([[False, False,  True],
       [ True,  True,  True]])
现在添加一个新轴,使其成为3通道,并将真值乘以新的“颜色”:

这就给了你:

array([[[  0,   0,   0],
        [  0,   0,   0],
        [255, 255, 255]],

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]]])

干得好!您可能需要将
.astype(np.uint8)
添加到末尾,否则它可能会显示为
int64
,并在RAM中占用8倍的空间,例如,PIL/Pillow可能无法将其保存为PNG。不过,我已经投了你一票:-)非常感谢。是的,我同意你的观点,在计算密集型或受限的情况下,完全有必要使用uint_8。谢谢你,这个解决方案绝对是我的目标。我确实找到了另一种解决方案,可以转换为图像,然后再转换回来,但这种方法更适用于numpy阵列。