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的控件上。


發佈了37 篇原創文章 · 獲贊 19 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章