This article will use opencv to open camera and video files.
Similar to opening a picture, the operation of a video is also very simple.
VideoCapture class: In opencv, the video is read and the camera is called through the VideoCapture class.
First, opencv open the camera
Code:
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videoio.hpp" #include <iostream> using namespace cv; using namespace std; intmain() { cout << "Built with OpenCV " << CV_VERSION << endl; VideoCapture capture(0); // open the camera if(!capture.isOpened()) // determine whether the opening is successful { cout << "open camera failed. " << endl; return -1; } while(true) { Mat frame; capture >> frame; // read image frame to frame if(!frame.empty()) // determine whether it is empty { imshow("camera", frame); } if(waitKey(30) > 0) // delay 30 ms to wait for the key { break; } } return 0; }
Compile and run:
Second, opencv to open the video file
Code:
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videoio.hpp" #include <iostream> using namespace cv; using namespace std; intmain() { cout << "Built with OpenCV " << CV_VERSION << endl; VideoCapture video; video.open("video.avi"); // open video file if(!video.isOpened()) // Determine whether the opening is successful { cout << "open video file failed. " << endl; return -1; } while(true) { Mat frame; video >> frame; // read image frame to frame if(!frame.empty()) // Is the frame empty { imshow("video", frame); // show the image } if(waitKey(30) > 0) // delay 30 ms to wait for a key { break; } } return 0; }
Compile and run:
So far, the simple use of opencv to open the camera and video files has been completed.