OpenCV学习第七篇:调整图像亮度和对比度

我们经常遇到需要调整图片亮度和对比度的地方:
Mat new image = Mat::zeros(iamge.size(),image.type());
创建一张跟原图像大小和类型一致的空白图像,像素值初始化为0;
saturate_cast(value)确保值在0-255之间;
Mat.at(y,x)[index] = value每个像素点每个通道赋值
这里是测试代码:

#include 
#include 
#include 

using namespace cv;
using namespace std;

int main(int argc, char** argv) {
    Mat src, dst;
    src = imread("F:/识图/测试1.JPG");
    if (src.empty())
    {
        printf("没有找到图片!");
        return -1;
    }

    char input_win[] = "input image";
    namedWindow(input_win, CV_WINDOW_AUTOSIZE);
    imshow(input_win, src);

    int height = src.rows;
    int width = src.cols;
    dst = Mat::zeros(src.size(), src.type());
    float alpha = 2;
    float beta = 30;

    Mat m1;
    src.convertTo(m1, CV_32F);

    for (int row = 0; row < height; row++)
    {
        for (int col = 0; col < width; col++)
        {
            if (src.channels()==3)
            {           
                float b = m1.at(row, col)[0];
                float g = m1.at(row, col)[1];
                float r = m1.at(row, col)[2];

                dst.at(row, col)[0] = saturate_cast(b*alpha + beta);
                dst.at(row, col)[1] = saturate_cast(g*alpha + beta);
                dst.at(row, col)[2] = saturate_cast(r*alpha + beta);
            }
            else if(src.channels()==1)
            {
                float v = src.at(row, col);
                dst.at(row, col) = saturate_cast(v*alpha + beta);
            }
        }
    }
    char output_title[] = "contrast and brightness change demo!";
    namedWindow(output_title, CV_WINDOW_AUTOSIZE);
    imshow(output_title, dst);
    waitKey(0);
    return 0;
}

效果:
OpenCV学习第七篇:调整图像亮度和对比度_第1张图片
OpenCV学习第七篇:调整图像亮度和对比度_第2张图片

你可能感兴趣的:(OpenCV学习旅程)