python - 使用 PySide 将 QImage 转为 Numpy 数组

标签 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,因为这是 void* support 的一部分PyQt 的。

我的问题是:如何使用 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

关于python - 使用 PySide 将 QImage 转为 Numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19902183/

相关文章:

python - 如何按值(DESC)然后按键(ASC)对字典进行排序?

python - 导入错误 : No module named 'win32com' Python 3. 4

qt - 在Centos EL7上编译Meshlab

python - reshape numpy 数组的列表,然后 reshape 回来

python - Scipy KDTree 获取由两点定义的网格的矩形子集

qt - 使用 'cmd' 命令的 QProcess 不会导致命令行窗口

c++ - 在 Qt4 中使用最新的 Qt5 串口库

opencv - cv2.split() 不适用于超过 512 个 channel

python - 基于索引列表的列表中的累积添加

python - 在 python 中使用破折号上传文件并绘制条形图