depecheSoul
depecheSoul

Reputation: 956

Image converter in Qt, colored image to black-white

I am trying to make a simple program that converts colored images to black-white images.

So far I have made this.

void ObradaSlike::convert_picture_to_bw()
{
    QImage image;
    image.load(fileModel->fileInfo(listView->currentIndex()).absoluteFilePath());

    QSize sizeImage = image.size();
    int width = sizeImage.width(), height = sizeImage.height();

    QRgb color;
    int value;

    for (int f1=0; f1<width; f1++) {
        for (int f2=0; f2<height; f2++) {
            color = image.pixel(f1, f2);
            image.setPixel(f1, f2, QColor((qRed(color) + qGreen(color) + qBlue(color))/3).rgb());
        }
    }
    sceneGraphics->clear();
    sceneGraphics->addPixmap(QPixmap::fromImage(image));
}

I think the code should work, but there is a problem.

The problem with this code is that I always get blue-black images insted black-white images. Do you know how to fix this.

Thanks.

Upvotes: 3

Views: 4259

Answers (1)

WildCrustacean
WildCrustacean

Reputation: 5966

Try this instead:

int gray = qGray(color);
image.setPixel(f1, f2, qRgb(gray, gray, gray));

Note that qGray() actually computes luminosity using the formula (r*11 + g*16 + b*5)/32.

If you want to get a normal average like you are trying to do now:

int gray = (qRed(color) + qGreen(color) + qBlue(color))/3;
image.setPixel(f1, f2, qRgb(gray, gray, gray));

Upvotes: 8

Related Questions