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

Posted p3nguin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[OpenCV] 图像亮度和对比度调整相关的知识,希望对你有一定的参考价值。

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

#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] 图像亮度和对比度调整的主要内容,如果未能解决你的问题,请参考以下文章

OpenCV 调整图像亮度与对比度

OpenCV 调整图像亮度与对比度

灰度图像亮度对比度调整的简单代码

Android OpenCV之算数操作与调整图像的亮度和对比度

Android OpenCV之算数操作与调整图像的亮度和对比度

学习 opencv--- 创建Trackbar(活动条) &图像对比度,亮度值调整