更改ndarray的维数并乘以内容

时间:2019-04-02 01:44:51

标签: python-3.x numpy python-imaging-library

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

# 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)

是否可以通过将元组直接替换为True值来将ndarray更改为MxNx3?

3 个答案:

答案 0 :(得分:1)

如果您拥有True / False 2D数组和颜色标签,例如[255,255,255],则可以使用以下方法:

colored = np.expand_dims(bool_array_2d,axis=-1)*np.array([255,255,255])

通过一个虚拟示例进行说明:在下面的代码中,我创建了一个0和1的随机矩阵,然后将1转换为白色([255,255,255])。

import numpy as np
import matplotlib.pyplot as plt

array = np.random.randint(0,2, (100,100))
colors = np.array([255,255,255])
colored = np.expand_dims(array, axis=-1)*colors

plt.imshow(colored)

希望这对您有所帮助

答案 1 :(得分:1)

找到另一种解决方案,先转换为图像,然后转换为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)

答案 2 :(得分:0)

我认为您可以像这样简单而快速地做到这一点:

# 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通道,并将真值乘以新的“颜色”

result = im[..., np.newaxis]*[255,255,255]                                                                     

为您提供了这一点:

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

       [[255, 255, 255],
        [255, 255, 255],
        [255, 255, 255]]])
相关问题