1. 程式人生 > >opencv 讀取攝像頭並儲存

opencv 讀取攝像頭並儲存

	m_capture = 0;
	m_writer = 0;
	m_frame = 0;
	m_capture = cvCaptureFromCAM(0/*m_CamIndex*/);
	int count = 0;
	m_frame = cvQueryFrame( m_capture );
	while (m_frame==NULL)
	{
		m_frame = cvQueryFrame( m_capture );
		count++;
	}
	m_writer=cvCreateVideoWriter(m_strVideoPathTemp,CV_FOURCC('X','V','I','D'),25.0,cvSize(m_frame->width,m_frame->height));

上面的程式碼的變數定義如下:

	CvCapture *		m_capture;
	CvVideoWriter*	m_writer;
	IplImage*		m_frame;
現在只是抓取了一幀影象,定義好了寫指標但是並沒有寫到本地,要想將視訊寫入本地,有兩種方法,一種用while迴圈,再用waitkey等待時間間隔,還可以使用定時器實現這個操作,主要用到的是三個函式:settimer、ontimer、killtimer,功能分別是設定一個定時器、定時器訊息響應函式、終止定時器。

這裡先設定一個定時器:

SetTimer(2,25,NULL);

接下來就需要在ontimer訊息響應函式中新增程式碼:

void CxxView::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: Add your message handler code here and/or call default

	switch (nIDEvent)
	{
	//case 1:
	//	getProbeRecord();
	//	UpdateData(FALSE);
	//	break;
	case 2:

		CMainFrame *pMain=(CMainFrame *)AfxGetApp()->m_pMainWnd;
		m_hWndStatic = pMain->m_wndNativeView.m_wndDrawContent.m_widget_NativeViedo.GetSafeHwnd();
		m_pWndStatic = FromHandle(m_hWndStatic);
		if( !m_capture ) //開啟視訊流失敗
		{
			AfxMessageBox("資料流載入失敗");
			KillTimer(2);
			return ;
		}
		m_frame = cvQueryFrame( m_capture );
		if (m_frame)
		{
			int frameH    = (int) cvGetCaptureProperty(m_capture, CV_CAP_PROP_FRAME_HEIGHT);    
			int frameW    = (int) cvGetCaptureProperty(m_capture, CV_CAP_PROP_FRAME_WIDTH);    

			cvWriteFrame(m_writer, m_frame);
			m_pWndStatic->GetClientRect(&m_oRect);
			videoFrameDisplay(m_frame,m_oRect,m_hWndStatic,m_pWndStatic->GetDC(),1);
		}
		break;
	}

	CView::OnTimer(nIDEvent);
}
videoFrameDisplay()是自己寫的函式,用來顯示視訊在指定的mfc的控制元件上。