Convert a QImage to grayscale

sashoalm picture sashoalm · Jan 14, 2015 · Viewed 19.5k times · Source

I have a QImage and I need to convert it to grayscale, then later paint over that with colors. I found an allGray() and isGrayScale() function to check if an image is already grayscale, but no toGrayScale() or similarly-named function.

Right now I'm using this code, but it's does not have a very good performance:

for (int ii = 0; ii < image.width(); ii++) {
    for (int jj = 0; jj < image.height(); jj++) {
        int gray = qGray(image.pixel(ii, jj));
        image.setPixel(ii, jj, QColor(gray, gray, gray).rgb());
    }
}

What would be the best way, performance-wise, to convert a QImage to grayscale?

Answer

baislsl picture baislsl · Nov 19, 2017

Since Qt 5.5, you can call QImage::convertToFormat() to convert a QImage to grayscale as follows:

QImage image = ...;
image.convertToFormat(QImage::Format_Grayscale8);