opencv攝像頭獲取連續影象(一) :單目獲取影象
阿新 • • 發佈:2019-02-20
利用攝像頭獲取連續影象
1.設定幀數為30fps
2.讀取攝像頭5秒視訊
2.將讀取到的視訊以每5幀採取一幅影象,共計30張,並儲存。
原始碼如下:
#include <iostream> #include <opencv2/opencv.hpp> using namespace std; using namespace cv; int main() { VideoCapture cap(0);//開啟電腦攝像頭 if (cap.isOpened()) cout << "camera is opened"<< endl; else cout << "camera is not opened" << endl; bool stop = false; Mat frame; //設定攝像頭解析度640*480 幀率30fps cap.set(CV_CAP_PROP_FRAME_HEIGHT, 480); cap.set(CV_CAP_PROP_FRAME_WIDTH, 640); cap.set(CV_CAP_PROP_FPS, 30.0); //儲存視訊格式為avi, 編碼為MJPG VideoWriter writer("test0.avi",CV_FOURCC('M', 'J', 'P', 'G'),30, Size(640,480),true); //通過總幀數控制拍攝時間,如果為5s的視訊,迴圈5*30次; Mat videoPlay; int count = 150; namedWindow("videoplay", WINDOW_NORMAL); while (count) { cap >> videoPlay; writer << videoPlay; imshow("videoplay", videoPlay); waitKey(30); count --; } VideoCapture cap0("test0.avi"); if(!cap0.isOpened()) cout << "no video" << endl; Mat frame0; int num = 1; string filename; char temp_file[5]; string path = "C:\\Users\\Administrator\\Desktop\\my\\pic";//can change the path for (int i = 1; ;i++) { cap0 >> frame0; if(frame0.empty()) break; if(i % 5 == 0) { _itoa_s(num, temp_file, 4, 10); filename = temp_file; filename = path + filename + ".jpg"; num ++; imwrite (filename,frame0); } } cap0.release(); //system("pause"); return 0; }