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

查看:28
本文介绍了`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: 'data' 是一个未知的关键字参数

TypeError: 'data' is an unknown keyword argument

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

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作为参数,而不是关键字叫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天全站免登陆