Environment
: CentOS7
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16)
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16)
$ pkg-config --modversion opencv 2.4.13
The video used in the test is the avi test video that comes with Opencv. The file path is: opencv-3.4.0\sources\samples\data\vtest.avi
If you can't find the download, you can also go to https://download.csdn.net/download/rong_toa/10392225 to download.
Source code:
#include<stdlib.h> #include<stdio.h> #include<math.h> #include<cv.h> #include<highgui.h> #include<iostream> using namespace std; int main(int argc,char**argv) { /******Initialize a camera capture******/ //CvCapture* capture1 = cvCaptureFromCAM(0); /*****Initialize a video file capturer*****/ CvCapture* capture = cvCaptureFromAVI("vtest.avi"); /**/ IplImage* img = 0; if(!cvGrabFrame(capture)){ // capture a frame printf("Could not grab a frame\n\7"); exit(0); } img=cvRetrieveFrame(capture); cvSaveImage("out.jpg",img); /******Get/Set video stream information*****/ /*Get video streaming device information*/ cvQueryFrame(capture); // Do this before reading the video stream information int frameH = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); int frameW = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); int fps = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FPS); int numFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_COUNT); /*Get frame info*/ float posMsec = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_MSEC); int posFrames = (int) cvGetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES); float posRatio = cvGetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO); /*Set the position of the first frame captured from the video file*/ //cvSetCaptureProperty(capture, CV_CAP_PROP_POS_AVI_RATIO, (double)0.9); img=cvRetrieveFrame(capture); cvSaveImage("out2.jpg",img); /******Save video file******/ /* Initialize the video writer */ CvVideoWriter *writer = 0; int isColor = 1; //fps = 25; // or 30 //frameW = 640; // 744 for firewire cameras //frameH = 480; // 480 for firewire cameras writer=cvCreateVideoWriter("out.avi",CV_FOURCC('D', 'I', 'V', 'X'), fps,cvSize(frameW,frameH),isColor); /*Save the video file*/ IplImage* img1 = 0; int nFrames = 80, key; for(int i=0;i<nFrames;i++){ cvGrabFrame(capture); // capture a frame img1=cvRetrieveFrame(capture); // retrieve the captured frame // img = cvQueryFrame(capture); cvShowImage("mainWin", img); key=cvWaitKey(40); // wait 20 ms cvWriteFrame(writer,img1); // add the frame to the file } /* release the video stream catcher */ cvReleaseCapture(&capture); /* release the video writer */ cvReleaseVideoWriter(&writer); return 0; }
Compile and run:
$ make g++ main.cpp `pkg-config --cflags --libs opencv` $ ./a.out
After running, a window will pop up to play a video, and two video screenshots will be saved after running (an example is given here).
For more information, see: "OpenCV Chinese Reference Manual"