1. 程式人生 > >Opencv---影象對比度和亮度調節

Opencv---影象對比度和亮度調節

調整影象亮度和對比度操作屬於畫素變換---點操作

數學原理:

       g(x,y) = af(x,y)+b; a>0,b為增益變數

程式碼實現:

#include <opencv2/opencv.hpp>
#include <iostream>

using namespace cv;

int main(int argc, char** argv) {
	Mat src, dst;
	src = imread("C:/usr/opencv-test/Testpictures/sight.jpg");
	if (src.empty())
	{
		printf("load image failed!\n");
		return -1;
	}
	namedWindow("input image", WINDOW_AUTOSIZE);
	imshow("input image", src);

	int height = src.rows;
	int width = src.cols;
	int nc = src.channels();
	dst = Mat::zeros(src.size(), src.type()); //初始化dst為與src同大小、型別,畫素為0的圖片

	float alpha = 1.2;
	float beta = 30.0;
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			//單通道
			if (nc == 1)
			{
				float v = src.at<uchar>(row, col); 
				dst.at<uchar>(row, col) = saturate_cast<uchar>(v*alpha + beta);
			}
			//三通道
			else if (nc == 3)
			{
				float b = src.at<Vec3b>(row, col)[0];
				float g = src.at<Vec3b>(row, col)[1];
				float r = src.at<Vec3b>(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);
			}
		}
	}

	imshow("contrast and brightness change", dst);


	waitKey(0);
	return 0;
}

執行效果: