VC捕捉摄像头图像入门源码要点_第1页
VC捕捉摄像头图像入门源码要点_第2页
VC捕捉摄像头图像入门源码要点_第3页
VC捕捉摄像头图像入门源码要点_第4页
VC捕捉摄像头图像入门源码要点_第5页
已阅读5页,还剩11页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、【转】vc捕捉摄像头图像入门源码vc捕捉摄像头图像入门源码(非常适合新手)(转)默认分类2009-11-02 17:46:56 阅读39评论0字号:大中 小此源码是我更改过的基于 vfw(video for windows)的源码,使用了定时器能 实时的显示图像,从网上可搜到原版源码,但是原版的功能是保存为一个文件, 且不能实时显示,此版本虽然能显示,但感觉反应速度不是很快,没有基于 directshow的程序更新速度快,不过在 wm_paint息处理里加while(1)capgrabframe(ghwndcap);刷新速度就快很多了,但是这样程序就进 入死循环不能再处理其他消息,至于怎样改进

2、,就靠读者你了。/源码的任何部分都可以在 msdn!查至ij,请参考 msdn#include <windows.h>#include <stdio.h>#include <vfw.h>#pragma comment(lib,"vfw32.lib")hwnd ghwndcap ; /f甫获窗的句柄capstatus gcapstatus ; / 捕获窗的状态capdrivercaps gcapdrivercaps ; 视频驱动的能力 char gachbuffer20;/char szcapturefile口 = "camcap

3、ture.avi"/ / statuscallbackproc: 册这个回调函数。/ hwnd:/ nid:/ lpstatustext:状态回调函数,使用capsetcallbackonstatus 宏来注捕获窗体句柄当前状态的状态码 当前状态的文本字符/lresult callback statuscallbackproc(hwnd hwnd,int nid,lpstr lpstatustext)if(!ghwndcap)return false;/获得捕获窗的状态capgetstatus(ghwndcap,&gcapstatus,sizeof(capstatus);/

4、更新捕获窗的大小 , 得到消息 wm_cap_get_statussetwindowpos(ghwndcap,null,0,0,gcapstatus.uiimagewidth,gcapstatus.uii mageheight,swp_nozorder|swp_nomove);if(nid=0)/ 清除旧的状态信息setwindowtext(ghwndcap,(lpstr)"hello");return (lresult)true;/ 显示状态 id 和状态文本wsprintf(gachbuffer,"status# %d: %s",nid,lpstat

5、ustext);setwindowtext(ghwndcap,(lpstr)gachbuffer);return (lresult)true;/ errorcallbackproc:错误回调函数, 过 capsetcallbackonerror 宏来 注册回调捕获窗口句柄错误代码关于错误的文本信息/ hwnd:/ nerrid: / lperrortext: /lresult callback errorcallbackproc(hwnd hwnd,int nerrid,lpstr lperrortext)if(!ghwndcap)return false;if(nerrid=0)return

6、 true;/ 清除旧的错误wsprintf(gachbuffer,"error# %d",nerrid);/ 显示错误标识和文本messagebox(hwnd, lperrortext, gachbuffer,mb_ok | mb_iconexclamation); return (lresult) true;/ framecallbackproc: 帧回调函数, 通过 capsetcallbackframe 宏来注册捕获窗体句柄指向一个包含帧信息的数据结构体回调函数/ hwnd:/ lpvhdr: / /lresult callback framecallbackpro

7、c(hwnd hwnd,lpvideohdr lpvhdr) file *fp;fp=fopen("caram.dat","w");if(!ghwndcap)return false;/ 假设 fp 为一打开的 .dat 文件指针fwrite(lpvhdr->lpdata,1,lpvhdr->dwbufferlength,fp); return (lresult)true;/ /timerproc 函数处理定时器,在这里抓取并显示图像/void callback timerproc(hwnd hwnd,/ handle to windowui

8、nt umsg,/ wm_timer messageuint_ptr idevent, / timer identifierdword dwtime/ current system time)capgrabframe(ghwndcap);/ 主回调函数/lresult callback windowproc(hwnd hwnd,/ handle to windowuint umsg,/ message identifierwparam wparam, / first message parameter lparam lparam / second message parameter )/ hd

9、c hdc;/ paintstruct ps;/ rect rect;switch(umsg)case wm_create:ghwndcap=capcreatecapturewindow(lpstr)"capture window",ws_child|ws_visible,0,0,320,240,(hwnd)hwnd,(int)0);capsetcallbackonerror(ghwndcap,(farproc)errorcallbackproc);capsetcallbackonstatus(ghwndcap,(farproc)statuscallbackproc); c

10、apsetcallbackonframe(ghwndcap,(farproc)framecallbackproc);capdriverconnect(ghwndcap,0); / 将捕获窗同驱动连接capdrivergetcaps(ghwndcap,&gcapdrivercaps,sizeof(capdrivercaps);/ 获得驱动的能力 , 相关的信息放在结构变量gcapdrivercaps 中cappreviewrate(ghwndcap, 66); /uses this macro to set the framedisplay rate for preview mode t

11、o 66 milliseconds per framecappreview(ghwndcap, true); /and then uses the cappreview macro to place the capture window in preview mode.if(gcapdrivercaps.fhasoverlay) / 检查驱动器是否有叠加能力capoverlay(ghwndcap,true); / 启动 overlay 模式if(gcapdrivercaps.fhasdlgvideosource)capdlgvideosource(ghwndcap);/video source

12、 对话框if(gcapdrivercaps.fhasdlgvideoformat)capdlgvideoformat(ghwndcap);/ video format 对话框if(gcapdrivercaps.fhasdlgvideodisplay)capdlgvideodisplay(ghwndcap); / video display 对话框/ capfilesetcapturefile( ghwndcap,szcapturefile); / 将要保存的文件名设为本源文件开头处的全局字符串常量/ capfilealloc(ghwndcap, (1024l * 1024l * 5); / 为

13、捕获文件分配存储空间capcapturesequence(ghwndcap); / 开始捕获视频序列/ capgrabframe(ghwndcap); / 捕获单帧图像settimer(hwnd,1,10,timerproc);break;case wm_paint:capgrabframe(ghwndcap);/* hdc=beginpaint(hwnd,&ps);getclientrect(hwnd,&rect);drawtext(hdc,text("hello,windowsxp!"),-1,&rect,dt_singleline|dt_cen

14、ter|dt_vcenter);endpaint(hwnd,&ps);*/break;case wm_close: if(idyes=messagebox(hwnd,"sure exit ?","camcapture",mb_yesno) destroywindow(hwnd); break;case wm_destroy:killtimer(hwnd,1);capsetcallbackonstatus(ghwndcap,null); capsetcallbackonerror(ghwndcap,null); capsetcallbackonfr

15、ame(ghwndcap,null); capcaptureabort(ghwndcap);/ 停止捕获 capdriverdisconnect(ghwndcap); / 将捕获窗同驱动断开 postquitmessage(0); break;default:return defwindowproc(hwnd,umsg,wparam,lparam); return 0;/ 主函数int winapi winmain(hinstance hinstance,/ handle to currentinstancehinstance hprevinstance, / handle to previo

16、us instancelpstr lpcmdline,/ command lineint ncmdshow/ show state) static tchar szappname=text("camcapture"); wndclass wndcls; hwnd hwnd; msg msg;wndcls.cbclsextra=0;wndcls.cbwndextra=0;wndcls.hbrbackground=(hbrush)getstockobject(black_brush); wndcls.hcursor=loadcursor(null,idc_cross); wnd

17、cls.hicon=loadicon(null,idi_question); wndcls.hinstance=hinstance;wndcls.lpfnwndproc=windowproc;wndcls.lpszclassname="camcapture"wndcls.lpszmenuname=null;wndcls.style=cs_hredraw | cs_vredraw;if(!registerclass(&wndcls)messagebox(null,text("this program requires windows nt!"),s

18、zappname,mb_iconerror);return 0;hwnd=createwindow("camcapture","camcapture",ws_overlappedwindow, cw_usedefault,cw_usedefault,320,240,null,null,hinstance,null);showwindow(hwnd,ncmdshow);updatewindow(hwnd);while(getmessage(&msg,null,0,0)translatemessage(&msg);dispatchmessag

19、e(&msg);return 0;摘要: 本文主要讲述用 directshow 进行视频捕捉 (捕捉静态图像) 的编程思路,并提供针对摄像头编程的一个视频捕捉类ccapturevideo 和一个示例。、户 、.前言directshow是微软公司提供的一套在 windows平台上进行流媒体处理的开发包,与 directx 开发包一起发布。 directshow 为多媒体流的捕捉和回放提供了强有力的支持。用 directshow 开发应用程序,我们可以很方便地从支持wdm驱动模型的采集卡上捕获数据,并且进行相应的后期处理乃至存储到文件中。directshow是基于com勺,为了编写 dir

20、ectshow应用程序,需要了解 com客户程序编写的基础知识。 directshow 提供了大量的接口,但在编程中发现还是不够方便, 如果能构建一个视频捕捉类把常用的一些动作封装起来, 那么就更方便了。编程思路为了更加容易建立视频捕捉应用程序, directshow 提供了一个叫做capturegraph builder 的对象, capture graph builder 提供 icapturegraphbuilder2 接口,该接口可以建立和控制 capture graph 。建立视频捕捉程序,必须首先获取并初始化 icapturegraphbuilder2 接口,然后选择一个适当的视频

21、捕捉设备。选择好设备后,为该设备创建capturefilter ,然后调用 addfilter 把 capture filter 添加到 filter graph 。如果仅仅希望用摄像头来进行实时监控的话,只需要在上面的基础上调用icapturegraphbuilder2:renderstream 就可以了:icapturegraphbuilder2 *pbuild; / capture graph builder/ 省略初始化部分代码ibasefilter *pcap; / video capture filter./ 省略初始化和添加到 filter graph 部分代码pbuild-&g

22、t;renderstream(&pin_category_preview, &mediatype_video, pcap, null, null);directshow 提供了一个捕捉静态图像的方法: 使用 samplegrabber filter 。依次按照以下三个步骤就可以了:第一步 , 定义一个类实现sample grabber 的回调接口 isamplegrabbercb :class csamplegrabbercb : public isamplegrabbercb / 在后面提供的类中具体完成csamplegrabbercb mcb;第二步、调用 renderst

23、ream 依次把 still pin 、 sample grabber 和系统默 认 renderer filter 连接起来。第三步、配置sample grabber 以捕获数据。视频捕捉类ccapturevideo 的具体实现/ ccapturevideo 视频捕捉类头文件/#if !defined(afx_capturevideo_h_f5345aa4_a39f_4b07_b843_3d87c4287aa0 _included_)#defineafx_capturevideo_h_f5345aa4_a39f_4b07_b843_3d87c4287aa0_included_ / captu

24、revideo.h : header file/#if _msc_ver > 1000#pragma once#endif / _msc_ver > 1000#include <atlbase.h>#include <windows.h>#include <dshow.h>#ifndef safe_release#define safe_release( x ) if ( null != x ) x->release( ); x = null; #endifclass csamplegrabbercb;class ccapturevideo

25、 : public cwndfriend class csamplegrabbercb;public:void graboneframe(bool bgrab);hresult init(int ideviceid,hwnd hwnd);int enumdevices(hwnd hlist);ccapturevideo();virtual ccapturevideo();private:hwnd m_hwnd;igraphbuilder *m_pgb;icapturegraphbuilder2* m_pcapture;ibasefilter* m_pbf;imediacontrol* m_pm

26、c;ivideowindow* m_pvw;ccomptr<isamplegrabber> m_pgrabber;protected:void freemediatype(am_media_type& mt);bool bindfilter(int deviceid, ibasefilter *pfilter);void resizevideowindow();hresult setupvideowindow();hresult initcapturegraphbuilder();#endif/ !defined(afx_capturevideo_h_f5345aa4_a3

27、9f_4b07_b843_3d87c4287aa0_included_)/ ccapturevideo 视频捕捉类实现文件 capturevideo.cpp/ capturevideo.cpp: implementation of the ccapturevideo class./#include "stdafx.h"#include "capturevideo.h"#ifdef _debug#undef this_filestatic char this_file=_file_;#define new debug_new#endifbool bones

28、hot=false;/全局变量class csamplegrabbercb : public isamplegrabbercbpublic:long lwidth;long lheight;tchar m_szfilenamemax_path;位图文件名称csamplegrabbercb( )strcpy(m_szfilename, "c:donaldo.bmp");stdmethodimp_(ulong) addref() return 2; stdmethodimp_(ulong) release() return 1; stdmethodimp queryinterf

29、ace(refiid riid, void * ppv)if( riid = iid_isamplegrabbercb | riid = iid_iunknown )*ppv = (void *) static_cast<isamplegrabbercb*> ( this );return noerror;return e_nointerface;stdmethodimp samplecb( double sampletime, imediasample * psample ) return 0;stdmethodimp buffercb( double dblsampletime

30、, byte * pbuffer, long lbuffersize )if( !boneshot )return 0;if (!pbuffer)return e_pointer;savebitmap(pbuffer, lbuffersize);boneshot = false;return 0;/ 创建位图文件bool savebitmap(byte * pbuffer, long lbuffersize )handle hf = createfile(m_szfilename, generic_write, file_share_read, null,create_always, null

31、, null );if( hf = invalid_handle_value )return 0;/ 写文件头bitmapfileheader bfh;memset( &bfh, 0, sizeof( bfh ) );bfh.bftype = mb;bfh.bfsize = sizeof( bfh ) + lbuffersize + sizeof( bitmapinfohead)e; rbfh.bfoffbits = sizeof( bitmapinfoheader ) +sizeof( bitmapfileheader );dword dwwritten = 0;writefile(

32、 hf, &bfh, sizeof( bfh ), &dwwritten, null );/ 写位图格式bitmapinfoheader bih;memset( &bih, 0, sizeof( bih ) );bih.bisize = sizeof( bih );bih.biwidth = lwidth;bih.biheight = lheight;bih.biplanes = 1;bih.bibitcount = 24;writefile( hf, &bih, sizeof( bih ), &dwwritten, null );/ 写位图数据writ

33、efile( hf, pbuffer, lbuffersize, &dwwritten, null );closehandle( hf );return 0;csamplegrabbercb mcb;/ construction/destruction/ccapturevideo:ccapturevideo()/com library intializationif(failed(coinitialize(null) /*, coinit_apartmentthreaded)*/afxmessagebox("coinitialize failed!rn");retu

34、rn;m_hwnd = null;m_pvw = null;m_pmc = null;m_pgb = null;m_pcapture = null;ccapturevideo:ccapturevideo()/ stop media playbackif(m_pmc)m_pmc->stop();if(m_pvw)m_pvw->put_visible(oafalse);m_pvw->put_owner(null);safe_release(m_pcapture);safe_release(m_pmc);safe_release(m_pgb);safe_release(m_pbf)

35、;couninitialize( );int ccapturevideo:enumdevices(hwnd hlist)if (!hlist)return -1;int id = 0;/ 枚举视频扑捉设备icreatedevenum *pcreatedevenum;hresult hr = cocreateinstance(clsid_systemdeviceenum, null,clsctx_inproc_server,iid_icreatedevenum, (void*)&pcreatedevenum);if (hr != noerror)return -1;ccomptr<

36、ienummoniker> pem;hr =pcreatedevenum->createclassenumerator(clsid_videoinputdevicecategory, &pem, 0);if (hr != noerror)return -1;pem->reset();ulong cfetched;imoniker *pm;while(hr = pem->next(1, &pm, &cfetched), hr=s_ok)ipropertybag *pbag;hr = pm->bindtostorage(0, 0, iid_ip

37、ropertybag, (void *)&pbag); if(succeeded(hr)variant var;var.vt = vt_bstr;hr = pbag->read(l"friendlyname", &var, null);if (hr = noerror)tchar str2048;id+;widechartomultibyte(cp_acp,0,var.bstrval, -1, str, 2048, null, null);:sendmessage(hlist, cb_addstring, 0,(lparam)str);sysfrees

38、tring(var.bstrval);pbag->release();pm->release();return id;hresult ccapturevideo:init(int ideviceid, hwnd hwnd)hresult hr;hr = initcapturegraphbuilder();if (failed(hr)afxmessagebox("failed to get video interfaces!"); return hr;/ bind device filter. we know the device because the id w

39、as passed in if(!bindfilter(ideviceid, &m_pbf)return s_false;hr = m_pgb->addfilter(m_pbf, l"capture filter");/ hr = m_pcapture->renderstream(&pin_category_preview, &mediatype_video,/ m_pbf, null, null);/ create a sample grabberhr = m_pgrabber.cocreateinstance( clsid_sampl

40、egrabber );if( !m_pgrabber )afxmessagebox("fail to create samplegrabber, maybeqedit.dll is not registered?");return hr;ccomqiptr< ibasefilter, &iid_ibasefilter > pgrabbase( m_pgrabber );/ 设置视频格式am_media_type mt;zeromemory(&mt, sizeof(am_media_type);mt.majortype = mediatype_vi

41、deo;mt.subtype = mediasubtype_rgb24;hr = m_pgrabber->setmediatype(&mt);if( failed( hr ) )afxmessagebox("fail to set media type!");return hr;hr = m_pgb->addfilter( pgrabbase, l"grabber" );if( failed( hr ) )afxmessagebox("fail to put sample grabber in graph");re

42、turn hr;/ try to render preview/capture pinhr = m_pcapture->renderstream(&pin_category_preview, &mediatype_video,m_pbf,pgrabbase,null);if( failed( hr ) )hr = m_pcapture->renderstream(&pin_category_capture, &mediatype_video,m_pbf,pgrabbase,null);if( failed( hr ) )afxmessagebox(&

43、quot;can t build the graph");return hr;hr = m_pgrabber->getconnectedmediatype( &mt );if ( failed( hr) )afxmessagebox("failt to read the connected media type");return hr;videoinfoheader * vih = (videoinfoheader*) mt.pbformat;mcb.lwidth = vih->bmiheader.biwidth;mcb.lheight = v

44、ih->bmiheader.biheight;freemediatype(mt);hr = m_pgrabber->setbuffersamples( false );hr = m_pgrabber->setoneshot( false );hr = m_pgrabber->setcallback( &mcb, 1 );/ 设置视频捕捉窗口m_hwnd = hwnd ;setupvideowindow();hr = m_pmc->run();/ 开始视频捕捉if(failed(hr)afxmessagebox("couldn t run the

45、graph!");return hr; return s_ok;bool ccapturevideo:bindfilter(int deviceid, ibasefilter *pfilter)if (deviceid < 0) return false;/ enumerate all video capture devicesccomptr<icreatedevenum> pcreatedevenum;hresult hr = cocreateinstance(clsid_systemdeviceenum, null,clsctx_inproc_server,ii

46、d_icreatedevenum, (void*)&pcreatedevenum);if (hr != noerror)return false;ccomptr<ienummoniker> pem;hr =pcreatedevenum->createclassenumerator(clsid_videoinputdevicecategory, &pem, 0);if (hr != noerror)return false;pem->reset();ulong cfetched;imoniker *pm;int index = 0;while(hr = p

47、em->next(1, &pm, &cfetched), hr=s_ok, index <= deviceid)ipropertybag *pbag;hr = pm->bindtostorage(0, 0, iid_ipropertybag, (void *)&pbag); if(succeeded(hr)variant var;var.vt = vt_bstr;hr = pbag->read(l"friendlyname", &var, null);if (hr = noerror)if (index = devic

48、eid)pm->bindtoobject(0, 0, iid_ibasefilter, (void*)pfilter);sysfreestring(var.bstrval);pbag->release();pm->release();index+;return true;hresult ccapturevideo:initcapturegraphbuilder()hresult hr;/ 创建 igraphbuilder 接口hr=cocreateinstance(clsid_filtergraph, null, clsctx_inproc_server, iid_igrap

49、hbuilder, (void *)&m_pgb);/ 创建 icapturegraphbuilder2 接口hr = cocreateinstance (clsid_capturegraphbuilder2 , null,clsctx_inproc,iid_icapturegraphbuilder2, (void *) &m_pcapture);if (failed(hr)return hr;m_pcapture->setfiltergraph(m_pgb);hr = m_pgb->queryinterface(iid_imediacontrol, (void *)&m_pmc);if (failed(hr)return hr;hr = m_pgb->queryinterface(iid_ivideowindow, (lpvoid *) &m_pvw);if (failed(hr)return hr;return hr;hresult ccapturevideo:setupvideowindow()hr

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论