【问题标题】:NumPy - Efficient conversion from tuple to array?NumPy - 从元组到数组的高效转换?
【发布时间】: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


    【解决方案1】:

    类似于上面的比尔,但可能更快:

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

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

    asarray 需要更多的东西:“输入数据,可以转换为数组的任何形式。这包括列表、元组列表、元组、元组元组、列表元组和 ndarray。”它直接采用元组:)

    【讨论】:

    • 这确实稍微快了一点(就我目前的使用而言,它比 Bill 提出的解决方案快了大约 10%)。
    【解决方案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')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-22
      • 1970-01-01
      • 2021-12-18
      • 2012-04-18
      • 1970-01-01
      • 2016-11-16
      相关资源
      最近更新 更多