Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Python Opencv Image (numpy array) to PyQt QPixmap image

Tags:

I am trying to convert python opencv image to QPixmap.

I follow the instruction shows Page Link and 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?

like image 267
SimaGuanxing Avatar asked Dec 11 '15 21:12

SimaGuanxing


People also ask

How do you convert QImage to QPixmap?

A QPixmap object can be converted into a QImage using the toImage() function. Likewise, a QImage can be converted into a QPixmap using the fromImage(). If this is too expensive an operation, you can use QBitmap::fromImage() instead.

Does OpenCV work with Numpy array?

OpenCV is the most popular computer vision library and has a wide range of features. It doesn't have its own internal storage format for images, instead, it uses NumPy arrays.

How do I add an image to PYQT?

From the property editor dropdown select "Choose File…" and select an image file to insert. As you can see, the image is inserted, but the image is kept at its original size, cropped to the boundaries of the QLabel box. You need to resize the QLabel to be able to see the entire image.

Is cv2 Imread a Numpy array?

OpenCV cv2 imread() You can read image into a numpy array using opencv library. The array contains pixel level data. And as per the requirement, you may modify the data of the image at a pixel level by updating the array values.


2 Answers

Use this to convert cvImage to Qimage, here cvImage is the original image.

height, width, channel = cvImg.shape bytesPerLine = 3 * width qImg = QImage(cvImg.data, width, height, bytesPerLine, QImage.Format_RGB888) 

and set this Qimage to Label.setPixmap parameter from Qimage. It works!!!

like image 74
AdityaIntwala Avatar answered Sep 18 '22 12:09

AdityaIntwala


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:

height, width, channel = cvImg.shape bytesPerLine = 3 * width qImg = QImage(cvImg.data, width, height, bytesPerLine, QImage.Format_RGB888).rgbSwapped() 
like image 37
Sergio Montazzolli Avatar answered Sep 20 '22 12:09

Sergio Montazzolli