opencv2:读入摄像机视频并写入AVI视频文件

2019-07-13 08:38发布

class="markdown_views prism-atom-one-light"> 首先用opencv 来显示一段视频,视频是提取成图片帧来播放的。

opencv读入一段视频

#include using namespace cv; int main(int argc, char** argv){ cvNamedWindow("Example2", CV_WINDOW_AUTOSIZE); CvCapture* capture = cvCreateFileCapture("Bye.mp4"); IplImage* frame; while(1){ frame = cvQueryFrame(capture); if(!frame) break; cvShowImage("Example2", frame); char c = cvWaitKey(33); if(c == 27) break; } cvReleaseCapture(&capture); cvDestroyWindow("Example2"); } 显示结果:
这里写图片描述 添加一个滚动条,但没有滚动条随代码播放移动功能。

opencv输出带有滚动条的视频播放

#include using namespace cv; int g_slider_position = 0; CvCapture* g_capture = NULL; void onTrackbarSlide(int pos){ cvSetCaptureProperty(g_capture, CV_CAP_PROP_POS_FRAMES, pos); } int main(int argc, char** argv){ cvNamedWindow("Example2", CV_WINDOW_AUTOSIZE); g_capture = cvCreateFileCapture("Bye.mp4"); int frames = (int) cvGetCaptureProperty(g_capture, CV_CAP_PROP_FRAME_COUNT); //obtain the total frame number of video if(frames!=0){ cvCreateTrackbar("Position", "Example2", &g_slider_position, frames, onTrackbarSlide); } CvCapture* capture = cvCreateFileCapture("Bye.mp4"); IplImage* frame; while(1){ frame = cvQueryFrame(capture); if(!frame) break; cvShowImage("Example2", frame); char c = cvWaitKey(33); if(c == 27) break; } cvReleaseCapture(&capture); cvDestroyWindow("Example2"); return 0; } 显示结果:
这里写图片描述

opencv从摄像机读入数据并写入AVI视频文件

#include using namespace cv; using namespace std; IplImage* in = NULL; IplImage* out = NULL; const char * InputTitle = "Input Video"; const char * OutputTitle = "Output Video"; int main(int argc, char** argv){ cvNamedWindow(InputTitle, CV_WINDOW_AUTOSIZE); cvNamedWindow(OutputTitle, CV_WINDOW_AUTOSIZE); CvCapture* capture; if(argc == 1){ capture = cvCreateCameraCapture(0); }else{ capture = cvCreateFileCapture("Bye.mp4"); } assert(capture != NULL); double fps = cvGetCaptureProperty(capture, CV_CAP_PROP_FPS); CvSize size = cvSize((int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH), (int)cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT)); CvVideoWriter* writer = cvCreateVideoWriter("shuchu2.avi", CV_FOURCC('M', 'J', 'P', 'S'), fps, size); // show IplImage* in_frame; IplImage* out_frame = cvCreateImage(size, IPL_DEPTH_8U, 1); while(in_frame = cvQueryFrame(capture)){ cvCvtColor(in_frame, out_frame, CV_BGR2GRAY); cvWriteFrame(writer, in_frame); cvShowImage(InputTitle, in_frame); cvShowImage(OutputTitle, out_frame); char c = cvWaitKey(33); if(c == 27) break; } waitKey(0); cvReleaseVideoWriter(&writer); cvReleaseCapture(&capture); cvDestroyWindow(InputTitle); cvDestroyWindow(OutputTitle); return 0; } 显示结果:
这里写图片描述