我试图找到一种有效的方法来从元组(每4个条目对应一个像素的R,G,B,alpha)转换为NumPy数组(在OpenCV中使用)。
更具体地说,我使用pywin32来获取窗口的客户端位图。这以元组的形式返回,其中前四个元素属于第一个像素的RGB alpha通道,然后是第二个像素的下四个,依此类推。元组本身只包含整数数据(也就是说,它不包含任何维度,尽管,我确实有这些信息)。从这个元组中,我想创建NumPy 3D数组(宽度x高度x通道)。目前,我只是创建一个0数组,然后遍历元组中的每个条目并将其放入NumPy数组中。我用下面的代码来做这个。我希望有一个更有效的方法来做这件事,我只是没有想到。有什么建议吗?非常感谢!
代码:
bitmapBits = dataBitmap.GetBitmapBits(False) #Gets the tuple.
clientImage = numpy.zeros((height, width, 4), numpy.uint8)
iter_channel = 0
iter_x = 0
iter_y = 0
for bit in bitmapBits:
clientImage[iter_y, iter_x, iter_channel] = bit
iter_channel += 1
if iter_channel == 4:
iter_channel = 0
iter_x += 1
if iter_x == width:
iter_x = 0
iter_y += 1
if iter_y == height:
iter_y = 0
为什么不做些
例如,让
('Ri', 'Gi', 'Bi', 'ai')
作为像素i
对应的颜色元组。如果你有一个大元组,你可以:每片
[:,:,i]
的i in [0,4)
将为您提供每个通道:与上面的法案类似,但可能更快:
根据文档所述,
array
接受“数组、任何暴露数组接口的对象、其__array__
方法返回数组或任何(嵌套)序列的对象。”asarray
还需要一些东西:“输入数据,以任何可以转换为数组的形式。这包括列表、元组列表、元组、元组、列表元组和ndarrays相关问题 更多 >
编程相关推荐