zoukankan      html  css  js  c++  java
  • OpenCv调用摄像头拍照代码

    近期在研究OpenCv对摄像头的调用。现将代码贴出,供大家批评指正。

    1、申明

    #include"./opencv2/opencv.hpp"
    
    #ifdef _DEBUG
    
    #pragma comment(lib,"opencv_core249d.lib")
    #pragma comment(lib,"opencv_highgui249d.lib")
    
    #else
    
    #pragma comment(lib,"opencv_core249.lib")
    #pragma comment(lib,"opencv_highgui249.lib")
    
    #endif
    
    using namespace cv;
    
    class COpencvCameraCtrl :
    	public CCameraBase
    {
    public:
    	VideoCapture vc;
    public:
    	COpencvCameraCtrl(void);
    	~COpencvCameraCtrl(void);
    
    public:
    	BOOL OpenCamera( HWND win, CString strVid, CString strPid );		//打开摄像头
    	BOOL PhotoPic( CString strSaveFile );
    	void CloseCamera();
    };


    2、打开摄像头

    //打开摄像头
    BOOL COpencvCameraCtrl::OpenCamera(HWND win, CString strVid, CString strPid)
    {
    	InitCameraWin( win );
    
    	vid = strVid;
    	pid = strPid;
    
    	nIndex = GetCameraIndexInOs( vid, pid );
    
    	if( nIndex < 0 )
    	{
    		return FALSE;
    	}
    	
    	if( !vc.open( nIndex ) )
    	{
    		return FALSE;
    	}
    
    	vc.set( CV_CAP_PROP_FRAME_WIDTH, nWidth );
    	vc.set( CV_CAP_PROP_FRAME_HEIGHT, nHight );	
    
    	if( !vc.isOpened() )
    	{
    		bOpen = false;
    		return FALSE;
    	}
    
    	bOpen = true;	
    
    	return TRUE;
    }


    3、关闭摄像头

    //关闭摄像头
    void COpencvCameraCtrl::CloseCamera()
    {
    	if( vc.isOpened() )
    	{
    		vc.release();
    	}	
    }


    4、拍照而且保存到本地

    //拍摄摄像头
    BOOL COpencvCameraCtrl::PhotoPic( CString strSaveFile )
    {
    	Mat frame;
    	
    	vc >> frame;
    	vc >> frame;
    	
    	if( !frame.data )
    	{
    		return FALSE;
    	}
    
    	//设置图像质量
    	vector<int> compression_params;
    	compression_params.push_back( IMWRITE_JPEG_QUALITY );
    	compression_params.push_back( 75 );
    
    	imwrite( strSaveFile.GetBuffer(0), frame, compression_params );
    	strSaveFile.ReleaseBuffer();	
    
    	return TRUE;
    }


    须要说明的是:每次从摄像头获取数据到Mat,须要运行两次

    Mat frame;
    	
    	vc >> frame;
    	vc >> frame;
    	
    	if( !frame.data )
    	{
    		return FALSE;
    	}

    假设只运行一次,会出现两个问题:

    A、假设打开摄像头马上调用拍照保存,第一次会失败,获取不到数据

    B、每次拍摄保存的图片是上一次的图片

  • 相关阅读:
    数据结构入门
    C语言入门-全局变量
    C语言入门-类型定义
    C++ 名称空间嵌套
    C++ 名称空间
    C++ 一些术语
    C++ new初始化与定位new运算符
    网络时间自动同步工具
    C++ 语言链接性
    C++ 函数和链接性
  • 原文地址:https://www.cnblogs.com/yxwkf/p/5132969.html
Copyright © 2011-2022 走看看