理论
- 图像变换可以看作如下:
- 像素变换 – 点操作
- 邻域操作 – 区域
调整图像亮度和对比度属于像素变换-点操作
g
(
i
,
j
)
=
α
f
(
i
,
j
)
+
β
g(i,j) = αf(i,j) + β
g(i,j)=αf(i,j)+β (其中 α>0,β是增益变量)
- 重要的API
Mat new_image = Mat::zeros( image.size(), image.type() );
:创建一张跟原图像大小和类型一致的空白图像、像素值初始化为0saturate_cast(value);
:确保值大小范围为0~255之间Mat.at(y,x)[index]=value;
:给每个像素点每个通道赋值
代码:
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace std;
using namespace cv;
int main(int argc,char** argv){
Mat src=imread("E:/Experiment/OpenCV/Pictures/test.jpg");
if(!src.data){
cout<<"could not load image ..."<<endl;
return -1;
}
char windows_name[]="input Image";
namedWindow(windows_name,CV_WINDOW_AUTOSIZE);
imshow(windows_name,src);
int height=src.rows;
int width=src.cols;
float alpha = 1.2f;
float beta = 10.f;
Mat dst,convert, dst_convert;
dst=Mat::zeros(src.size(),src.type());
src.convertTo(convert, CV_32F);
dst_convert=Mat::zeros(src.size(),src.type());
for(int row= 0; row < height; row++){
for (int col= 0; col < width; col++){
if(src.channels()==1){
int v=src.at<uchar>(row,col);
dst.at<uchar>(row,col)=saturate_cast<uchar>(alpha*v + beta);
}
else if(src.channels()==3){
int b = src.at<Vec3b>(row, col)[0];
int g = src.at<Vec3b>(row, col)[1];
int r = src.at<Vec3b>(row, col)[2];
dst.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(alpha*b + beta);
dst.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(alpha*g + beta);
dst.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(alpha*r + beta);
float f_b = convert.at<Vec3f>(row, col)[0];
float f_g = convert.at<Vec3f>(row, col)[1];
float f_r = convert.at<Vec3f>(row, col)[2];
dst_convert.at<Vec3b>(row, col)[0] = saturate_cast<uchar>(alpha*f_b + beta);
dst_convert.at<Vec3b>(row, col)[1] = saturate_cast<uchar>(alpha*f_g + beta);
dst_convert.at<Vec3b>(row, col)[2] = saturate_cast<uchar>(alpha*f_r + beta);
}
}
}
imshow("dst_Image",dst);
imshow("dst_convert Image",dst_convert);
waitKey(0);
return 0;
}
运行结果