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'是列表列表,則只能使用切片或整數對其進行索引。 –