1. 程式人生 > >Opencv影象對比度和亮度的調整-滾動條

Opencv影象對比度和亮度的調整-滾動條

#include<iostream>
#include<opencv2/opencv.hpp>
#include"stdio.h"

using namespace std;
using namespace cv;

Mat srcImage, resultImage;
int g_nContrast, g_nBright;
const int g_nContrastMax = 300, g_nBright_Max = 300;

//a控制對比度,b控制亮度
void ContrastBright(const Mat &srcImage, Mat &dstImage, double a, double b);

//有滾動條事件時,可以進入回撥函式
void on_Trackbar(int, void *);

int main()
{
	srcImage = imread("group.jpg");

	namedWindow("滾動條視窗");

	g_nContrast = 50;
	g_nBright = 50;
	createTrackbar("對比度", "滾動條視窗", &g_nContrast, g_nContrastMax, on_Trackbar);
	createTrackbar("亮度", "滾動條視窗", &g_nBright, g_nBright_Max, on_Trackbar);
	on_Trackbar(g_nContrast, 0);
	on_Trackbar(g_nBright, 0);

	waitKey(0);

	return 0;
}

void ContrastBright(const Mat &srcImage, Mat &dstImage, double a, double b)
{
	srcImage.copyTo(dstImage);

	const int imageRows = srcImage.rows;
	const int imageCols = srcImage.cols * srcImage.channels();
	for (int i = 0; i < imageRows; i++)
	{
		uchar *data = dstImage.ptr<uchar>(i);
		for (int j = 0; j < imageCols; j++)
		{
			data[j] = saturate_cast<uchar>(a * data[j] + b);
		}
	}
}

void on_Trackbar(int, void *)
{
	const double contrastValue = g_nContrast / 100.0;
	const double brightValue = g_nBright;

	ContrastBright(srcImage, resultImage, contrastValue, brightValue);

	imshow("【處理後的影象】", resultImage);
}