从元组到数组的高效转换?

2024-09-28 20:54:55 发布

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

我试图找到一种有效的方法来从元组(每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

Tags: 方法代码alphanumpyifchannel条目像素
2条回答

为什么不做些

import numpy as np
clientImage = np.array(list(bitmapBits), np.uint8).reshape(height, width, 4)

例如,让('Ri', 'Gi', 'Bi', 'ai')作为像素i对应的颜色元组。如果你有一个大元组,你可以:

In [9]: x = ['R1', 'G1', 'B1', 'a1', 'R2', 'G2', 'B2', 'a2', 'R3', 'G3', 'B3', 'a3', 'R4', 'G4', 'B4', 'a4']

In [10]: np.array(x).reshape(2, 2, 4)
Out[10]: 
array([[['R1', 'G1', 'B1', 'a1'],
        ['R2', 'G2', 'B2', 'a2']],

       [['R3', 'G3', 'B3', 'a3'],
        ['R4', 'G4', 'B4', 'a4']]], 
      dtype='|S2')

每片[:,:,i]i in [0,4)将为您提供每个通道:

In [15]: np.array(x).reshape(2, 2, 4)[:,:,0]
Out[15]: 
array([['R1', 'R2'],
       ['R3', 'R4']], 
      dtype='|S2')

与上面的法案类似,但可能更快:

clientImage = np.asarray(bitmapBits, dtype=np.uint8).reshape(height, width, 4)

根据文档所述,array接受“数组、任何暴露数组接口的对象、其__array__方法返回数组或任何(嵌套)序列的对象。”

asarray还需要一些东西:“输入数据,以任何可以转换为数组的形式。这包括列表、元组列表、元组、元组、列表元组和ndarrays

相关问题 更多 >