我是 python 新手,仍在尝试找到解决此问题的好方法:
我有一个二维数组label
存储图像的标签(从0到10;0是背景,1是树等)。我想从这个数组中创建一个 RGB 图像 rgb = np.zeros((height, width , 3), np.uint8)
,其中 rgb
中的每个像素将颜色取决于label
的值。例如,如果 label[4, 8] = 1
,则 rgb[4, 8] = green_color
。最有效的方法是什么?
最佳答案
假设您有一个名为 colors
的数组,其形状为 11 x 3
,其中包含 11
标签的所有可能颜色(因为标签范围为 0
到 10
),这是一种使用 integer indexing
的方法-
img = colors[label.ravel()].reshape(label.shape+(3,)).astype('uint8')
运行示例来验证输出 -
In [58]: label
Out[58]:
array([[ 2, 4, 0],
[ 2, 9, 10],
[ 6, 10, 10],
[ 4, 0, 4],
[ 1, 4, 10],
[ 8, 1, 7],
[ 9, 8, 0]])
In [59]: colors
Out[59]:
array([[ 28, 175, 15],
[ 0, 255, 0], # Green color at label = 1
[228, 12, 104],
[198, 135, 99],
[126, 124, 222],
[ 35, 78, 14],
[ 64, 61, 0],
[ 34, 49, 147],
[240, 1, 174],
[252, 1, 181],
[171, 114, 191]])
In [60]: img = colors[label.ravel()].reshape(label.shape+(3,))
In [61]: label[4,0]
Out[61]: 1
In [62]: img[4,0]
Out[62]: array([ 0, 255, 0])
In [63]: label[5,1]
Out[63]: 1
In [64]: img[5,1]
Out[64]: array([ 0, 255, 0])
关于python - 在另一个数组的条件下更改 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33899887/