原理在这里有所阐述:
http://www.jizhuomi.com/software/257.html
http://blog.csdn.net/pizi0475/article/details/6740428
自己写个小界面测试一下
VS2012 MFC,OpenCV 3.0beta
添加以下控件:
1、一个button,IDC_BUTTON1,用于打开图片;
2、2个slider,IDC_CONTRAST和IDC_BRIGHTNESS,用于调对比度和亮度,分别添加控件变量m_slider1和m_slider2;
3、2个edit,IDC_EDIT_CONTRAST和IDC_EDIT_BRIGHTNESS,用于显示对比度和亮度的调整值
编码:
1、**Dlg.h:
添加私有变量
int mValueContrast;
int mValueBrightness;
Mat img,img1;
添加头文件
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui/highgui.hpp"
2、往**Dlg类添加消息
WM_HScroll
添加消息处理函数
OnHScroll
编辑该函数
void CsetContrastAndBrightnessDlg::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CSliderCtrl *pSlidCtrl=(CSliderCtrl*)GetDlgItem(IDC_CONTRAST); mValueContrast=pSlidCtrl->GetPos();//取得当前位置值 pSlidCtrl=(CSliderCtrl*)GetDlgItem(IDC_BRIGHTNESS); mValueBrightness=pSlidCtrl->GetPos();//取得当前位置值 UpdateData(FALSE); //刷新edit控件 //刷新显示 setContrastBrightness(mValueBrightness,mValueContrast,img,img1); imshow("im1",img1); CDialogEx::OnHScroll(nSBCode, nPos, pScrollBar); }3、编写亮度对比度算法
void setContrastBrightness(double percentB, double percentC, Mat& img, Mat& result) { const double pi = 3.1415926535898; //百分比转为调整系数,0~100 转为 -range~range,最大为[-1,1] const double Crange = 0.7; //range越小,对比度调节的精度越高 double C = (percentC-50)* Crange/50; //取值范围:[-range,range] const double Brange = 0.5; double B = (percentB-50)* Brange/50; double k = tan( (45 + 44 * C) / 180 * pi ); int channel=0; int MAXGRAYVALUE=0; int orgtype = img.type(); switch(orgtype) { case CV_8UC1: channel = 1; MAXGRAYVALUE =255; break; case CV_8UC3: channel = 3; MAXGRAYVALUE =255; break; case CV_16UC1: channel = 1; MAXGRAYVALUE =65535; break; default: MAXGRAYVALUE =65535;break; } double threshold = MAXGRAYVALUE/2; vector<Mat> mv(channel); Mat imgcyp; img.convertTo(imgcyp,CV_32F); split(imgcyp,mv); for(int i=0;i<channel;i++) { mv[i] = (mv[i] - threshold * (1 - B)) * k + threshold * (1 + B); } merge(mv,result); result.convertTo(result,orgtype); }4、为botton添加事件响应函数
OnBnClickedButton1
编辑该函数
void CsetContrastAndBrightnessDlg::OnBnClickedButton1() { //选择文件 CFileDialog* dlg = new CFileDialog(TRUE,"(*.*)|*.*",NULL,4|2,"图像文件(*.*)|*.*||"); //新建CFileDialog对象 dlg->m_ofn.lpstrInitialDir="I:\\素材"; //指定初始目录 CString mPath; CString mFileName; if (IDOK==dlg->DoModal()) { mPath = dlg->GetPathName(); //获取路径 mFileName = dlg->m_ofn.lpstrFileTitle; } delete dlg; img = imread(mPath.GetBuffer(0)); namedWindow("im1", CV_WINDOW_AUTOSIZE); imshow("im1",img); }5、改写OnInitDialog()函数,添加以下代码
// TODO: 在此添加消息处理程序代码和/或调用默认值 m_slider1.SetRange(0,100);//设置滑动范围 m_slider1.SetTicFreq(1);//每10个单位画一刻度 m_slider1.SetPos(50); m_slider2.SetRange(0,100);//设置滑动范围 m_slider2.SetTicFreq(1);//每10个单位画一刻度 m_slider2.SetPos(50); mValueContrast = 50; mValueBrightness=50;//取得当前位置值 UpdateData(FALSE); //刷新edit控件6、改写DoDataExchange()函数,添加以下代码
DDX_Text(pDX, IDC_EDIT_CONTRAST, mValueContrast); DDX_Text(pDX, IDC_EDIT_BRIGHTNESS, mValueBrightness);