【OpenCV】调整图像亮度与对比度
理论
图像变换可以看作如下:
- 像素变换 – 点操作
- 邻域操作 – 区域
调整图像亮度和对比度属于像素变换-点操作
相关的API
Mat new_image = Mat::zeros( image.size(), image.type() ); 创建一张跟原图像大小和类型一致的空白图像、像素值初始化为0
saturate_cast(value)确保值大小范围为0~255之间
Mat.at(y,x)[index]=value 给每个像素点每个通道赋值
代码实现
#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
Mat src, dst;
src = imread("1.jpg");
if (src.empty()) {
cout << "cannot load the src" << endl;
return -1;
}
imshow("src", src);
int height = src.rows;
int width = src.cols;
int channel = src.channels();
dst = Mat::zeros(src.size(), src.type());
float alpha = 1.2, beta = 30;
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
if (channel == 3) {
int b = src.at<Vec3b>(row, col)[0];//b通道
int g = src.at<Vec3b>(row,col)[1];//g通道
int r = src.at<Vec3b>(row, col)[2]; //r通道
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 (channel == 1) {
float v = src.at<uchar>(row, col);
dst.at<uchar>(row, col) = saturate_cast<uchar>(v*alpha + beta);
}
}
}
char window_title[] = "output";
namedWindow(window_title, CV_WINDOW_AUTOSIZE);
imshow(window_title, dst);
imwrite("dst.jpg", dst);
waitKey(0);
return 0;
}
效果图
1.原图
效果图(alpha=1.2,beta=30)