QImage to Numpy Array using PySide



我目前正在从PyQt切换到PySide。

使用

PyQt,我使用我在 SO 上找到的以下代码将QImage转换为Numpy.Array

def convertQImageToMat(incomingImage):
    '''  Converts a QImage into an opencv MAT format  '''
    incomingImage = incomingImage.convertToFormat(4)
    width = incomingImage.width()
    height = incomingImage.height()
    ptr = incomingImage.bits()
    ptr.setsize(incomingImage.byteCount())
    arr = np.array(ptr).reshape(height, width, 4)  #  Copies the data
    return arr

但是ptr.setsize(incomingImage.byteCount())不适用于PySide,因为这是PyQt void*支持的一部分。

我的问题是:如何使用 PySide 将 QImage 转换为Numpy.Array

编辑:

Version Info
> Windows 7 (64Bit)
> Python 2.7
> PySide Version 1.2.1
> Qt Version 4.8.5
对我来说

constBits()的解决方案不起作用,但以下方法有效:

def QImageToCvMat(incomingImage):
    '''  Converts a QImage into an opencv MAT format  '''
    incomingImage = incomingImage.convertToFormat(QtGui.QImage.Format.Format_RGBA8888)
    width = incomingImage.width()
    height = incomingImage.height()
    ptr = incomingImage.bits()
    ptr.setsize(height * width * 4)
    arr = np.frombuffer(ptr, np.uint8).reshape((height, width, 4))
    return arr
诀窍

是按照@Henry Gomersall的建议使用QImage.constBits()。我现在使用的代码是:

def QImageToCvMat(self,incomingImage):
    '''  Converts a QImage into an opencv MAT format  '''
    incomingImage = incomingImage.convertToFormat(QtGui.QImage.Format.Format_RGB32)
    width = incomingImage.width()
    height = incomingImage.height()
    ptr = incomingImage.constBits()
    arr = np.array(ptr).reshape(height, width, 4)  #  Copies the data
    return arr

PySide 似乎没有提供bits方法。如何使用 constBits 来获取指向数组的指针?

最新更新