您的位置:首页 > 运维架构

OpenCV学习7--调整图像亮度和对比度

2018-03-15 10:57 615 查看
在opencv\sources\samples下面提供了很多的官方例程,是学习OpenCV的最好的资源。

理论:

图像变换可以看做如下:

像素变换–点操作

邻域变换–区域操作

其中图像亮度和对比度属于像素变换–点操作



α是对比度调节参数,

β是调节亮度。

一些主要API:

Mat new_image = Mat::zeros(image.size(),image.type()); //创建一个空白图像

saturate_cast< uchar>(value)确保值大小范围是0~255之间

Mat.at< Vec3b>(y,x)[index]=value //给每个像素点的每个通道赋值

代码参考:

#include<iostream>
#include<opencv2/core/core.hpp>
#include<highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <math.h>

using namespace cv;
using namespace std;

int main()
{
Mat src,dst;
src = imread("1.jpg");

char input_win[] = "input image";

namedWindow(input_win,CV_WINDOW_AUTOSIZE);
imshow(input_win,src);

int height = src.rows;
int width = src.cols;

double alpha = 5.2;   //对比度参数
double beta = 30;     //亮度参数
//src.convertTo(m1,CV_64F);
dst = Mat::zeros(src.size(),src.type());
for(int row = 0;row <height;row++){
for(int col = 0;col < width;col++){
if(src.channels() == 3){                  //三通道数据
float b = src.at<Vec3b>(row,col)[0];  //第一个通道是blue,第二个是green,第三个是red,每个像素是3个uchar类型的向量
float g = src.at<Vec3b>(row,col)[1];
float r = src.at<Vec3b>(row,col)[2];

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(src.channels() == 1){
float v = src.at<uchar>(row,col);
dst.at<uchar>(row,col) = saturate_cast<uchar>(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;
}


效果展示:

        


        

源码和原图片请到Github下载:

 https://github.com/MRwangmaomao/OpencvBrightnessTest-Project.git
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: