第五课 调整图像亮度与对比度
1.理论
像素变换——点操作
邻域操作——区域(概念参照数字图像处理)
调整图像亮度和对比度属于前者
2.代码
#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("H:/pictures/prepic.png");
if (!src.data)
{
cout << "could not load image.." << endl;
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 = 1.5;//对比度
float beta = 100;//亮度增加
Mat m1;
src.convertTo(m1, CV_32F);//像素值转化为float类型
for (int row = 0; row < height;row++)
{
for (int col = 0; col < width;col++)
{
if (src.channels()==3)
{
float b = m1.at<Vec3f>(row, col)[0];//读取像素值BGR
float g = m1.at<Vec3f>(row, col)[1];
float r = m1.at<Vec3f>(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[] = "output image";
namedWindow("output", CV_WINDOW_AUTOSIZE);
imshow("output", dst);
waitKey(0);
return 0;
}