1 #include <opencv2/opencv.hpp> 2 #include <opencv2/core/core.hpp> 3 #include <opencv2/highgui/highgui.hpp> 4 #include<iostream> 5 using namespace cv; 6 using namespace std; 7 static void on_ContrastAndBright(int,void *); 8 //static void ShowHelpText(); 9 int g_nContrastValue;//对比度值 10 int g_nBrightValue;//亮度值 11 Mat g_srcImage,g_dstImage; 12 int main() 13 { 14 g_srcImage=imread("E:\\lena.jpg"); 15 g_dstImage=Mat::zeros(g_srcImage.size(),g_srcImage.type()); 16 g_nContrastValue=80;//对比度初始化 17 g_nBrightValue=80;//亮度初始化 18 namedWindow("效果图窗口",1); 19 createTrackbar("对比度:","效果图窗口",&g_nContrastValue,300,on_ContrastAndBright); 20 createTrackbar("亮度:","效果图窗口",&g_nBrightValue,200,on_ContrastAndBright); 21 on_ContrastAndBright(g_nContrastValue,0); 22 on_ContrastAndBright(g_nBrightValue,0); 23 //while(char(waitKey(1))!='q'){} 24 waitKey(0); 25 return 0; 26 } 27 static void on_ContrastAndBright(int,void *) 28 { 29 //namedWindow("originalwindow",1); 30 for(int y=0;y<g_srcImage.rows;y++){ 31 for(int x=0;x<g_srcImage.cols;x++){ 32 for(int c=0;c<3;c++){ 33 g_dstImage.at<Vec3b>(y,x)[c]=saturate_cast<uchar>((g_nContrastValue*0.01)*(g_srcImage.at<Vec3b>(y,x)[c])+g_nBrightValue); 34 35 } 36 } 37 } 38 //y是像素所在的行,x是像素所在的列,c是BGR其中之一,saturate_cast对结果进行转化确保它为有效值,执行的运算是new_image=a*image+b 39 //saturate_cast模板函数大致原理 40 //if(data<0)data=0; 41 //else if(data>255)data=255; 42 imshow("原始图窗口",g_srcImage); 43 imshow("效果图窗口",g_dstImage); 44 }
运行结果: