调整图像亮度与对比度

VS2017&OPENCV4.0

#include 
#include 
#include 

using namespace cv;
int main(int argc, char** argv) {
	Mat src, dst;
	src = imread("D:\\test.jpg");
	if (!src.data) {
		printf("could not load image...\n");
		return -1;
	}
	char input_win[] = "input image";//input_win等于字符串 "input image"
	//cvtColor(src, src, CV_BGR2GRAY);
	namedWindow(input_win, 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 = 30;//设置数值

	Mat m1;
	src.convertTo(m1, CV_32F);//把src转换为m1
	//获得像素值
	for (int row = 0; row < height; row++) {
		for (int col = 0; col < width; col++) {
			if (src.channels() == 3) {
				float b = m1.at(row, col)[0];// 获得蓝色的像素
				float g = m1.at(row, col)[1]; 
				float r = m1.at(row, col)[2]; 

				// 通过给像素复制,改变图像的亮度和对比度
				dst.at(row, col)[0] = saturate_cast(b*alpha + beta);
				dst.at(row, col)[1] = saturate_cast(g*alpha + beta);
				dst.at(row, col)[2] = saturate_cast(r*alpha + beta);
			}
			//获得像素值
			else if (src.channels() == 1) {
				float v = src.at(row, col);
				dst.at(row, col) = saturate_cast(v*alpha + beta);
			}
		}
	}

	char output_title[] = "contrast and brightness change demo";//output_title等于 "contrast and brightness change demo"
	namedWindow(output_title, WINDOW_AUTOSIZE);
	imshow(output_title, dst);

	waitKey(0);
	return 0;
}

你可能感兴趣的:(调整图像亮度与对比度)