Python 如何有效地将数组广播到数组中
我需要用numpy数组构造一个图像。每个像素都应该基于数组中的整数获得r、g、b、alpha值。为此,我编写了以下代码: 设r是一个整数范围为-2到0的数组Python 如何有效地将数组广播到数组中,python,numpy,Python,Numpy,我需要用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
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 x 256的图像,运行时间已超过0.2秒。有人对如何优化这一点有什么建议吗
不幸的是,numpy数组不允许我将数组广播到条目中。 这执行速度要快得多,但还是有点间接
r = r.astype('int32')
im = np.zeros((256,256,4))
for i in [0,1,2,3]:
for key in colors.keys():
im[r == key,i] = colors[key][i]
im = im.astype('float64')
toimage(im, cmin = 0, cmax = 1 ).save(dir_to + '/' + 'label' + '/' + str(zoom) + '/' + str(x) + '/' + str(y) + '.png')
这里有一条路-
v = np.array(list(colors.values()), dtype=float)
k = np.array(list(colors.keys()), dtype=int)
sidx = k.argsort()
out = v[sidx[k.searchsorted(r,sorter=sidx)]]
对于按降序排序且范围从-2到0的特定字典r,我们可以避免searchsorted,从而替换最后两个,实际上也可以用类似的方式跳过获取k步骤-
out = v[-r]
对于许多用于索引的重复索引,使用可能会有更好的性能。例如,对于给定的样本-
In [195]: r = np.random.randint(-2,1,(400,500))
In [196]: %timeit v[-r]
100 loops, best of 3: 3.06 ms per loop
In [197]: %timeit np.take(v,-r,axis=0)
1000 loops, best of 3: 1.45 ms per loop
请您的职位提供一个-目前,不可能运行您的代码是否发布的解决方案为您工作?Divakar的解决方案执行比我自己提出的解决方案快一点,但都DOE的伎俩,并比我上面做的快。考虑接受一个最适合您的发布解决方案?