問題描述
假設我正在使用 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`的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!