Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python NumPy-从元组到数组的高效转换?_Python_Arrays_Opencv_Numpy_Tuples - Fatal编程技术网

Python NumPy-从元组到数组的高效转换?

Python NumPy-从元组到数组的高效转换?,python,arrays,opencv,numpy,tuples,Python,Arrays,Opencv,Numpy,Tuples,我试图找到一种有效的方法,将元组(其中每4个条目对应一个像素的R、G、B、alpha)转换为NumPy数组(用于OpenCV) 更具体地说,我使用pywin32获取窗口的客户端位图。这以元组的形式返回,其中前四个元素属于第一个像素的RGB alpha通道,然后是第二个像素的下四个,依此类推。元组本身只包含整数数据(即,它不包含任何维度,尽管我有这些信息)。从这个元组中,我想创建NumPy 3D阵列(宽x高x通道)。目前,我只是创建一个零数组,然后遍历元组中的每个条目,并将其放入NumPy数组中。

我试图找到一种有效的方法,将元组(其中每4个条目对应一个像素的R、G、B、alpha)转换为NumPy数组(用于OpenCV)

更具体地说,我使用pywin32获取窗口的客户端位图。这以元组的形式返回,其中前四个元素属于第一个像素的RGB alpha通道,然后是第二个像素的下四个,依此类推。元组本身只包含整数数据(即,它不包含任何维度,尽管我有这些信息)。从这个元组中,我想创建NumPy 3D阵列(宽x高x通道)。目前,我只是创建一个零数组,然后遍历元组中的每个条目,并将其放入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

为什么不做些像这样的事情呢

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')
[0,4]中
i的每个片段
[:,:,i]
将为您提供每个频道:

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

与上面的Bill相似,但可能更快:

clientImage = np.asarray(bitmapBits, dtype=np.uint8).reshape(height, width, 4)
根据文档,
array
获取:“一个数组、公开数组接口的任何对象、一个其
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu


asarray
还需要一些东西:“输入数据,可以转换成数组的任何形式。这包括列表、元组列表、元组、元组的元组、列表的元组和数组。”它直接接受元组:)

这确实稍微快一点(对于我目前的使用,它比Bill提出的解决方案快10%左右)。