使用OpenCV和多线程编程实现摄像头实时播放

271 篇文章 2 订阅

作者:jink2005

转自:http://www.aiseminar.cn/bbs/forum.php?mod=viewthread&tid=608&reltid=1313&pre_thread_id=0&pre_pos=3&ext=


此文原位于本坛文章“MFC多线程编程:问题的提出与解决方案”的第二贴中,为了方便OpenCV的学习者,重新复制于此。

原理请见:http://www.aiseminar.cn/bbs/viewthread.php?tid=338&page=1&fromuid=3#pid583

根据上面介绍我的程序应该使用工作者线程,完成后,视频可以实施预览,拍照按钮可以响应,并拍照。注意下面程序中m_video是对应显示视频的空间的Control变量。

实现效果如下:


多线程实现代码:

  1. // AISeminarVTDlg.h : header file

  2. class CAISeminarVTDlg : public CDialog
  3. {
  4. // Construction
  5. public:
  6. CAISeminarVTDlg(CWnd* pParent = NULL); // standard constructor
  7. CWinThread* pThread; // 新加代码
  8. // ……
  9. protected:
  10. HICON m_hIcon;
  11. // ……
  12. };

复制代码

  1. // AISeminarVTDlg.cpp : implementation file
  2. // ……添加下面代码

  3. // 声明IplImage指针
  4. IplImage* pFrame;
  5. IplImage* pFrImg;
  6. IplImage* pBkImg;
  7. // 声明摄像头图像采集对象
  8. CvCapture* pCapture;
  9. int nFrmNum;
  10. UINT previewVideo(LPVOID lpParam);

  11. // 启动摄像头按钮事件处理:线程调用部分
  12. void CAISeminarVTDlg::OnBtnDvstart()
  13. {
  14. // TODO: Add your control notification handler code here
  15. UpdateData(true);
  16. if (! pCapture)
  17. {
  18.   if (! (pCapture = cvCaptureFromCAM(0)))
  19.   {
  20.    MessageBox("找不到可用摄像头,请接入!");
  21.    return;
  22.   }
  23. }
  24. pThread = AfxBeginThread(previewVideo, &m_video);
  25. MessageBox("摄像头已启动!");
  26. }

  27. // ……

  28. // 多线程函数实现
  29. UINT previewVideo(LPVOID lpParam)
  30. {
  31. // CWnd *video = (CWnd *)GetDlgItem(IDC_VIDEO);
  32. CStatic *video = (CStatic *)lpParam;
  33. CDC *pDC = video->GetDC();
  34. HDC hDC = pDC->GetSafeHdc();
  35. CRect rect;
  36. video->GetClientRect(&rect);
  37. CvvImage img;
  38. while (pFrame = cvQueryFrame(pCapture))
  39. {
  40.   nFrmNum ++;
  41.   img.CopyOf(pFrame);
  42.   img.DrawToHDC(hDC, &rect);
  43.   
  44. }
  45. // ReleaseDC(pDC);
  46. return 0;
  47. }


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值