1
colors = [ [0,0,0],\
[0, 255, 0],\
[0, 0, 255],\
[255, 0, 0]]
和索引numpy的矩阵输入2×2:
a = np.array([[0,1],[1,1]])
我如何映射到一个2x2x3矩阵b,其中b[i][j] = colors[a[i][j]]
?我想避免在这里使用for循环。
colors = [ [0,0,0],\
[0, 255, 0],\
[0, 0, 255],\
[255, 0, 0]]
和索引numpy的矩阵输入2×2:
a = np.array([[0,1],[1,1]])
我如何映射到一个2x2x3矩阵b,其中b[i][j] = colors[a[i][j]]
?我想避免在这里使用for循环。
你试过:
colors[a]
这里有一个完整的例子:
import numpy as np
colors = np.array([[0,0,0],
[0, 255, 0],
[0, 0, 255],
[255, 0, 0]
])
a = np.array([[0, 1], [1, 1]])
new = colors[a]
new.shape
# (2, 2, 3)
new
# array([[[ 0, 0, 0],
# [ 0, 255, 0]],
#
# [[ 0, 255, 0],
# [ 0, 255, 0]]])
请注意,您在这里重新定义颜色使用numpy的数组,否则你得到“OP颜色”的错误。 – agstudy
@agstudy,非常真实。如果'colors'是列表列表,则只能使用切片或整数对其进行索引。 –