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?
Average method is the most simple one. You just have to take the average of three colors. Since its an RGB image, so it means that you have add r with g with b and then divide it by 3 to get your desired grayscale image. Its done in this way.
Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.
Since Qt 5.5, you can call QImage::convertToFormat() to convert a QImage to grayscale as follows:
QImage image = ...;
image.convertToFormat(QImage::Format_Grayscale8);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With