使用PySide对Numpy数组进行QImage

时间:2013-11-11 08:48:59

标签: python qt numpy pyqt 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* support的一部分。

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

编辑:

Version Info
> Windows 7 (64Bit)
> Python 2.7
> PySide Version 1.2.1
> Qt Version 4.8.5

3 个答案:

答案 0 :(得分:3)

诀窍是使用@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

答案 1 :(得分:2)

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

答案 2 :(得分:1)

对我来说,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
相关问题