opencv6-调整图像亮度和对比度

 一、理论

 亮度:0~255之间取大一些的值

对比度:即让R G B 分量的差值增大

二、代码演示

#include<opencv2\opencv.hpp>
#include<iostream>
#include<math.h>
using namespace cv;
using namespace std;
int main()
{
	Mat src = imread("E:\\vs2015\\opencvstudy\\3.jpg", 1);
	if (!src.data)
	{
		cout << "could not load image1!" << endl;
		return -1;
	}
	char input_win[] = "input image";
	imshow(input_win, src);
	cvtColor(src, src, CV_BGR2GRAY);
	//Vec3b 到 Vec3f 的转换函数 src.convertTo()
	Mat m1;
	src.convertTo(m1, CV_32F);

	int height = src.rows;
	int width = src.cols;
	Mat dst = Mat::zeros(src.size(), src.type());
	double alpha = 0.6; //控制对比度
	float beta = 10;  //控制亮度
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			if (src.channels() == 3)
			{
				/*int b = src.at<Vec3b>(row,col)[0];  这里直接使用Vec3f会报错。不可以强转
				int g = src.at<Vec3b>(row,col)[1];
				int r = src.at<Vec3b>(row,col)[2];*/
				float b = m1.at<Vec3f>(row, col)[0];
				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>(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);

			}
			else if (src.channels() == 1)
			{
				float pixel = src.at<uchar>(row, col);
				dst.at<uchar>(row, col) = saturate_cast<uchar>(alpha*pixel + beta);
			}
			else {
				cout << "ERROR" << endl;
			}
		}
	}
	char output_title[] = "contrast and brightness change demo";
	imshow(output_title, dst);


	waitKey(0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_38383877/article/details/89194398