【发布时间】:2013-11-20 22:29:47
【问题描述】:
我正在尝试找到一种有效的方法将元组(其中每 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
【问题讨论】:
标签: python arrays opencv numpy tuples