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;
    }
    
    // 单通道情况
    // 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; // 对比度
    float beta = 30; // 亮度
    
    /*
     若使用
     src.convertTo(m1, CV_32F);
     则在下面遍历的过程中不使用Vec3b,而是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;
}


阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页