OpenCv calls the Camera Photo code and opencv calls the camera
We have recently studied how OpenCv calls cameras. The code is now posted for criticism and correction.
1. Statement
# Include ". /opencv2/opencv. hpp "# ifdef _ DEBUG # pragma comment (lib," opencv_core249d.lib ") # pragma comment (lib," release ") # else # pragma comment (lib," opencv_core249.lib ") # pragma comment (lib, "Warn") # endifusing namespace cv; class COpencvCameraCtrl: public CCameraBase {public: VideoCapture vc; public: COpencvCameraCtrl (void );~ COpencvCameraCtrl (void); public: BOOL OpenCamera (HWND win, CString strVid, CString strPid); // open the camera BOOL PhotoPic (CString strSaveFile); void CloseCamera ();};
2. Open the camera
// Open the camera BOOL tip: 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. Disable the camera
// Disable the camera void COpencvCameraCtrl: CloseCamera () {if (vc. isOpened () {vc. release ();}}
4. Take a photo and save it locally
// Camera BOOL COpencvCameraCtrl: PhotoPic (CString strSaveFile) {Mat frame; vc> frame; if (! Frame. data) {return FALSE;} // sets the image quality vector <int> compression_params; compression_params.push_back (imwrite_pai_quality); compression_params.push_back (75); imwrite (strSaveFile. getBuffer (0), frame, compression_params); strSaveFile. releaseBuffer (); return TRUE ;}
It should be noted that: each time data is obtained from the camera to the Mat, it needs to be executed twice.
Mat frame;vc >> frame;vc >> frame;if( !frame.data ){return FALSE;}
If you run the command only once, two problems will occur:
A. If you enable the camera and immediately call the camera to save the image, the first attempt will fail and the data cannot be obtained.
B. the last image is saved for each shot.