weiwen
weiwen

Reputation: 466

Incorrect image display in QGraphicsScene, PyQt

I'm faced with a strange problem while I'd like to display an image with a QGraphicsScene inside a QGraphicsView in PyQt.

For some image files it works well,

image1 display of image1

but for others it seems wrong,

image2 display of image2

i think maybe it's related with the format of the images? If so, what should I do?

Related part of codes are as follows, thanks for your kind help :D

image = cv2.imread(str(file_path))
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
height, width = image.shape[:2]

self.scene.clear()
self.frame = QtGui.QImage(image.data, width, height, QtGui.QImage.Format_RGB888)
self.scene.addPixmap(QtGui.QPixmap.fromImage(self.frame))
self.scene.update()
self.graphicsView.setScene(self.scene)

Upvotes: 0

Views: 1359

Answers (1)

Jablonski
Jablonski

Reputation: 18524

I had absolutely same issue, but it was C++ project, so I think that my solution will work for you too. Consider next code:

   QString sss = "path";
   cv::Mat img = cv::imread(sss.toStdString());

   cv::cvtColor(img,img,CV_BGR2RGB);//in your code cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
   QImage image1((uchar*)img.data,img.cols,img.rows,QImage::Format_RGB888);
   //in your code QtGui.QImage(image.data, width, height, QtGui.QImage.Format_RGB888)
   //same problem
   QPixmap px1(QPixmap::fromImage(image1));
   ui->label_2->setPixmap(px1);

Solution:

//...
QImage image1((uchar*)img.data,img.cols,img.rows,img.step,QImage::Format_RGB888);
//...

As you can see, I added one more argument: img.step ( int bytesPerLine ) in Qt documentation. So try to do the same in your python app.

Upvotes: 0

Related Questions