将 Python Opencv 图像(numpy 数组)转换为 PyQt QPixmap 图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34232632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Python Opencv Image (numpy array) to PyQt QPixmap image
提问by SimaGuanxing
I am trying to convert python opencv image to QPixmap.
我正在尝试将 python opencv 图像转换为 QPixmap。
I follow the instruction shows Page Linkand my code is attached below
我按照说明显示页面链接,我的代码附在下面
img = cv2.imread('test.png')[:,:,::1]/255.
imgDown = cv2.pyrDown(img)
imgDown = np.float32(imgDown)
cvRGBImg = cv2.cvtColor(imgDown, cv2.cv.CV_BGR2RGB)
qimg = QtGui.QImage(cvRGBImg.data,cvRGBImg.shape[1], cvRGBImg.shape[0], QtGui.QImage.Format_RGB888)
pixmap01 = QtGui.QPixmap.fromImage(qimg)
self.image01TopTxt = QtGui.QLabel('window',self)
self.imageLable01 = QtGui.QLabel(self)
self.imageLable01.setPixmap(pixmap01)
The code has no compile and runtime error but the conversion is wrong and I just get some noise image. I am not sure what the problem is. Could anyone help?
代码没有编译和运行时错误,但转换是错误的,我只是得到了一些噪声图像。我不确定问题是什么。有人可以帮忙吗?
回答by SkyCityRuler
#image is the numpy array that you got from cv2.imread(example_image.jpg)
image = QtGui.QImage(image, image.shape[1],\
image.shape[0], image.shape[1] * 3,QtGui.QImage.Format_RGB888)
pix = QtGui.QPixmap(image)
self.scene.addPixmap(pix)
回答by AdityaIntwala
Use this to convert cvImage to Qimage, here cvImage is the original image.
用它来将 cvImage 转换为 Qimage,这里的 cvImage 是原始图像。
height, width, channel = cvImg.shape
bytesPerLine = 3 * width
qImg = QImage(cvImg.data, width, height, bytesPerLine, QImage.Format_RGB888)
and set this Qimage to Label.setPixmapparameter from Qimage. It works!!!
并将这个 Qimage 设置为 Label。来自 Qimage 的setPixmap参数。有用!!!
回答by Sergio Montazzolli
Just complementing the answer of AdityaIntwala, if the image appears to be red or blue, it is because the format is not RGB, but BGR (the inverse). In this case, use the QImage.rgbSwapped method to correct:
只是补充AdityaIntwala的回答,如果图像出现红色或蓝色,那是因为格式不是RGB,而是BGR(反之)。在这种情况下,使用 QImage.rgbSwapped 方法来更正:
height, width, channel = cvImg.shape
bytesPerLine = 3 * width
qImg = QImage(cvImg.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped()
回答by so860
Hate to add to the large number of answers, but as this was the only thing that worked for me I will, in case others run into the same issue.
不想添加大量答案,但由于这是唯一对我有用的方法,以防其他人遇到同样的问题。
As mentioned here on GitHub
正如在 GitHub 上提到的
Wrap the numpy array/ndarry in a np.require(array, np.uint8, 'C')
call first, such as:
首先将 numpy 数组/ndarry 包裹在一个np.require(array, np.uint8, 'C')
调用中,例如:
arr2 = np.require(arr, np.uint8, 'C')
qImg = QtGui.QImage(arr2, width, height, QtGui.QImage.Format_RGB888)