QImage:从灰度转换为具有颜色 table 的 RGB

QImage: convert from grayscale to RGB with a color table

使用 Qt,我尝试使用由颜色 table 定义的自定义转换规则将 Format_Indexed8 图像转换为 Format_RGB30。我认为这很简单,因为 QImage::convertToFormat 可以将颜色 table 作为参数,但我无法让它工作。

这是我的代码:

QImage image = QImage(data, width, height, QImage::Format_Indexed8);
QVector<QRgb> colorTable(256);
for (int i = 0; i < 255; i++)
    colorTable[i] = qRgb(255 - i, i, i);
image = image.convertToFormat(QImage::Format_RGB30, colorTable);

这段代码只是给我一个 RGB 格式的图像,但从灰度图像看,它看起来与眼睛完全相同。

我认为 QImage::convertToFormat 中的颜色 table 参数需要从 RGB 转换为索引,而您正在以相反的方式进行转换。

我会尝试直接在索引文件(源)中设置颜色 table,使用 QImage::setColorTable,然后调用 convertToFormat 仅传递格式参数:

QImage image = QImage(data, width, height, QImage::Format_Indexed8);
image.setColorTable(colorTable);
image = image.convertToFormat(QImage::Format_RGB30);

自 Qt 5.5(2015 年 7 月发布)以来,这不是必需的。您现在可以使用 QImage::Format_Grayscale8。您的代码很简单:

QImage image{data, width, height, QImage::Format_Grayscale8};