首页 > 解决方案 > Python,索引和分配给 Np 数组

问题描述

为了提高速度,我想避免 forloops。我有一个看起来像的图像数组: image = np.zeros_like(np.zeros(shape=(480,640,1)),dtype=np.uint8) 和一个类型化的 np 数组Eventsdtype = [('x', '<f8'),('y', '<f8'),('grayVal','<u2') 其中'x' = 行和'y' = 图像数组的列。

问题是:如何将grayValin分配Events给所有xyin image

到目前为止,我尝试过(并且更多无法显示): For 循环:

for event in Events:
    image[event['y'],event['x']] = event['grayVal']

和索引

events['y'].shape
(98210,)
events['x'].shape
(98210,)
events['grayVal'].shape
(98210,)
image[np.ix_(events['y'],events['x'])] = events['grayVal']

由于错误消息,这在某种程度上不起作用:

ValueError: shape mismatch: value array of shape (98210,) could not be broadcast to indexing result of shape (98210,98210,1)

我错过了什么?谢谢您的帮助。

标签: pythonarraysnumpy

解决方案


我只能想到一个慢版本,现在有一个 for 循环。但如果数组是稀疏的,那可能没问题。也许其他人可以将其矢量化。

import numpy as np

image =  np.zeros(shape=(3,4 ),dtype=np.uint8)  # image is empty
 
# evy is just a bag of nonzero pixels

evy=np.zeros(shape=(3), dtype = [('x', '<u2'),('y', '<u2') ,('grayVal','<u2') ])
evy[0]=(1,1,128)
evy[1]=(0,0,1)
evy[2] =(2,3,255) 
 #slow version
for i in range(3):
    image[evy[i][0],evy[i][1]]=evy[i][2]
        

输出:

array([[  1,   0,   0,   0],
       [  0, 128,   0,   0],
       [  0,   0,   0, 255]], dtype=uint8)

​</p>


推荐阅读