简体   繁体   中英

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);

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM