2
以下脚本根据列表中包含的颜色渐变创建RGB数组。数组“卷心菜”的元素是“黄瓜”列表的索引。下面的脚本创建一个与'cabbage'形状相同的数组'花椰菜',但其索引被替换为来自'黄瓜'的相应元组。 Numpy有没有更直接的方法来执行这个程序?以元素作为其他对象索引的Numpy数组
from numpy import array, shape, zeros
cabbage = array([[0,3,2],[3,2,1],[3,1,0]])
cucumber=[(0,100,0),(0,150,0),(0,200,0),(0,255,0)]
rows ,cols = shape(cabbage)
cauliflower = zeros((rows,cols),dtype=object)
for row in range(rows):
for col in range(cols):
cauliflower[row,col]=cucumber[cabbage[row,col]]
print cauliflower
[[(0, 100, 0) (0, 255, 0) (0, 200, 0)]
[(0, 255, 0) (0, 200, 0) (0, 150, 0)]
[(0, 255, 0) (0, 150, 0) (0, 100, 0)]]
这是我的第一个想法 - 但它不符合的是相同的形状... – 2012-08-04 15:39:47
形状可要求(3,3,3- )而不是(3,3),但它仍然给我留下了深刻的印象!碰巧,我的图像数组需要使用dtype ='uint8'作为3d的PIL fromarray()函数。 – Naaaysmith 2012-08-04 17:08:14