Conversion method between Pyqt QImage and np array

  • 2021-07-03 00:29:38
  • OfStack

The project uses Pyqt as the UI framework, uses camera threads to capture image and display it in QGraphicsView, and encounters the following issues:

1. The collected data is nparray data, and the conversion code to be converted into QImage is as follows:


img=cv2.resize(src=img,dsize=None,fx=0.2,fy=0.2)
img2=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
self._image = QtGui.QImage(img2[:],img2.shape[1], img2.shape[0],img2.shape[1] * 3, QtGui.QImage.Format_RGB888)

Note: bytesPerLine parameter in QImage (uchar * data, int width, int height, int bytesPerLine, Format format) cannot be omitted, which is responsible for causing Qimage data error and abnormal display picture. This parameter is set to width*image. channels of image

2. If the thread collecting data is a non-UI thread, not only the Item object needs to be added when displaying in QGraphicsView, but also the update display thread needs to be in the UI thread. Otherwise, QGraphicsView will not update the display actively, and the image can be updated in the UI thread by using the signal

3. Ensure that when UI is updated, the image that needs to be updated has not been destroyed. Because it is in different threads, image can be stored in objects that will not be destroyed before updating


Related articles: