Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
106 views
in Technique[技术] by (71.8m points)

python - `QImage` constructor has unknown keyword `data`

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

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

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' is an unknown keyword argument

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

I am using anaconda environment to run this project.

opencv version = 3.1.4

pyqt version = 5.9.2

numpy version = 1.15.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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())

or you can use the qimage2ndarray library

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())

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...