QImage does not show image correctly as OpenCV does
-
I'm use the following code to do test.
class PP(QMainWindow): def __init__(self): super().__init__() loader = QUiLoader() self.main_ui = loader.load('test.ui') self.setCentralWidget(self.main_ui) img = cv2.imread('2222.png', cv2.IMREAD_GRAYSCALE) cv2.imshow('aa', img) cv2.waitKey() height, width = img.shape print('shape:', img.shape, 'dtype:', img.dtype) qimg = QImage(img.astype('uint8').data, width, height, QImage.Format_Grayscale8) self.main_ui.label.setPixmap(QPixmap(qimg)) self.show() if __name__ == '__main__': app = QApplication() ui = PP() app.exec()
When the image is '2222.png', the widget shows the same as OpenCV does. Th left window is called by OpenCV.
But if I change '2222.png' to another image, the widget shows weirdly. I want the widget (the right window) to show the same as OpenCV does.
The two image are both greyscale image and are bothuint8
dtype. But why is the difference? -
@feiyuhuahuo
I would say you have some "chunk" data in your file, that is causing an offset in the bytes -> the result is the shifted image. That chunkdata is probably the header. Did you simply change the ending/file extension of your image ?
Seems like opencv does some error corrections., but my guess is your image is not format conform. -
@J-Hilk Hi,the two images are saved by OpenCV.Write() function, and I did not simply change the ending/file extension.
I tried another initialization method of QImage.
I modified the code to:
qimg = QImage(img.astype('uint8').data, width, height, width*1, QImage.Format_Grayscale8)
And now the image shows correctly.
Can this exclude that the data of my image is error?