看了TLD的視頻,熱血沸騰啊。測試了一下C++版本的,發現速度有點慢,matlab版本的還未測試,不知道速度如何,不過看作者的視頻實時性真他媽夠好的。過段時間研究研究,C++的速度改快一點,不過其涉及的東西甚多,任重而道遠。不過感覺速度快了的話這貨前景非常廣啊。
言歸正轉,opencv cookbook看到最後一章了,傳個用c++類封裝的opencv視頻讀取處理的代碼。
#include "opencv2/opencv.hpp"
using namespace std;
using namespace cv;
class VideoProcessor{
private:
VideoCapture caputure;
//圖像處理函數指針
void (*process)(Mat &,Mat &);
bool callIt;
string WindowNameInput;
string WindowNameOutput;
//延時
int delay;
long fnumber;
//第frameToStop停止
long frameToStop;
//暫停標誌
bool stop;
public:
VideoProcessor() : callIt(true),delay(0),fnumber(0),stop(false),frameToStop(-1){}
//設置圖像處理函數
void setFrameProcess(void (*process)(Mat &,Mat &)){
this->process = process;
}
//打開視頻
bool setInput(string filename){
fnumber = 0;
//若已打開,釋放重新打開
caputure.release ();
return caputure.open (filename);
}
//設置輸入視頻播放窗口
void displayInput(string wn){
WindowNameInput = wn;
namedWindow (WindowNameInput);
}
//設置輸出視頻播放窗口
void displayOutput(string wn){
WindowNameOutput = wn;
namedWindow (WindowNameOutput);
}
//銷燬窗口
void dontDisplay(){
destroyWindow (WindowNameInput);
destroyWindow (WindowNameOutput);
WindowNameInput.clear ();
WindowNameOutput.clear ();
}
//啓動
void run(){
Mat frame;
Mat output;
if(!isOpened())
return;
stop = false;
while(!isStopped()){
//讀取下一幀
if(!readNextFrame(frame))
break;
if(WindowNameInput.length ()!=0)
imshow (WindowNameInput,frame);
//處理該幀
if(callIt){
process(frame,output);
}
else{
output = frame;
}
if(WindowNameOutput.length ()!=0)
imshow (WindowNameOutput,output);
//按鍵暫停,繼續按鍵繼續
if(delay>=0&&waitKey (delay)>=0)
waitKey(0);
//到達指定暫停鍵,退出
if(frameToStop>=0&&getFrameNumber()==frameToStop)
stopIt();
}
}
//暫停鍵置位
void stopIt(){
stop = true;
}
//查詢暫停標誌位
bool isStopped(){
return stop;
}
//返回視頻打開標誌
bool isOpened(){
return caputure.isOpened ();
}
//設置延時
void setDelay(int d){
delay = d;
}
//讀取下一幀
bool readNextFrame(Mat &frame){
return caputure.read (frame);
}
void CallProcess(){
callIt = true;
}
void dontCallProcess(){
callIt = false;
}
//設置停止幀
void stopAtFrameNo(long frame){
frameToStop = frame;
}
// 獲得當前幀的位置
long getFrameNumber(){
long fnumber = static_cast<long>(caputure.get ((CV_CAP_PROP_POS_FRAMES)));
return fnumber;
}
//獲取幀率
double getFrameRate(){
return caputure.get(CV_CAP_PROP_FPS);
}
};
//幀處理函數:canny邊緣檢測
void canny(cv::Mat& img, cv::Mat& out) {
//灰度變換
if (img.channels()==3)
cvtColor(img,out,CV_BGR2GRAY);
// canny算子求邊緣
Canny(out,out,100,200);
//顏色反轉,看起來更舒服些
threshold(out,out,128,255,cv::THRESH_BINARY_INV);
}
int main(int argc, char *argv[])
{
VideoProcessor processor;
//打開輸入視頻
processor.setInput ("bike.avi");
processor.displayInput ("Current Frame");
processor.displayOutput ("Output Frame");
//設置每一幀的延時
processor.setDelay (1000./processor.getFrameRate ());
//設置幀處理函數,可以任意
processor.setFrameProcess (canny );
processor.run ();
return 0;
}
視頻處理效果貼圖附上一張: