我需要用numpy数组构造一个图像。每个像素应该基于数组中的整数得到一个r,g,b,alpha值。为此,我编写了以下代码:
设r是一个整数从-2到0的数组
print(r)
array([[-1, -1, -1, ..., 0, 0, 0],
[-1, -1, -1, ..., 0, 0, 0],
[-1, -1, -1, ..., 0, 0, 0],
...,
[ 0, 0, 0, ..., 0, 0, 0],
[ 0, 0, 0, ..., 0, 0, 0],
[ 0, 0, 0, ..., 0, 0, 0]], dtype=int32)
颜色是一个编码r,g,b,alpha值的字典
print(colors)
{-2: ['0', '0', '0', '0'],
-1: ['1', '1', '1', '0.5'],
0: ['0', '0', '0', '0.5']}
要获得尺寸为a.shape[0],a.shape[1],4的图像,我执行以下操作
r = r.astype('int32')
im = r.reshape(r.shape[0]*r.shape[1])
im = [ colors[j] for j in im ]
im = np.reshape(im, (r.shape[0], r.shape[1], 4))
im = im.astype('float64')
toimage(im, cmin = 0, cmax = 1 ).save(dir_to + '/' + 'label' + '/' + str(zoom) + '/' + str(x) + '/' + str(y) + '.png')
这段代码工作得很好,但是对于一个只有256乘256的图像,运行时间已经超过了0.2秒。有人对如何优化这个有什么建议吗?你知道吗
不幸的是,numpy数组不允许我将数组广播到条目中
有一个办法-
对于特定的字典,
r
按降序排序,范围从-2
到0
,我们可以避免searchsorted
,这样就可以用类似这样的内容替换最后两个步骤(事实上也跳过获取k
)对于许多用于索引的重复索引,使用^{} 可能会有更好的性能。例如,对于给定的样本-
这执行得快很多,但还是有点间接的。。。你知道吗
相关问题 更多 >
编程相关推荐