【发布时间】:2019-11-14 22:30:15
【问题描述】:
您好,我是 python 新手,我正在尝试将 2d numpy 数组保存到 png 文件中。
我的 2d numpy 数组中的每个元素都是 0 ~ 100 之间的整数,我有一个 getColor() 函数将其映射为 rgb 值。我现在正在做的方式是构建一个与我的 2d numpy 数组具有相同形状的 3 通道 numpy 数组,并将每个值映射到相应的 rgb 值。然而,这需要很多时间,我觉得应该有一个更有效的方法来做到这一点。我的代码目前处理一张图像大约需要 5 秒。
import numpy as np
import imageio
flt_m = get2dArray() # returns a (880*880) numpy array
def getColor(value):
if(value < 0):
return (0,0,0)
elif(value < 50):
return (100,150,200)
else:
return (255,255,255)
canvas = np.zeros((flt_m.shape[0], flt_m.shape[1], 3)).astype(np.uint8)
for row in range(flt_m.shape[0]):
for col in range(flt_m.shape[1]):
rgb = getColor(flt_m[row, col])
for i in range(3):
canvas[row, col, i] = rgb[i]
imageio.imwrite('test.png', canvas) # saves file to png
【问题讨论】:
-
您的问题是您的值范围为 0..100,但您的代码测试负值?
-
你试过
canvas[row, col] = rgb吗?模块pillow也可以将 numpy.array 转换为图像 - Image.fromarray 并且可能会更快。