您可能会考虑使用结构化数组,因为它允许不使用数据类型的元组
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)]]
另一个选项是使用三维数组,其中最后一个维度是
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.]]])