`QImage`构造函数有未知关键字`data`

2024-10-01 11:41:32 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我正在使用opencv从网络摄像头拍摄图像。在

_, img = self.cap.read()  # numpy.ndarray (480, 640, 3)

然后我使用img创建一个QImageqimg:

^{pr2}$

但错误的说法是:

TypeError: 'data' is an unknown keyword argument

但是在this文档中,构造函数应该有一个名为data的参数。在

我正在使用水蟒环境来运行这个项目。在

opencv version = 3.1.4

pyqt version = 5.9.2

numpy version = 1.15.0


Tags: 图像self网络numpyimgreaddataversion
2条回答

我怀疑它用TypeError: 'data' is an unknown keyword argument出错,因为这是它遇到的第一个参数。在

链接类引用用于PyQt4,对于PyQt5,它链接到位于https://doc.qt.io/qt-5/qimage.htmlC++文档,但相似之处很明显。在

PyQt4:

QImage.__init__ (self, bytes data, int width, int height, int bytesPerLine, Format format)

Constructs an image with the given width, height and format, that uses an existing memory buffer, data. The width and height must be specified in pixels. bytesPerLine specifies the number of bytes per line (stride).

PyQt5 (C++):

QImage(const uchar *data, int width, int height, int bytesPerLine, QImage::Format format, QImageCleanupFunction cleanupFunction = nullptr, void *cleanupInfo = nullptr)

Constructs an image with the given width, height and format, that uses an existing memory buffer, data. The width and height must be specified in pixels. bytesPerLine specifies the number of bytes per line (stride).

根据https://www.programcreek.com/python/example/106694/PyQt5.QtGui.QImage中的示例,您可以尝试

qimg = QImage(img, img.shape[1], img.shape[0], img.strides[0], QImage.Format_Indexed8)

(没有数据=宽度=等)

他们所表示的是数据是必需的参数,而不是关键字被称为data,下面的方法将numpy/opencv图像转换为QImage:

from PyQt5.QtGui import QImage, qRgb
import numpy as np
import cv2

gray_color_table = [qRgb(i, i, i) for i in range(256)]

def NumpyToQImage(im):
    qim = QImage()
    if im is None:
        return qim
    if im.dtype == np.uint8:
        if len(im.shape) == 2:
            qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_Indexed8)
            qim.setColorTable(gray_color_table)
        elif len(im.shape) == 3:
            if im.shape[2] == 3:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_RGB888)
            elif im.shape[2] == 4:
                qim = QImage(im.data, im.shape[1], im.shape[0], im.strides[0], QImage.Format_ARGB32)
    return qim

img = cv2.imread('/path/of/image')
qimg = NumpyToQImage(img)
assert(not qimg.isNull())

或者您可以使用qimage2ndarray

当使用索引裁剪图像时,只修改shape,而不是{},解决方案是制作一个副本

^{pr2}$

相关问题 更多 >