从视频中抓拍图片
#include "opencv2/highgui/highgui.hpp" #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> #include <vector> #include <stdio.h> using namespace cv; using namespace std; int process(VideoCapture& capture) { int n = 0; char filename[200]; string window_name = "video | q or esc to quit";//窗口名称 cout << " \n\t按下【Space】空格键可以截图,图片将存放在工程目录下。\n\n\t【Esc】和【q】键 - 退出程序。 " << endl; namedWindow(window_name, CV_WINDOW_KEEPRATIO); // CV_WINDOW_KEEPRATIO:保持图像的比例 Mat frame; for (;;) { capture >> frame; if (frame.empty()) break; Mat gray; cvtColor(frame,gray,COLOR_RGB2GRAY); //彩色转化为灰度图 vector<string> codes; Mat corners; findDataMatrix(gray, codes, corners); drawDataMatrixCodes(frame, codes, corners); imshow(window_name, frame); char key = (char) waitKey(1); //delay N millis, usually long enough to display and capture input switch (key) { case 'q': case 'Q': case 27: //escape key return 0; case ' ': //Save an image sprintf(filename, "视频截图%.3d.jpg", n++);//格式化字符串 imwrite(filename, frame); //保存图片 cout << "\n\t>保存了 " << filename <<"文件到工程目录下"<< endl; break; default: break; } } return 0; } int main( ) { //VideoCapture capture("E:\\图片\\bike.avi"); //从本地载入视频 VideoCapture capture(0);//从摄像头载入视频 if (!capture.isOpened()) { cerr << "Failed to open a video device or video file!\n" << endl; return 1; } return process(capture); }