Sirop4ik
Sirop4ik

Reputation: 5243

How to apply gamma correction for cv::mat?

I am new to opencv. There is such a question: I have an image that I get and save this way

    Decoder decoder;
    decoder.HandleRequest_GetFrame(nullptr, filename, 1, image);
    cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
    bool isOk = cv::imwrite(save_location, image);

I need to apply gamma correction to the cv::mat before it is saved. I tried to google but it looks like openCV doesn't have a direct method like cv::gamma(image, 2.2) for this purpose.

How to do it?

Upvotes: 0

Views: 4317

Answers (2)

Sirop4ik
Sirop4ik

Reputation: 5243

Eventually, I found the way to do it (according to this tutorial https://docs.opencv.org/3.4/d3/dc1/tutorial_basic_linear_transform.html):

    //>>>Get Frame
    Decoder decoder;
    decoder.HandleRequest_GetFrame(nullptr, filename, 1, image);
    //<<<

    //>>> Collor conversion from BGR to RGB
    cv::cvtColor(image, image, cv::COLOR_BGR2RGB);
    //<<<

#if 1
    //>>> Gamma correction
    cv::Mat new_image = cv::Mat::zeros(image.size(), image.type());
    double alpha = 2.2; /*< Simple contrast control */
    int beta = 0;       /*< Simple brightness control */

    for (int y = 0; y < image.rows; y++) {
        for (int x = 0; x < image.cols; x++) {
            for (int c = 0; c < image.channels(); c++) {
                new_image.at<cv::Vec3b>(y, x)[c] =
                    cv::saturate_cast<uchar>(alpha*image.at<cv::Vec3b>(y, x)[c] + beta);
            }
        }
    }

    image = new_image;
    //<<<
#endif // 0

    bool isOk = cv::imwrite(save_location, image);

Upvotes: 0

TzviLederer
TzviLederer

Reputation: 137

Gamma correction is not directly implemented in opencv.
What you can do is to implement a lookup table that maps each value from 0 to 255 to the corresponding value after the gamma correction: ((value/255) ** (1/gamma)) * 255. After creating the LUT you can use the cv2.LUT to map the values of the image to the values after correction - cv2.LUT(image, table).

Link to python implementation:
https://www.pyimagesearch.com/2015/10/05/opencv-gamma-correction/#:~:text=There%20are%20two%20(easy)%20ways,range%20%5B0%2C%20255%5D.

Upvotes: 1

Related Questions