QImage构造函数的关键字data未知 [英] `QImage` constructor has unknown keyword `data`

查看:381
本文介绍了QImage构造函数的关键字data未知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Suppose I am taking an image from the webcam using opencv.

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

然后我使用img创建一个QImage qimg:

Then I create a QImage qimg using img:

qimg = QImage(
    data=img,
    width=img.shape[1],
    height=img.shape[0],
    bytesPerLine=img.strides[0],
    format=QImage.Format_Indexed8)

但是它给出了一个错误:

But it gives an error saying that:

TypeError:数据"是一个未知的关键字参数

TypeError: 'data' is an unknown keyword argument

但是在文档中说,构造函数应该有一个名为data.

But said in this documentation, the constructor should have an argument named data.

我正在使用anaconda环境来运行此项目.

I am using anaconda environment to run this project.

opencv版本= 3.1.4

opencv version = 3.1.4

pyqt版本= 5.9.2

pyqt version = 5.9.2

numpy版本= 1.15.0

numpy version = 1.15.0

推荐答案

它们所指示的是,数据是参数所必需的,而不是将关键字称为data,以下方法将numpy/opencv转换为图片到QImage:

What they are indicating is that the data is required as a parameter, not that the keyword is called data, the following method makes the conversion of a numpy/opencv image to 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而不修改data时,解决方案是进行复制

When using the indexes to crop the image is only modifying the shape but not the data, the solution is to make a copy

img = cv2.imread('/path/of/image')
img = np.copy(img[200:500, 300:500, :]) # copy image
qimg = NumpyToQImage(img)
assert(not qimg.isNull())

这篇关于QImage构造函数的关键字data未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆