python - Python,索引和分配给 Np 数组
问题描述
为了提高速度,我想避免 forloops。我有一个看起来像的图像数组:
image = np.zeros_like(np.zeros(shape=(480,640,1)),dtype=np.uint8)
和一个类型化的 np 数组Events
,
dtype = [('x', '<f8'),('y', '<f8'),('grayVal','<u2')
其中'x' = 行和'y' = 图像数组的列。
问题是:如何将grayVal
in分配Events
给所有x
和y
in 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)
我错过了什么?谢谢您的帮助。
解决方案
我只能想到一个慢版本,现在有一个 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>
推荐阅读
- android - Android如何将触摸事件坐标发送到另一个不同尺寸和密度的屏幕并保留它?
- shell - Shellscript 打开 csvfile 并打印第 4 列,如果该字段为 null,则打印 null
- asp.net - 如何将数据存储在内存中并由其他按钮单击事件使用来显示数据?
- amazon-web-services - AWS 目的地不工作,我不知道为什么
- jython - 带有 jython 脚本的 wsadmin 给出错误 AttributeError: 'javapackage' object has no attribute 'SEC_SEGMENT'
- python - Python 3 - 'While loop' 验证用户输入是否在 2 个数字之间
- jquery - 使用键盘进行选择时的事件
- python - 如何为 jupyter notebook 手动安装 chromium?
- angular - PrimeNG 主题字体覆盖 Angular 应用程序字体
- javascript - 如何将 API 响应变量从服务传递到多个控制器