Cookie
Cookie

Reputation: 688

QImage false coloring with Format Indexed8

I'm currently having som trouble with false-coloring a QImage with a colormap I generate. I have stripped down the code to some basic steps (usually distributed over multiple classes).

I can reproduce the problem with this code:

    //fill color table
    QVector< QRgb > colors;
    for (unsigned int i = 0; i < 256; ++i) {
        double fac = (double(i) / 255.) * 0.8;
        QColor color = QColor::fromHslF(fac, 0.95, 0.5);
        colors.push_front(color.rgba());
    }

    //load original
    QImage origImg;
    origImg.load("lena.jpg");
    QImage::Format f = origImg.format(); //outputs Format_Grayscale8 (24)
    origImg.save("out1.jpg");

    //convert to pixmap
    QPixmap pixmap;
    pixmap.convertFromImage(origImg);

    //convert back to Image
    QImage tmp = pixmap.toImage();
    tmp.save("out2.jpg");

    //make false color version
    QImage fc = QImage(tmp.bits(), tmp.width(), tmp.height(), QImage::Format_Indexed8);
    fc.setColorTable(colors);

    //save false color version
    fc.save("fc.jpg");

My temporary results out1.jpg and out2.jpg look fine (copies of the original) but the final result is broken. Can anybody tell me what is going wrong?

original image:

original image

output for fc.jpg

output for fc.jpg

Upvotes: 1

Views: 1817

Answers (1)

Ray B
Ray B

Reputation: 151

Change

QImage tmp = pixmap.toImage();

to

QImage tmp = pixmap.toImage().convertToFormat(QImage::Format_Grayscale8);

The QPixmap stores the image as RGB, so when you convert from QPixmap to QImage the format will be 32 bpp (Format_RGB32). Converting back to Format_Grayscale8, will give you the expected 8 bpp grayscale format.

Upvotes: 3

Related Questions