灰度图像亮度对比度调整的简单代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了灰度图像亮度对比度调整的简单代码相关的知识,希望对你有一定的参考价值。

代码:

#include<opencv2/opencv.hpp>
using namespace cv;
int brightness = 5;
int contrast = 5;
Mat src;
Mat brightnessContrast;
void BrightnessContrastFilter(int, void*){
    float bri = brightness / 5.0f;
    float cont = contrast / 5.0f;
    //增亮图像
    cv::Mat bright = src*(bri);
    //平均亮度
    float sum = 0;
    for (int i = 0; i < bright.rows; i++){
        for (int j = 0; j < bright.cols; j++){
            sum += bright.at<uchar>(i, j);
        }
    }
    float aver = sum / (bright.cols*bright.rows);
    cv::Mat averImg = cv::Mat::ones(bright.rows, bright.cols, bright.type());
    averImg *= aver;
    //根据contrast进行插值
    brightnessContrast = (bright - averImg)*cont + averImg;
    imshow("brightnessContrast", brightnessContrast);
}

int main(){
    src = imread("densityGray.png", 0);
    imshow("src", src);
    namedWindow("brightnessContrast");
    createTrackbar("brightness", "brightnessContrast", &brightness, 20, BrightnessContrastFilter);
    createTrackbar("contrast", "brightnessContrast", &contrast, 20, BrightnessContrastFilter);
    BrightnessContrastFilter(0, 0);
    imshow("brightnessContrast", brightnessContrast);

    waitKey();
    destroyAllWindows();
    return 0;
}

效果:

技术分享

技术分享

 

以上是关于灰度图像亮度对比度调整的简单代码的主要内容,如果未能解决你的问题,请参考以下文章

灰度图像直方图变换的一些代码

MATLAB中如何将一幅图像改为不同的亮度级?

OpenCV图像处理

数字图像处理:图像的灰度变换(Matlab实现)

opencv中如何调整图像亮度和对比度,以及亮度和对比度调整的原理

投影仪灰度调多少好