# 在numpy数组中映射值-问答-阿里云开发者社区-阿里云

## 在numpy数组中映射值

array([[ 1, 0, -1],

``````   [-1,  1,  1],
[ 0,  0,  1]])``````

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

``````   [(255, 0, 0), (0, 0, 255), (0, 0, 255)],
[(0, 255, 0), (0, 255, 0), (0, 0, 255)]])``````

Python

• 游客drl6uevi2k7uk
2019-07-17 23:26:22

palette = np.array( [ [0,0,0], # black
... [255,0,0], # red

... [0,255,0], # green
... [0,0,255], # blue
... [255,255,255] ] ) # white

image = np.array( [ [ 0, 1, 2, 0 ], # each value corresponds to a color in the palette

... [ 0, 3, 4, 0 ] ] )

palette[image] # the (2,4,3) color image

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

``````    [255,   0,   0],
[  0, 255,   0],
[  0,   0,   0]],
[[  0,   0,   0],
[  0,   0, 255],
[255, 255, 255],
[  0,   0,   0]]])
``````
0 0
• 一码平川MACHEL
2019-07-17 23:26:22

您可能想要考虑结构化数组，因为它允许没有数据类型的元组object。

import numpy as np

replacements = {-1: (255, 0, 0), 0: (0, 255, 0), 1: (0, 0, 255)}

arr = np.array([[ 1, 0, -1],

``````            [-1,  1,  1],
[ 0,  0,  1]])
``````

new = np.zeros(arr.shape, dtype=np.dtype([('r', np.int32), ('g', np.int32), ('b', np.int32)]))

for n, tup in replacements.items():

``````new[arr == n] = tup
``````

print(new)
输出：

[[( 0, 0, 255) ( 0, 255, 0) (255, 0, 0)]
[(255, 0, 0) ( 0, 0, 255) ( 0, 0, 255)]
[( 0, 255, 0) ( 0, 255, 0) ( 0, 0, 255)]]
另一个选择是使用3D数组，其中最后一个维度是3。第一个“层”是红色，第二个“层”是绿色，第三个“层”是蓝色。此选项与plt.imshow()。兼容。

import numpy as np

arr = np.array([[ 1, 0, -1],

``````            [-1,  1,  1],
[ 0,  0,  1]])
``````

new = np.zeros((*arr.shape, 3))

for i in range(-1, 2):

``new[i + 1, arr == i] = 255``

输出：

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

``````    [255.,   0.,   0.],
[  0.,   0.,   0.]],

[[  0., 255.,   0.],
[  0.,   0.,   0.],
[255., 255.,   0.]],

[[255.,   0.,   0.],
[  0., 255., 255.],
[  0.,   0., 255.]]])``````
0 0

+ 订阅