python - 在另一个数组的条件下更改 numpy 数组

标签 python arrays performance numpy

我是 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 标签的所有可能颜色(因为标签范围为 010),这是一种使用 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/

相关文章:

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

MySQL 查询速度连接

javascript - 我可以为具有已知元素数量的映射/集预分配内存吗?

python - aiohttp应用进程中监听ZeroMQ

python - Django-rest框架结构不捕获post或put请求

c 编程 10 个数字中最大的一个。我的代码有什么问题吗?我没有得到输出

javascript - Ractivejs 中的递归部分超出调用堆栈

python - 在没有 WinAppDbg 的情况下使用 Python 捕获 3rd 方 exe 的崩溃

python - 使用 C 绑定(bind)导入代码的 Pickle 模块

javascript - 将 id 从单击的 div 推送到我的数组中