Qt QImage 显示错误的灰度图像

Qt QImage shows wrong grayscale image

我想在 Qt 5.12 中将 0 到 255 之间的整数值矩阵可视化为灰度图像。首先,我构建了一个示例 256x256 uchar 数组,每行的值都在 0 到 255 之间。然后我尝试以 QImage 和 format_grayscale 作为格式显示图像。但令人困惑的是,生成的图像在最后一行中包含受干扰的像素。

结果图像

我还创建了一个灰度色图并尝试了 format_indexed8,但结果相同。这是我的代码。

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

您不应使用矩阵,而应使用大小为 256x256 = 65535 的数组,
所以而不是:

uchar imageArray[256][256]; 

使用:

uchar imageArray[65536];

然后用你想要的值填充你的数组。 然后,调用 QImage 的构造函数:

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

我的猜测是您的缓冲区在显示之前已被释放并被部分覆盖。当使用不执行深度复制的构造函数时,您有责任确保数据缓冲区保持有效。

引用自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.