[OpenCV] 图像亮度和对比度调整

时间:2023-02-13 08:42:37

对比度调整的原理参考这篇博客

以下是代码实现:

#include <iostream>
#include "opencv2/core.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/highgui.hpp"

using namespace std;
using namespace cv;

#define CLIP_RANGE(value, min, max)  ( (value) > (max) ? (max) : (((value) < (min)) ? (min) : (value)) )
#define COLOR_RANGE(value)  CLIP_RANGE(value, 0, 255)
#define PI 3.1415926

/*
* Adjust Brightness and Contrast
* @param src [in] InputArray
* @param dst [out] OutputArray
* @param brightness [in] integer, value range [-255, 255]
* @param contrast [in] integer, value range [-255, 255]
* @return 0 if success, else return error code
*/
int adjustBrightnessContrast(Mat src, Mat& dst, int brightness, int contrast)
{
	if (src.empty()) {
		return -1;
	}

	brightness = CLIP_RANGE(brightness, -255, 255);
	contrast = CLIP_RANGE(contrast, -255, 255);

	/*
	Algorithm of Brightness Contrast transformation
	The formula is:
	y = [x - 127.5 * (1 - B)] * k + 127.5 * (1 + B);
	x is the input pixel value;
	y is the output pixel value;
	B is brightness, value range is [-1,1];
	k is used to adjust contrast;
	k = tan( (45 + 44 * c) / 180 * PI );
	c is contrast, value range is [-1,1];
	especially:
	when B = 0, y = (x-127.5)*k + 127.5, adjust Contrast only;
	when c = 0, k = 1, y = x + 255*B, adjust Brightness only;
	*/

	double B = brightness / 255.;
	double c = contrast / 255.;
	double k = tan((45 + 44 * c) / 180 * PI);

	Mat lookupTable(1, 256, CV_8U);
	uchar *p = lookupTable.data;
	for (int i = 0; i < 256; i++)
		p[i] = COLOR_RANGE((i - 127.5 * (1 - B)) * k + 127.5 * (1 + B));

	LUT(src, lookupTable, dst);

	return 0;
}


//=====主程序开始====
static Mat src;
static int brightness = 255;
static int contrast = 255;

static void callbackAdjust(int, void *)
{
	Mat dst;
	adjustBrightnessContrast(src, dst, brightness - 255, contrast - 255);
	imshow("photo", dst);
}

int main()
{
	src = imread("D:\\1.jpg");

	if (!src.data) {
		cout << "error read image" << endl;
		return -1;
	}

	namedWindow("photo");
	createTrackbar("brightness", "photo", &brightness, 2 * brightness, callbackAdjust);
	createTrackbar("contrast", "photo", &contrast, 2 * contrast, callbackAdjust);
	callbackAdjust(0, 0);

	waitKey();
	destroyAllWindows();

	return 0;
}

[OpenCV] 图像亮度和对比度调整