简体   繁体   English

Qt QImage显示错误的灰度图像

[英]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. 我想在Qt 5.12中将0到255之间的整数值矩阵可视化为灰度图像。 First, I built a sample 256x256 uchar array with values between 0 and 255 in each row. 首先,我构建了一个样本256x256 uchar数组,每行的值介于0和255之间。 then I tried to show the image with QImage and format_grayscale as the format. 然后我尝试用QImage和format_grayscale作为格式显示图像。 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. 我还创建了一个灰度色彩图,并尝试使用format_indexed8,但结果相同。 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 : 引用Qt文档

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). bytesPerLine指定每行的字节数(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. 缓冲区必须在QImage的整个生命周期内保持有效,并且所有未复制或以其他方式从原始缓冲区中分离的副本都必须保持有效。 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. 您可以提供一个函数指针cleanupFunction以及一个额外的指针cleanupInfo,它将在销毁最后一个副本时被调用。

You should not use a matrix but an array of size 256x256 = 65535 , 您不应该使用矩阵,而是使用大小为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的构造函数:

QImage image(imageArray, 256, 256, QImage::Format_Grayscale8);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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