1、代碼
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <fstream>
using namespace std;
int g_slider_position = 0;? //全局變量來表示滑動(dòng)條的位置
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(參數(shù)1,參數(shù)2)set方法能讓我們?nèi)〕鲆曨l幀序列中的指定的幀,參數(shù)1和參數(shù)2配合使用,參數(shù)1決定是按照什么序列方式取幀,例如 參數(shù)1=CAP_PROP_POS_FRAMES ,則取幀按照幀個(gè)數(shù)序列,即 參數(shù)2指第幾幀。參數(shù)1=CV_CAP_PROP_POS_MSEC,則取幀按照時(shí)間序列
,即 參數(shù)2指第幾毫秒的幀。參數(shù)1=CV_CAP_PROP_POS_AVI_RATIO,則取幀按比例方式,如參數(shù)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(參數(shù)1,參數(shù)2,參數(shù)3,參數(shù)4,參數(shù)5,參數(shù)6) 創(chuàng)建滑動(dòng)條,參數(shù)1:軌跡條名字 參數(shù) 2:窗口名字 參數(shù) 3:滑塊初始位置? 參數(shù)4:表示滑塊達(dá)到最大位置的值 參數(shù)? 5:默認(rèn)值為0,指向回調(diào)函數(shù) 參數(shù)? 6:默認(rèn)值為0,用戶傳給回調(diào)函數(shù)的數(shù)據(jù)值*/
? 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 );//得到當(dāng)前幀位置,按幀數(shù)序列
? ? ? g_dontset = 1;//初始值為0
? ? ? cv::setTrackbarPos("Position", "Example 2-4", current_pos);//"Position"滑動(dòng)條名稱,"Example 2-4"窗口名稱,current_pos 新位置。
? ? ? cv::imshow( "Example 2-4", frame );? //顯示當(dāng)前幀
? ? ? 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、調(diào)試
程序運(yùn)行以后,點(diǎn)擊視頻窗口,鍵盤輸入切換為英文小寫,當(dāng)點(diǎn)擊鍵盤r時(shí),視頻自動(dòng)播放,當(dāng)點(diǎn)擊s時(shí)單步播放(點(diǎn)一次s播放1幀)