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?
Since Qt 5.5, you can call QImage::convertToFormat() to convert a QImage to grayscale as follows:
QImage image = ...;
image.convertToFormat(QImage::Format_Grayscale8);