直接上代码:
1 #include <Windows.h> 2 #include <iostream>// for stand I/O 3 #include <string> // for strings 4 #include <iomanip> // for controlling float print precision 5 #include <sstream> // string to number conversion 6 #include <cmath> 7 #include <ctype.h> 8 #include <opencv2/opencv.hpp> 9 10 using namespace std; 11 using namespace cv; 12 13 int main() 14 { 15 Mat m_frame; 16 Mat m_ycrcb; 17 Mat m_result; 18 Mat m_result2; 19 VideoCapture m_Cap; 20 int m_nWidth = 640; 21 int m_nHeight = 480; 22 23 double alpha = 2.0; /**< Simple contrast control */ 24 int beta = 0; /**< Simple brightness control */ 25 /// Initialize values 26 std::cout<<" Basic Linear Transforms "<<std::endl; 27 std::cout<<"-------------------------"<<std::endl; 28 std::cout<<"* Enter the alpha value [1.0-3.0]: ";std::cin>>alpha; 29 std::cout<<"* Enter the beta value [0-100]: "; std::cin>>beta; 30 31 m_Cap.open(0); 32 33 bool bSuccess1 = false,bSuccess2 = false; 34 bSuccess1 = m_Cap.set(CV_CAP_PROP_FRAME_WIDTH,m_nWidth); 35 bSuccess2 = m_Cap.set(CV_CAP_PROP_FRAME_HEIGHT,m_nHeight); 36 if (bSuccess1==false || bSuccess2==false) 37 { return -1;} 38 39 m_Cap>>m_frame; 40 if (m_frame.empty()) 41 { 42 return -1; 43 } 44 45 //用来存储各通道图片的向量 46 vector<Mat> splitBGR(m_frame.channels()); 47 vector<Mat> splitYCrCb(m_frame.channels()); 48 49 Mat new_image = Mat::zeros( m_frame.size(), m_frame.type() ); 50 51 for (;;) 52 { 53 m_Cap>>m_frame; 54 if (m_frame.empty()) 55 { return -1; } 56 57 //方法一:直方图均衡化 58 //分割通道,存储到splitBGR中 59 split(m_frame,splitBGR); 60 //对各个通道分别进行直方图均衡化 61 for(int i=0; i<m_frame.channels(); i++) 62 equalizeHist(splitBGR[i],splitBGR[i]); 63 //合并通道 64 merge(splitBGR,m_result); 65 66 //方法二: 直方图均衡化 67 //转化为ycrcb 68 cvtColor(m_frame,m_ycrcb,CV_BGR2YCrCb); 69 split(m_ycrcb,splitYCrCb); 70 equalizeHist(splitYCrCb[0],splitYCrCb[0]); 71 merge(splitYCrCb,m_ycrcb); 72 cvtColor(m_ycrcb,m_result2,CV_YCrCb2BGR); 73 74 75 //方法三: 76 //g(i,j) = alpha * f(i,j) + beta 77 for( int y = 0; y < m_frame.rows; y++ ) { 78 for( int x = 0; x < m_frame.cols; x++ ) { 79 for( int c = 0; c < 3; c++ ) { 80 new_image.at<Vec3b>(y,x)[c] = 81 saturate_cast<uchar>( alpha*( m_frame.at<Vec3b>(y,x)[c] ) + beta ); 82 } 83 } 84 } 85 86 imshow("原图",m_frame); 87 imshow("对比度1",m_result); 88 imshow("对比度2",m_result2); 89 imshow("对比度3",new_image); 90 91 int c = waitKey(33); 92 if (c==27)//ESC退出 93 { break; } 94 95 } 96 97 return 0; 98 }
参考网址:http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/core/basic_linear_transform/basic_linear_transform.html