Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a QImage to grayscale

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?

like image 232
sashoalm Avatar asked Jan 14 '15 18:01

sashoalm


People also ask

How do I convert a RGB image 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.

How do I convert my cv2 image to grayscale?

Step 1: Import OpenCV. Step 2: Read the original image using imread(). Step 3: Convert to grayscale using cv2. cvtcolor() function.


1 Answers

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

QImage image = ...;
image.convertToFormat(QImage::Format_Grayscale8);
like image 196
baislsl Avatar answered Sep 18 '22 07:09

baislsl