windows下摄像头的使用
windows下提供了调用摄像头的相关api函数,函数定义包含在vfw.h头文件中。
http://msdn.microsoft.com/zh-cn/dd757677 这个地址提供了完整的教程。
下面贴出一个简单的例子
头文件:
#ifndef pvcamerasnapshoter_h #define pvcamerasnapshoter_h #include <QtGui/QWidget> #include <QtGui/QPixmap> #include <QtCore/QByteArray> #include <Windows.h> #include <Vfw.h> #pragma comment(lib,"Vfw32.lib") class pvCameraSnapshoter : public QWidget { Q_OBJECT public: pvCameraSnapshoter(QWidget *parent = 0); ~pvCameraSnapshoter(void); bool OpenCamera(); //初始化摄像头 void CloseCamera(); QPixmap GetCameraSnapshot(); //保持一帧图片数据
private: HWND cameraScreenHwnd; }; #endif //pvcamerasnapshoter_h
实现文件:
#include <tchar.h> #include <QtGui/QBitmap> #include <QtCore/QByteArray> #include "pvCameraSnapshoter.h" #include "../common/pvcmuserpath.h" LRESULT PASCAL SnapshotFrameCbProc(HWND hWnd, LPVIDEOHDR lpVHdr); //回调函数用于处理接收到的图像数据
pvCameraSnapshoter::pvCameraSnapshoter(QWidget *parent) : QWidget(parent) { } pvCameraSnapshoter::~pvCameraSnapshoter(void) { } bool pvCameraSnapshoter::OpenCamera() { LPTSTR lpszName = new TCHAR[100]; LPTSTR lpszVer = new TCHAR[100]; capGetDriverDescription(0,lpszName,100,lpszVer,100); cameraScreenHwnd = capCreateCaptureWindow(lpszName, WS_CHILD | WS_VISIBLE, 0, 0, width(), height(), winId(), 0); //创建一个用来显示摄像头视频的窗口 if(cameraScreenHwnd == INVALID_HANDLE_VALUE) { return false; } if(capDriverConnect(cameraScreenHwnd,0)) //与链接摄像头 { capPreview(cameraScreenHwnd,true); //设置娱乐模式,这样与摄像头关联的窗口就可以自动显示视频数据了 capPreviewRate(cameraScreenHwnd,60); //每秒60帧 BITMAPINFO bitmapinfo; memset(&bitmapinfo,0,sizeof(BITMAPINFO)); bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bitmapinfo.bmiHeader.biWidth = 320; bitmapinfo.bmiHeader.biHeight = 240; bitmapinfo.bmiHeader.biPlanes = 1; bitmapinfo.bmiHeader.biBitCount = 32; bitmapinfo.bmiHeader.biCompression = BI_RGB; capSetVideoFormat(cameraScreenHwnd, &bitmapinfo, sizeof(bitmapinfo)); //设置摄像头的视频格式,不过这个函数好像不起作用 capSetUserData(cameraScreenHwnd,this); //添加用户数据,在回调函数中可能会用到 capSetCallbackOnFrame(cameraScreenHwnd,SnapshotFrameCbProc); //设置回调函数,摄像头的视频数据每一帧都会经过这个函数 return true; } return false; } void pvCameraSnapshoter::CloseCamera() { capDriverDisconnect(cameraScreenHwnd); } QPixmap pvCameraSnapshoter::GetCameraSnapshot() { QPixmap cameraSnapshot; if(cameraScreenHwnd == INVALID_HANDLE_VALUE) { return cameraSnapshot; } if(capGrabFrameNoStop(cameraScreenHwnd)) //抓取一帧图像数据,与capGrabFrame相比,它不会停止预览模式和重叠 { pvcmUserPath userpath; QString strSnapshotFile = userpath.GetUserSubPath("camerasnapshot").filePath("snapshot.bmp"); const wchar_t* wSnapshotpath = reinterpret_cast<const wchar_t*>(strSnapshotFile.utf16()); if(!capFileSaveDIB(cameraScreenHwnd,wSnapshotpath)) //保持摄像头快照 { qDebug("save camerasnapshot fail"); return cameraSnapshot; } cameraSnapshot.load(strSnapshotFile); } return cameraSnapshot; } LRESULT PASCAL SnapshotFrameCbProc(HWND hWnd, LPVIDEOHDR lpVHdr) { //这里处理视频数据return (LRESULT) TRUE ; } #include "moc_pvcamerasnapshoter.cpp"
版权声明:本文为jck34原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。