1、代码
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <fstream>
using namespace std;
int g_slider_position = 0; //全局变量来表示滑动条的位置
int g_run = 1, g_dontset = 0; //start out in single step mode
cv::VideoCapture g_cap;
void onTrackbarSlide( int pos, void *) {
g_cap.set( cv::CAP_PROP_POS_FRAMES, pos );
/*set(参数1,参数2)set方法能让我们取出视频帧序列中的指定的帧,参数1和参数2配合使用,参数1决定是按照什么序列方式取帧,例如 参数1=CAP_PROP_POS_FRAMES ,则取帧按照帧个数序列,即 参数2指第几帧。参数1=CV_CAP_PROP_POS_MSEC,则取帧按照时间序列
,即 参数2指第几毫秒的帧。参数1=CV_CAP_PROP_POS_AVI_RATIO,则取帧按比例方式,如参数2=0.5,则指视频中间位置的帧。*/
if( !g_dontset ) g_run = 1;
g_dontset = 0;
}
void help(char** argv ) {
std::cout << "\n"
<< "2-04: Addeing a trackbar to a basic viewer for moving w/in the video file \n"
<< argv[0] <<" <path/video>\n"
<< "For example:\n"
<< argv[0] << " ../tree.avi\n"
<< std::endl;
}
int main( int argc, char** argv ) {
if (argc != 2) {
help(argv);
return 0;
}
cv::namedWindow( "Example 2-4", cv::WINDOW_AUTOSIZE );
g_cap.open( string(argv[1]) );
int frames = (int) g_cap.get( cv::CAP_PROP_FRAME_COUNT );
int tmpw = (int) g_cap.get(cv::CAP_PROP_FRAME_WIDTH );
int tmph = (int) g_cap.get(cv::CAP_PROP_FRAME_HEIGHT );
cout << "Video has " << frames << " frames of dimensions("
<< tmpw << ", " << tmph << ")." << endl;
/*createTrackbar(参数1,参数2,参数3,参数4,参数5,参数6) 创建滑动条,参数1:轨迹条名字 参数 2:窗口名字 参数 3:滑块初始位置 参数4:表示滑块达到最大位置的值 参数 5:默认值为0,指向回调函数 参数 6:默认值为0,用户传给回调函数的数据值*/
cv::createTrackbar( "Position", "Example 2-4", &g_slider_position,frames, onTrackbarSlide);
cv::Mat frame;
for(;;) {
if( g_run != 0 ) { //g_run 初始值为1
g_cap >> frame;
if(frame.empty()) break;
int current_pos = (int)g_cap.get(cv::CAP_PROP_POS_FRAMES );//得到当前帧位置,按帧数序列
g_dontset = 1;//初始值为0
cv::setTrackbarPos("Position", "Example 2-4", current_pos);//"Position"滑动条名称,"Example 2-4"窗口名称,current_pos 新位置。
cv::imshow( "Example 2-4", frame ); //显示当前帧
g_run-=1;
}
char c = (char) cv::waitKey(10);
if( c == 's' ) { // single step
g_run = 1;
cout << "Single step, run = " << g_run << endl;
}
if( c == 'r' ) { // run mode
g_run = -1;
cout << "Run mode, run = " << g_run <<endl;
}
if( c == 27 ) break;
}
return(0);
}
2、调试
程序运行以后,点击视频窗口,键盘输入切换为英文小写,当点击键盘r时,视频自动播放,当点击s时单步播放(点一次s播放1帧)