首页 > 代码库 > opencvbase 实现opencv打开摄像头和初步处理等效果操作(附源码)

opencvbase 实现opencv打开摄像头和初步处理等效果操作(附源码)

// TwoCameraOnTimer2Dlg.cpp : 实现文件/*CvMat, Mat, IplImage之间的互相转换IpIImage -> CvMatCvMat matheader;CvMat * mat = cvGetMat(img, &matheader);CvMat * mat = cvCreateMat(img->height, img->width, CV_64FC3);cvConvert(img, mat)IplImage -> MatMat::Mat(const IplImage* img, bool copyData=http://www.mamicode.com/false);"greatwave.jpg", 1);Mat mtx(iplImg);Mat -> IplImageMat MIplImage iplimage = M;CvMat -> MatMat::Mat(const CvMat* m, bool copyData=http://www.mamicode.com/false);"stdafx.h"#include "TwoCameraOnTimer2.h"#include "TwoCameraOnTimer2Dlg.h"#include "afxdialogex.h"#include <opencv/cv.h>#include <opencv/highgui.h>#ifdef _DEBUG#define new DEBUG_NEW#endif// 用于应用程序“关于”菜单项的 CAboutDlg 对话框class CAboutDlg : public CDialogEx{public:	CAboutDlg();// 对话框数据	enum { IDD = IDD_ABOUTBOX };	protected:	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持// 实现protected:	DECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD){}void CAboutDlg::DoDataExchange(CDataExchange* pDX){	CDialogEx::DoDataExchange(pDX);}BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)END_MESSAGE_MAP()// CTwoCameraOnTimer2Dlg 对话框CTwoCameraOnTimer2Dlg::CTwoCameraOnTimer2Dlg(CWnd* pParent /*=NULL*/)	: CDialogEx(CTwoCameraOnTimer2Dlg::IDD, pParent)	, m_nCamCount(0)	, m_nLeftCamCount(0)	, m_nRightCamCount(0)	, m_nRAD_SELECT(0){	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CTwoCameraOnTimer2Dlg::DoDataExchange(CDataExchange* pDX){	CDialogEx::DoDataExchange(pDX);	DDX_Control(pDX, IDC_COMBO1, m_CBNCamList);	//  DDX_Control(pDX, IDC_IMG_LOGO, m_imglogo);}BEGIN_MESSAGE_MAP(CTwoCameraOnTimer2Dlg, CDialogEx)	ON_WM_SYSCOMMAND()	ON_WM_PAINT()	ON_WM_QUERYDRAGICON()	ON_BN_CLICKED(IDC_BTN_OPENCAM, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnOpencam)	ON_CBN_SELCHANGE(IDC_COMBO1, &CTwoCameraOnTimer2Dlg::OnCbnSelchangeCombo1)	ON_WM_TIMER()	ON_BN_CLICKED(IDC_BTN_CLOSECAM, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnClosecam)	ON_BN_CLICKED(IDC_BTN_CAPTURE, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnCapture)	ON_BN_CLICKED(IDC_BTN_SAVE, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnSave)	ON_BN_CLICKED(IDC_BTN_MIRROR, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnMirror)	ON_BN_CLICKED(IDC_BTN_MIRROR2, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnMirror2)	ON_BN_CLICKED(IDC_BTN_ROTATE, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnRotate)	ON_BN_CLICKED(IDC_BTN_PRINT, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnPrint)	ON_WM_DESTROY()	ON_BN_CLICKED(IDC_BTN_OPENCAM3, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnOpencam3)	 	ON_BN_CLICKED(IDC_BTN_SOBEL, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnSobel)	ON_BN_CLICKED(IDC_BTN_EMPTY, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnEmpty)	ON_BN_CLICKED(IDC_BTN_CANNY, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnCanny)	ON_BN_CLICKED(IDC_BTN_BLACK, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnBlack)	ON_BN_CLICKED(IDC_BTN_OPENCAM2, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnOpencam2)	ON_BN_CLICKED(IDC_BTN_BIN, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnBin)	ON_BN_CLICKED(IDC_BTN_PREWITTE, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnPrewitte)	ON_BN_CLICKED(IDC_BTN_AUTOBIN, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnAutobin)	 	ON_BN_CLICKED(IDC_BTN_LOG, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnLog)	 	ON_BN_CLICKED(IDC_BTN_HIST, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnHist)	ON_BN_CLICKED(IDC_BTN_WATER, &CTwoCameraOnTimer2Dlg::OnBnClickedBtnWater)END_MESSAGE_MAP()// CTwoCameraOnTimer2Dlg 消息处理程序BOOL CTwoCameraOnTimer2Dlg::OnInitDialog(){	CDialogEx::OnInitDialog();	// 将“关于...”菜单项添加到系统菜单中。	// IDM_ABOUTBOX 必须在系统命令范围内。	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);	ASSERT(IDM_ABOUTBOX < 0xF000);	CMenu* pSysMenu = GetSystemMenu(FALSE);	if (pSysMenu != NULL)	{		BOOL bNameValid;		CString strAboutMenu;		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);		ASSERT(bNameValid);		if (!strAboutMenu.IsEmpty())		{			pSysMenu->AppendMenu(MF_SEPARATOR);			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);		}	}	// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动	//  执行此操作	SetIcon(m_hIcon, TRUE);			// 设置大图标	SetIcon(m_hIcon, FALSE);		// 设置小图标	// TODO: 在此添加额外的初始化代码	//设置logo	 	m_nCamCount = CCameraDS::CameraCount();//摄像头总数	m_nLeftCamCount = 1;//左边摄像头默认为1	m_nRightCamCount = 0;//右边摄像头默认为0	//在listbox中添加数据	char camera_name[1024];	char istr[25];	CString camstr;	for(int i=0; i < m_nCamCount; i++)	{  		int retval = CCameraDS::CameraName(i, camera_name, sizeof(camera_name) );		sprintf_s(istr, " # %d", i);		strcat_s( camera_name, istr );  		camstr = camera_name;		if(retval >0)			m_CBNCamList.AddString(camstr);		else			AfxMessageBox(_T("不能获取摄像头的名称"));	}	camstr.ReleaseBuffer();	// 初始化图像显示控件的图像	CRect rect;	GetDlgItem(IDC_PBRIGHT)->GetClientRect(&rect);	m_lfimage = Mat::zeros(rect.Height(),rect.Width(),CV_8UC3);	GetDlgItem(IDC_PBRIGHT)->GetClientRect(&rect); 	m_rightimage = Mat::zeros(rect.Height(),rect.Width(),CV_8UC3);		return TRUE;  // 除非将焦点设置到控件,否则返回 TRUE}void CTwoCameraOnTimer2Dlg::OnSysCommand(UINT nID, LPARAM lParam){	if ((nID & 0xFFF0) == IDM_ABOUTBOX)	{		CAboutDlg dlgAbout;		dlgAbout.DoModal();	}	else	{		CDialogEx::OnSysCommand(nID, lParam);	}}// 如果向对话框添加最小化按钮,则需要下面的代码//  来绘制该图标。对于使用文档/视图模型的 MFC 应用程序,//  这将由框架自动完成。void CTwoCameraOnTimer2Dlg::OnPaint(){	if (IsIconic())	{		CPaintDC dc(this); // 用于绘制的设备上下文		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);		// 使图标在工作区矩形中居中		int cxIcon = GetSystemMetrics(SM_CXICON);		int cyIcon = GetSystemMetrics(SM_CYICON);		CRect rect;		GetClientRect(&rect);		int x = (rect.Width() - cxIcon + 1) / 2;		int y = (rect.Height() - cyIcon + 1) / 2;		// 绘制图标		dc.DrawIcon(x, y, m_hIcon);	}	else	{		CDialogEx::OnPaint();	}	//绘制logo	CString fileName="1.png";	std::string str = fileName;	Mat mat = imread(str);	F_ShowImage(mat,mat,IDC_IMG_LOGO);//打开并写入m_rightimage }//当用户拖动最小化窗口时系统调用此函数取得光标//显示。HCURSOR CTwoCameraOnTimer2Dlg::OnQueryDragIcon(){	return static_cast<HCURSOR>(m_hIcon);}//打开摄像头void CTwoCameraOnTimer2Dlg::OnBnClickedBtnOpencam(){	 	 if (!leftcam.open(m_nLeftCamCount))	 {	 	AfxMessageBox(_T("摄像头打开失败"));	 }	 else	 {		 AfxMessageBox(_T("摄像头打开成功"));		 QueryCam();//开始摄像头	 }// 	 if (m_nCamCount>=1)// 	 {	// 		 //如果两个摄像头的开启号是不一样的// 		 if (m_nLeftCamCount != m_nRightCamCount)// 		 {// 			 if (!leftcam.open(m_nLeftCamCount))// 			 {// 				  AfxMessageBox(_T("左摄像头打开失败"));// 			 }// 			 // 			 if (!rightcam.open(m_nRightCamCount))// 			 {// 				  AfxMessageBox(_T("右摄像头打开失败"));// 			 }// 			 // 			 QueryCam();//开始摄像头// 		 }// 		 else// 		 {// 			AfxMessageBox(_T("两个摄像头不能设定的一样"));// 		 }// 	 }// 	 else// 	 {// 		 AfxMessageBox(_T("请确认至少有一个摄像头连上了"));// 	 }}void CTwoCameraOnTimer2Dlg::OnCbnSelchangeCombo1(){	// TODO: 在此添加控件通知处理程序代码// 	m_nRAD_SELECT = GetCheckedRadioButton(IDC_RADIOLEFT,IDC_PBRIGHT);// 	if (m_nRAD_SELECT == IDC_RADIOLEFT)// 	{		m_nLeftCamCount = m_CBNCamList.GetCurSel();// 	}// 	else// 	{// 		m_nRightCamCount = m_CBNCamList.GetCurSel();// 	}}//打开timer,开始摄像头捕捉void CTwoCameraOnTimer2Dlg::QueryCam(void){	SetTimer(1,50,NULL);//采用timer触发,进行摄像头操作}void CTwoCameraOnTimer2Dlg::OnTimer(UINT_PTR nIDEvent){	// TODO: 在此添加消息处理程序代码和/或调用默认值	if (leftcam.isOpened())	{		Mat leftframe;		leftcam >>leftframe;		F_ShowImage(leftframe,m_lfimage,IDC_PBLEFT);	}	 		F_ShowImage(m_rightimage,m_rightimage,IDC_PBRIGHT);	// 	if (rightcam.isOpened())// 	{// 		Mat rightframe;// 		rightcam>>rightframe;// 		F_ShowImage(rightframe,m_rightimage,IDC_PBRIGHT);// 	}	CDialogEx::OnTimer(nIDEvent);}/*---------------------------- * 功能 : 显示图像 *		 将要绘制的图像 src 复制到 des,然后绘制到控件号为 ID 的 Picture 控件 *---------------------------- * 函数 : CStereoVisionDlg::F_ShowImage * 访问 : private  * 返回 : void * * 参数 : src	[in]	待显示图像 * 参数 : des	[in]	窗口图像 * 参数 : ID		[in]	图像窗口控件ID */void CTwoCameraOnTimer2Dlg::F_ShowImage(Mat& src, Mat& des, UINT ID){	if (src.empty())	{		return;	}	// 计算将图片缩放到 Image 区域所需的比例因子	double wRatio = des.cols / (double)src.cols;	double hRatio = des.rows / (double)src.rows;	double srcWH = src.cols / (double)src.rows;	double desWH = des.cols / (double)des.rows;	double scale = srcWH > desWH ? wRatio : hRatio;	// 缩放后图片的宽和高	int nw = (int)( src.cols * scale );	int nh = (int)( src.rows * scale );	// 为了将缩放后的图片存入 des 的正中部位,需计算图片在 des 左上角的期望坐标值	int tlx = (int)((des.cols - nw) / 2);	int tly = (int)((des.rows - nh) / 2);	// 设置 des 的 ROI 区域,用来存入图片 img	Mat desRoi = des(Rect(tlx, tly, nw, nh));	// 如果src是单通道图像,则转换为三通道图像	if (src.channels() == 1)	{		Mat src_c;		cvtColor(src, src_c, CV_GRAY2BGR);		// 对图片 src_t 进行缩放,并存入到 des 中		resize(src_c, desRoi, desRoi.size());	}	else	{		// 对图片 src 进行缩放,并存入到 des 中		resize( src, desRoi, desRoi.size() );	}	CDC* pDC = GetDlgItem( ID ) ->GetDC();		// 获得显示控件的 DC	HDC hDC = pDC ->GetSafeHdc();				// 获取 HDC(设备句柄) 来进行绘图操作	CRect rect;	GetDlgItem(ID) ->GetClientRect( &rect );	// 获取控件尺寸位置	CvvImage cimg;	IplImage cpy = des;	cimg.CopyOf( &cpy );						// 复制图片	cimg.DrawToHDC( hDC, &rect );				// 将图片绘制到显示控件的指定区域内	ReleaseDC( pDC );}//关闭摄像头void CTwoCameraOnTimer2Dlg::OnBnClickedBtnClosecam(){		KillTimer(1);	if (leftcam.isOpened())	{		m_lfimage = Scalar(0);		F_ShowImage(m_lfimage,m_lfimage,IDC_PBLEFT);		leftcam.release();		AfxMessageBox(_T("摄像头关闭成功"));	}// 	if (rightcam.isOpened())// 	{// 		m_rightimage = Scalar(0);// 		F_ShowImage(m_rightimage,m_rightimage,IDC_PBRIGHT);// 		rightcam.release();// 	}}//截获当前画面void CTwoCameraOnTimer2Dlg::OnBnClickedBtnCapture(){	// TODO: 在此添加控件通知处理程序代码	m_rightimage = NULL;	Mat rightframe;	leftcam >>rightframe;	F_ShowImage(rightframe,m_rightimage,IDC_PBRIGHT);}//保存当前画面void CTwoCameraOnTimer2Dlg::OnBnClickedBtnSave(){	// TODO: 在此添加控件通知处理程序代码// 	Mat rightframe;// 	leftcam >>rightfram		IplImage iplimage =m_lfimage;	//打开保存界面,获得保存的地址	CString fileName;	CString szFilters="jpg(*.jpg)|*.jpg||";	CFileDialog dlgFile(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,szFilters,NULL,0,TRUE); 	const int c_cMaxFiles = 100;	const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;	dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(c_cbBuffSize);	dlgFile.GetOFN().nMaxFile = c_cMaxFiles;	dlgFile.DoModal();	fileName.ReleaseBuffer();	fileName = fileName+".jpg";//加个后缀名	int i = cvSaveImage(fileName,&iplimage);	if (i!=0)	{		AfxMessageBox(_T("文件保存成功"));	}}//镜像1void CTwoCameraOnTimer2Dlg::OnBnClickedBtnMirror(){		IplImage iplimage =m_rightimage;		cvFlip(&iplimage,&iplimage,1);//镜像		Mat img(&iplimage,0);		F_ShowImage(img,m_rightimage,IDC_PBRIGHT);}//镜像2void CTwoCameraOnTimer2Dlg::OnBnClickedBtnMirror2(){	IplImage iplimage =m_rightimage;	cvFlip(&iplimage,&iplimage,0);//镜像	Mat img(&iplimage,0);	F_ShowImage(img,m_rightimage,IDC_PBRIGHT);}//旋转void CTwoCameraOnTimer2Dlg::OnBnClickedBtnRotate(){	// TODO: 在此添加控件通知处理程序代码	int rotation_degrees = 30;	Mat M = getRotationMatrix2D(Point(m_rightimage.cols/2,m_rightimage.rows/2),rotation_degrees,1);	warpAffine(m_rightimage,m_rightimage,M,m_rightimage.size(),INTER_LINEAR);	F_ShowImage(m_rightimage,m_rightimage,IDC_PBRIGHT);}//printvoid CTwoCameraOnTimer2Dlg::OnBnClickedBtnPrint(){ }//destory就是关闭时候的情况void CTwoCameraOnTimer2Dlg::OnDestroy(){	CDialogEx::OnDestroy();	KillTimer(1);	if (leftcam.isOpened())	{		m_lfimage = Scalar(0);		F_ShowImage(m_lfimage,m_lfimage,IDC_PBLEFT);		leftcam.release();		AfxMessageBox(_T("摄像头关闭成功"));	}	 }//保存文件void CTwoCameraOnTimer2Dlg::OnBnClickedBtnOpencam3(){	// TODO: 在此添加控件通知处理程序代码	IplImage iplimage =m_rightimage;	//打开保存界面,获得保存的地址	CString fileName;	CString szFilters="jpg(*.jpg)|*.jpg||";	CFileDialog dlgFile(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,szFilters,NULL,0,TRUE); 	const int c_cMaxFiles = 100;	const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;	dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(c_cbBuffSize);	dlgFile.GetOFN().nMaxFile = c_cMaxFiles;	dlgFile.DoModal();	fileName.ReleaseBuffer();	fileName = fileName+".jpg";//加个后缀名	int i = cvSaveImage(fileName,&iplimage);	if (i!=0)	{		AfxMessageBox(_T("文件保存成功"));	}} //sobelvoid CTwoCameraOnTimer2Dlg::OnBnClickedBtnSobel(){	IplImage iplimage =m_rightimage;	cvSobel(&iplimage,&iplimage,1,0,3);   	Mat img(&iplimage,0);	F_ShowImage(img,m_rightimage,IDC_PBRIGHT);}//清空void CTwoCameraOnTimer2Dlg::OnBnClickedBtnEmpty(){	IplImage iplimage =m_rightimage;    m_rightimage = NULL;	F_ShowImage(m_rightimage,m_rightimage,IDC_PBRIGHT);}//cannyvoid CTwoCameraOnTimer2Dlg::OnBnClickedBtnCanny(){	IplImage iplimage =m_rightimage;	IplImage *src = http://www.mamicode.com/&iplimage;"jpg(*.jpg)|*.jpg||bmp(*.bmp)|*.bmp";	CFileDialog dlgFile(TRUE,NULL,NULL,OFN_HIDEREADONLY|OFN_OVERWRITEPROMPT,szFilters,NULL,0,TRUE); 	const int c_cMaxFiles = 100;	const int c_cbBuffSize = (c_cMaxFiles * (MAX_PATH + 1)) + 1;	dlgFile.GetOFN().lpstrFile = fileName.GetBuffer(c_cbBuffSize);	dlgFile.GetOFN().nMaxFile = c_cMaxFiles;	dlgFile.DoModal();	fileName.ReleaseBuffer();	std::string str = fileName;    Mat mat = imread(str);	F_ShowImage(mat,m_rightimage,IDC_PBRIGHT);//打开并写入m_rightimage	SetTimer(1,50,NULL);//采用timer触发}//二值化void CTwoCameraOnTimer2Dlg::OnBnClickedBtnBin(){	// TODO: 在此添加控件通知处理程序代码	IplImage iplimage =m_rightimage;	IplImage *src = http://www.mamicode.com/&iplimage;>

 

程序代码视频 http://pan.baidu.com/s/1dDINRnr o2p3

任何问题,请联系qq:1755311380