本文将用opencv打开摄像头、视频文件。
跟打开图片类似,视频的操作也十分简单。
VideoCapture类:opencv中通过VideoCapture类对视频进行读取操作及调用摄像头。
一、opencv打开摄像头
代码:
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videoio.hpp" #include <iostream> using namespace cv; using namespace std; int main() { cout << "Built with OpenCV " << CV_VERSION << endl; VideoCapture capture(0); // 打开摄像头 if(!capture.isOpened()) // 判断是否打开成功 { cout << "open camera failed. " << endl; return -1; } while(true) { Mat frame; capture >> frame; // 读取图像帧至frame if(!frame.empty()) // 判断是否为空 { imshow("camera", frame); } if(waitKey(30) > 0) // delay 30 ms等待按键 { break; } } return 0; }
编译运行:
二、opencv打开视频文件
代码:
#include "opencv2/core.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" #include "opencv2/videoio.hpp" #include <iostream> using namespace cv; using namespace std; int main() { cout << "Built with OpenCV " << CV_VERSION << endl; VideoCapture video; video.open("video.avi"); // 打开视频文件 if(!video.isOpened()) // 判断是否打开成功 { cout << "open video file failed. " << endl; return -1; } while(true) { Mat frame; video >> frame; // 读取图像帧至frame if(!frame.empty()) // frame是否为空 { imshow("video", frame); // 显示图像 } if(waitKey(30) > 0) // delay 30 ms 等待是否按键 { break; } } return 0; }
编译运行:
至此,简单的用opencv打开摄像头及视频文件已完成。