`QImage` constructor has unknown keyword `data`(`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`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:`QImage` 构造函数有未知关键字 `data`
				
        
 
            
        基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 包装空间模型 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				