Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt QImage shows wrong grayscale image

I want to visualize a matrix of integer values between 0 and 255 as a gray-scale image in Qt 5.12. First, I built a sample 256x256 uchar array with values between 0 and 255 in each row. then I tried to show the image with QImage and format_grayscale as the format. But confusingly, the resulting image contains disturbed pixels in the last rows.

The Resulting Image

I also created a gray-scale color map and tried with format_indexed8, but the same result. Here is my code.

uchar imageArray[256][256];
for (int i = 0; i < 256; i++)
{
    for (int j = 0; j < 256; j++)
    {
        imageArray[i][j] = uchar(j);
    }
}

QImage image(&imageArray[0][0],
                256,
                256,
                QImage::Format_Grayscale8);
like image 812
Moh Avatar asked Oct 16 '22 05:10

Moh


2 Answers

My guess is your buffer is deallocated and partially overwritten before you can get it displayed. It is your responsability to ensure the data buffer remains valid when using a constructor that does not perform a deep copy.

Quoting from the Qt documentation:

Constructs an image with the given width, height and format, that uses an existing memory buffer, data. The width and height must be specified in pixels. bytesPerLine specifies the number of bytes per line (stride).

The buffer must remain valid throughout the life of the QImage and all copies that have not been modified or otherwise detached from the original buffer. The image does not delete the buffer at destruction. You can provide a function pointer cleanupFunction along with an extra pointer cleanupInfo that will be called when the last copy is destroyed.

like image 80
zeFrenchy Avatar answered Oct 20 '22 04:10

zeFrenchy


You should not use a matrix but an array of size 256x256 = 65535 ,
So instead of :

uchar imageArray[256][256]; 

use :

uchar imageArray[65536];

Then fill your array with the values you want. Then, call the constructor of QImage :

QImage image(imageArray, 256, 256, QImage::Format_Grayscale8);
like image 31
Hayfa Avatar answered Oct 20 '22 03:10

Hayfa