1 /*
2 * starter_video.cpp
3 *
4 * Created on: Nov 23, 2010
5 * Author: Ethan Rublee
6 *
7 * Modified on: April 17, 2013
8 * Author: Kevin Hughes
9 *
10 * A starter sample for using OpenCV VideoCapture with capture devices, video files or image sequences
11 * easy as CV_PI right?
12 */
13
14 #include <opencv2/imgcodecs.hpp>
15 #include <opencv2/videoio/videoio.hpp>
16 #include <opencv2/highgui/highgui.hpp>
17
18 #include <iostream>
19 #include <stdio.h>
20
21 using namespace cv;
22 using namespace std;
23
24 //hide the local functions in an anon namespace
25 namespace {
help(char ** av)26 void help(char** av) {
27 cout << "The program captures frames from a video file, image sequence (01.jpg, 02.jpg ... 10.jpg) or camera connected to your computer." << endl
28 << "Usage:\n" << av[0] << " <video file, image sequence or device number>" << endl
29 << "q,Q,esc -- quit" << endl
30 << "space -- save frame" << endl << endl
31 << "\tTo capture from a camera pass the device number. To find the device number, try ls /dev/video*" << endl
32 << "\texample: " << av[0] << " 0" << endl
33 << "\tYou may also pass a video file instead of a device number" << endl
34 << "\texample: " << av[0] << " video.avi" << endl
35 << "\tYou can also pass the path to an image sequence and OpenCV will treat the sequence just like a video." << endl
36 << "\texample: " << av[0] << " right%%02d.jpg" << endl;
37 }
38
process(VideoCapture & capture)39 int process(VideoCapture& capture) {
40 int n = 0;
41 char filename[200];
42 string window_name = "video | q or esc to quit";
43 cout << "press space to save a picture. q or esc to quit" << endl;
44 namedWindow(window_name, WINDOW_KEEPRATIO); //resizable window;
45 Mat frame;
46
47 for (;;) {
48 capture >> frame;
49 if (frame.empty())
50 break;
51
52 imshow(window_name, frame);
53 char key = (char)waitKey(30); //delay N millis, usually long enough to display and capture input
54
55 switch (key) {
56 case 'q':
57 case 'Q':
58 case 27: //escape key
59 return 0;
60 case ' ': //Save an image
61 sprintf(filename,"filename%.3d.jpg",n++);
62 imwrite(filename,frame);
63 cout << "Saved " << filename << endl;
64 break;
65 default:
66 break;
67 }
68 }
69 return 0;
70 }
71 }
72
main(int ac,char ** av)73 int main(int ac, char** av) {
74
75 if (ac != 2) {
76 help(av);
77 return 1;
78 }
79 std::string arg = av[1];
80 VideoCapture capture(arg); //try to open string, this will attempt to open it as a video file or image sequence
81 if (!capture.isOpened()) //if this fails, try to open as a video camera, through the use of an integer param
82 capture.open(atoi(arg.c_str()));
83 if (!capture.isOpened()) {
84 cerr << "Failed to open the video device, video file or image sequence!\n" << endl;
85 help(av);
86 return 1;
87 }
88 return process(capture);
89 }
90