Simple way to change contrast and brightness in OpenCV

dst(i, j) = α · src(i, j) + β

α and β in the above formula affects respectively contrast and brightness


#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>


using namespace std;
using namespace cv;


int main() {
    Mat src1, src2, gray_src, dst;
    src1 = imread("/Users/apple/Desktop/test.jpg", IMREAD_COLOR);
    //src2 = imread("/Users/apple/Desktop/test2.jpg", IMREAD_COLOR);
    if (src1.empty()) { // if (!src.data())
        cout << "could not load image..." << endl;
        return -1;
    }
    
    // single channel case
    // cvtColor(src1, src1, CV_BGR2GRAY);
    
    string input = "input image";
    namedWindow(input, CV_WINDOW_AUTOSIZE);
    imshow(input, src1);
    
    
    // contrast and brightness changes
    int height = src1.rows;
    int width = src1.cols;
    dst = Mat::zeros(height, width, src1.type());
    float alpha = 1.2; // contrast
    float beta = 30; // brightness
    
    /*
     If using
     src.convertTo(m1, CV_32F);
     Then in the following traversal process, Vec3b is not used, but Vec3f.
     */
     
    
    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            if (src1.channels() == 3) {
                int b = src1.at<Vec3b>(row, col)[0]; // blue
                int g = src1.at<Vec3b>(row, col)[1]; // green
                int r = src1.at<Vec3b>(row, col)[2]; // red
                
                dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(b * alpha + beta);
                dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(g * alpha + beta);
                dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(r * alpha + beta);
            }
            else if (src1.channels() == 1) {
                int v = src1.at<uchar>(row, col);
                dst.at<uchar>(row, col) = saturate_cast<uchar>(v * alpha + beta);
            }
        }
    }
    
    imshow("output", dst);
    
    waitKey(0);
    
    return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325620258&siteId=291194637