如何有效地将数组广播到数组中

2024-04-20 11:26:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要用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数组不允许我将数组广播到条目中


Tags: 代码图像alphanumpy整数像素数组print
2条回答

有一个办法-

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)]]

对于特定的字典,r按降序排序,范围从-20,我们可以避免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

这执行得快很多,但还是有点间接的。。。你知道吗

    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')

相关问题 更多 >