2

I'm working on a homework for my Digital Image Processing class, and I'm using OpenCV with QT Framework.

I've created a class ImageDisplay, which is as sub class of the QWidget class.

I've using OpenCV to manipulate a grayscale image, and then creating a QImage object from the Mat object. After that I use the QWidget::drawImage() to draw the image. But sometimes it shows a distorted, angled image.

I was experimenting and discovered that it has something to do with the image dimensions.

For instance, this image with 320x391 pixels is rendered normally The image with 320x391 pixels is rendered normally

But if change the dimension to 321x391 (using Gimp), it shows up like this: The image with 321x391 pixels is rendered anormally

This is the code for the paintEvent method:

void ImageDisplay::paintEvent(QPaintEvent *){
   QPainter painter(this);
   Mat tmp;
   /* The mat in the next line is a Mat object that contains the image data */
   cvtColor(mat, tmp, CV_GRAY2BGR);
   QImage image(tmp.data, tmp.cols, tmp.rows, QImage::Format_RGB888);
   painter.drawImage(rect(), image);
}

Does anyone has a clue what is the problem and how to fix it?

Thanks in advance!

Alexandre Justino
  • 1,716
  • 1
  • 19
  • 28
  • 1
    Where are you resizing the image? It seems that you changed the dimensions, but using the old data buffer (with old dimension). You can see this looking at the bottom black row of your _tilted_ image – Miki Aug 20 '16 at 19:46
  • Oh, no. I didn't resize the image using code. I just used gimp and changed the image size. – Alexandre Justino Aug 21 '16 at 19:51

1 Answers1

3

I think you may need to specify the step of the image (number of bytes per line) when creating QImage in the fourth parameter:

QImage image((const uchar*) tmp.data, tmp.cols, tmp.rows, tmp.step, QImage::Format_RGB888);
ikaro
  • 703
  • 6
  • 10
  • Wow, this worked! Thank you very much!! Can you explain what this parameter does? – Alexandre Justino Aug 24 '16 at 00:35
  • 2
    I'll try... for optimization, opencv store the image in a determinate number of pixels per row that is not exactly the width of the image (you may want a 14 pixel width image but opencv create a 16 pixel width). Step parameter tells 16, but cols tells 14. – ikaro Aug 24 '16 at 07:58