TLD 詳細解析之 綜合器

下面是自己在看論文和這些大牛的分析過程中,對代碼進行了一些理解,但是由於自己接觸圖像處理和機器視覺沒多久,另外由於自己編程能力比較弱,所以分析過程可能會有不少的錯誤,希望各位不吝指正。而且,因爲編程很多地方不懂,所以註釋得非常亂,還海涵。

 

TLD.h

  1. #include <opencv2/opencv.hpp>  
  2. #include <tld_utils.h>  
  3. #include <LKTracker.h>  
  4. #include <FerNNClassifier.h>  
  5. #include <fstream>  
  6.   
  7.   
  8. //Bounding Boxes  
  9. struct BoundingBox : public cv::Rect {  
  10.   BoundingBox(){}  
  11.   BoundingBox(cv::Rect r): cv::Rect(r){}   //繼承的話需要初始化基類  
  12. public:  
  13.   float overlap;        //Overlap with current Bounding Box  
  14.   int sidx;             //scale index  
  15. };  
  16.   
  17. //Detection structure  
  18. struct DetStruct {  
  19.     std::vector<int> bb;  
  20.     std::vector<std::vector<int> > patt;  
  21.     std::vector<float> conf1;  
  22.     std::vector<float> conf2;  
  23.     std::vector<std::vector<int> > isin;  
  24.     std::vector<cv::Mat> patch;  
  25.   };  
  26.     
  27. //Temporal structure  
  28. struct TempStruct {  
  29.     std::vector<std::vector<int> > patt;  
  30.     std::vector<float> conf;  
  31.   };  
  32.   
  33. struct OComparator{  //比較兩者重合度  
  34.   OComparator(const std::vector<BoundingBox>& _grid):grid(_grid){}  
  35.   std::vector<BoundingBox> grid;  
  36.   bool operator()(int idx1,int idx2){  
  37.     return grid[idx1].overlap > grid[idx2].overlap;  
  38.   }  
  39. };  
  40.   
  41. struct CComparator{  //比較兩者確信度?  
  42.   CComparator(const std::vector<float>& _conf):conf(_conf){}  
  43.   std::vector<float> conf;  
  44.   bool operator()(int idx1,int idx2){  
  45.     return conf[idx1]> conf[idx2];  
  46.   }  
  47. };  
  48.   
  49.   
  50. class TLD{  
  51. private:  
  52.   cv::PatchGenerator generator;  //PatchGenerator類用來對圖像區域進行仿射變換  
  53.   FerNNClassifier classifier;  
  54.   LKTracker tracker;  
  55.     
  56.   //下面這些參數通過程序開始運行時讀入parameters.yml文件進行初始化  
  57.   ///Parameters  
  58.   int bbox_step;  
  59.   int min_win;  
  60.   int patch_size;  
  61.     
  62.   //initial parameters for positive examples  
  63.   //從第一幀得到的目標的bounding box中(文件讀取或者用戶框定),經過幾何變換得  
  64.   //到 num_closest_init * num_warps_init 個正樣本  
  65.   int num_closest_init;  //最近鄰窗口數 10  
  66.   int num_warps_init;  //幾何變換數目 20  
  67.   int noise_init;  
  68.   float angle_init;  
  69.   float shift_init;  
  70.   float scale_init;  
  71.     
  72.   ////從跟蹤得到的目標的bounding box中,經過幾何變換更新正樣本(添加到在線模型?)  
  73.   //update parameters for positive examples  
  74.   int num_closest_update;  
  75.   int num_warps_update;  
  76.   int noise_update;  
  77.   float angle_update;  
  78.   float shift_update;  
  79.   float scale_update;  
  80.     
  81.   //parameters for negative examples  
  82.   float bad_overlap;  
  83.   float bad_patches;  
  84.     
  85.   ///Variables  
  86. //Integral Images  積分圖像,用以計算2bitBP特徵(類似於haar特徵的計算)  
  87. //Mat最大的優勢跟STL很相似,都是對內存進行動態的管理,不需要之前用戶手動的管理內存  
  88.   cv::Mat iisum;  
  89.   cv::Mat iisqsum;  
  90.   float var;  
  91.     
  92. //Training data  
  93.   //std::pair主要的作用是將兩個數據組合成一個數據,兩個數據可以是同一類型或者不同類型。  
  94.   //pair實質上是一個結構體,其主要的兩個成員變量是first和second,這兩個變量可以直接使用。  
  95.   //在這裏用來表示樣本,first成員爲 features 特徵點數組,second成員爲 labels 樣本類別標籤  
  96.   std::vector<std::pair<std::vector<int>,int> > pX; //positive ferns <features,labels=1>  正樣本  
  97.   std::vector<std::pair<std::vector<int>,int> > nX; // negative ferns <features,labels=0>  負樣本  
  98.   cv::Mat pEx;  //positive NN example    
  99.   std::vector<cv::Mat> nEx; //negative NN examples  
  100.     
  101. //Test data   
  102.   std::vector<std::pair<std::vector<int>,int> > nXT; //negative data to Test  
  103.   std::vector<cv::Mat> nExT; //negative NN examples to Test  
  104.     
  105. //Last frame data  
  106.   BoundingBox lastbox;  
  107.   bool lastvalid;  
  108.   float lastconf;  
  109.     
  110. //Current frame data  
  111.   //Tracker data  
  112.   bool tracked;  
  113.   BoundingBox tbb;  
  114.   bool tvalid;  
  115.   float tconf;  
  116.     
  117.   //Detector data  
  118.   TempStruct tmp;  
  119.   DetStruct dt;  
  120.   std::vector<BoundingBox> dbb;  
  121.   std::vector<bool> dvalid;   //檢測有效性??  
  122.   std::vector<float> dconf;  //檢測確信度??  
  123.   bool detected;  
  124.   
  125.   
  126.   //Bounding Boxes  
  127.   std::vector<BoundingBox> grid;  
  128.   std::vector<cv::Size> scales;  
  129.   std::vector<int> good_boxes; //indexes of bboxes with overlap > 0.6  
  130.   std::vector<int> bad_boxes; //indexes of bboxes with overlap < 0.2  
  131.   BoundingBox bbhull; // hull of good_boxes  //good_boxes 的 殼,也就是窗口的邊框  
  132.   BoundingBox best_box; // maximum overlapping bbox  
  133.   
  134. public:  
  135.   //Constructors  
  136.   TLD();  
  137.   TLD(const cv::FileNode& file);  
  138.   void read(const cv::FileNode& file);  
  139.     
  140.   //Methods  
  141.   void init(const cv::Mat& frame1,const cv::Rect &box, FILE* bb_file);  
  142.   void generatePositiveData(const cv::Mat& frame, int num_warps);  
  143.   void generateNegativeData(const cv::Mat& frame);  
  144.   void processFrame(const cv::Mat& img1,const cv::Mat& img2,std::vector<cv::Point2f>& points1,std::vector<cv::Point2f>& points2,  
  145.       BoundingBox& bbnext,bool& lastboxfound, bool tl,FILE* bb_file);  
  146.   void track(const cv::Mat& img1, const cv::Mat& img2,std::vector<cv::Point2f>& points1,std::vector<cv::Point2f>& points2);  
  147.   void detect(const cv::Mat& frame);  
  148.   void clusterConf(const std::vector<BoundingBox>& dbb,const std::vector<float>& dconf,std::vector<BoundingBox>& cbb,std::vector<float>& cconf);  
  149.   void evaluate();  
  150.   void learn(const cv::Mat& img);  
  151.     
  152.   //Tools  
  153.   void buildGrid(const cv::Mat& img, const cv::Rect& box);  
  154.   float bbOverlap(const BoundingBox& box1,const BoundingBox& box2);  
  155.   void getOverlappingBoxes(const cv::Rect& box1,int num_closest);  
  156.   void getBBHull();  
  157.   void getPattern(const cv::Mat& img, cv::Mat& pattern,cv::Scalar& mean,cv::Scalar& stdev);  
  158.   void bbPoints(std::vector<cv::Point2f>& points, const BoundingBox& bb);  
  159.   void bbPredict(const std::vector<cv::Point2f>& points1,const std::vector<cv::Point2f>& points2,  
  160.       const BoundingBox& bb1,BoundingBox& bb2);  
  161.   double getVar(const BoundingBox& box,const cv::Mat& sum,const cv::Mat& sqsum);  
  162.   bool bbComp(const BoundingBox& bb1,const BoundingBox& bb2);  
  163.   int clusterBB(const std::vector<BoundingBox>& dbb,std::vector<int>& indexes);  
  164. };  


TLD.cpp

  1. /* 
  2.  * TLD.cpp 
  3.  * 
  4.  *  Created on: Jun 9, 2011 
  5.  *      Author: alantrrs 
  6.  */  
  7.   
  8. #include <TLD.h>  
  9. #include <stdio.h>  
  10. using namespace cv;  
  11. using namespace std;  
  12.   
  13.   
  14. TLD::TLD()  
  15. {  
  16. }  
  17. TLD::TLD(const FileNode& file){  
  18.   read(file);  
  19. }  
  20.   
  21. void TLD::read(const FileNode& file){  
  22.   ///Bounding Box Parameters  
  23.   min_win = (int)file["min_win"];  
  24.   ///Genarator Parameters  
  25.   //initial parameters for positive examples  
  26.   patch_size = (int)file["patch_size"];  
  27.   num_closest_init = (int)file["num_closest_init"];  
  28.   num_warps_init = (int)file["num_warps_init"];  
  29.   noise_init = (int)file["noise_init"];  
  30.   angle_init = (float)file["angle_init"];  
  31.   shift_init = (float)file["shift_init"];  
  32.   scale_init = (float)file["scale_init"];  
  33.   //update parameters for positive examples  
  34.   num_closest_update = (int)file["num_closest_update"];  
  35.   num_warps_update = (int)file["num_warps_update"];  
  36.   noise_update = (int)file["noise_update"];  
  37.   angle_update = (float)file["angle_update"];  
  38.   shift_update = (float)file["shift_update"];  
  39.   scale_update = (float)file["scale_update"];  
  40.   //parameters for negative examples  
  41.   bad_overlap = (float)file["overlap"];  
  42.   bad_patches = (int)file["num_patches"];  
  43.   classifier.read(file);  
  44. }  
  45.   
  46. //此函數完成準備工作  
  47. void TLD::init(const Mat& frame1, const Rect& box, FILE* bb_file){  
  48.   //bb_file = fopen("bounding_boxes.txt","w");  
  49.   //Get Bounding Boxes  
  50.   //此函數根據傳入的box(目標邊界框)在傳入的圖像frame1中構建全部的掃描窗口,並計算重疊度  
  51.     buildGrid(frame1, box);  
  52.     printf("Created %d bounding boxes\n",(int)grid.size());  //vector的成員size()用於獲取向量元素的個數  
  53.       
  54.   ///Preparation  
  55.   //allocation  
  56.   //積分圖像,用以計算2bitBP特徵(類似於haar特徵的計算)  
  57.   //Mat的創建,方式有兩種:1.調用create(行,列,類型)2.Mat(行,列,類型(值))。  
  58.   iisum.create(frame1.rows+1, frame1.cols+1, CV_32F);  
  59.   iisqsum.create(frame1.rows+1, frame1.cols+1, CV_64F);  
  60.     
  61.   //Detector data中定義:std::vector<float> dconf;  檢測確信度??  
  62.   //vector 的reserve增加了vector的capacity,但是它的size沒有改變!而resize改變了vector  
  63.   //的capacity同時也增加了它的size!reserve是容器預留空間,但在空間內不真正創建元素對象,  
  64.   //所以在沒有添加新的對象之前,不能引用容器內的元素。  
  65.   //不管是調用resize還是reserve,二者對容器原有的元素都沒有影響。  
  66.   //myVec.reserve( 100 );     // 新元素還沒有構造, 此時不能用[]訪問元素  
  67.   //myVec.resize( 100 );      // 用元素的默認構造函數構造了100個新的元素,可以直接操作新元素  
  68.   dconf.reserve(100);  
  69.   dbb.reserve(100);  
  70.   bbox_step =7;  
  71.     
  72.   //以下在Detector data中定義的容器都給其分配grid.size()大小(這個是一幅圖像中全部的掃描窗口個數)的容量  
  73.   //Detector data中定義TempStruct tmp;    
  74.   //tmp.conf.reserve(grid.size());  
  75.   tmp.conf = vector<float>(grid.size());  
  76.   tmp.patt = vector<vector<int> >(grid.size(), vector<int>(10,0));  
  77.   //tmp.patt.reserve(grid.size());  
  78.   dt.bb.reserve(grid.size());  
  79.   good_boxes.reserve(grid.size());  
  80.   bad_boxes.reserve(grid.size());  
  81.     
  82.   //TLD中定義:cv::Mat pEx;  //positive NN example 大小爲15*15圖像片  
  83.   pEx.create(patch_size, patch_size, CV_64F);  
  84.     
  85.   //Init Generator  
  86.   //TLD中定義:cv::PatchGenerator generator;  //PatchGenerator類用來對圖像區域進行仿射變換  
  87.   /* 
  88.   cv::PatchGenerator::PatchGenerator (     
  89.       double     _backgroundMin, 
  90.       double     _backgroundMax, 
  91.       double     _noiseRange, 
  92.       bool     _randomBlur = true, 
  93.       double     _lambdaMin = 0.6, 
  94.       double     _lambdaMax = 1.5, 
  95.       double     _thetaMin = -CV_PI, 
  96.       double     _thetaMax = CV_PI, 
  97.       double     _phiMin = -CV_PI, 
  98.       double     _phiMax = CV_PI  
  99.    )  
  100.    一般的用法是先初始化一個PatchGenerator的實例,然後RNG一個隨機因子,再調用()運算符產生一個變換後的正樣本。 
  101.   */  
  102.   generator = PatchGenerator (0,0,noise_init,true,1-scale_init,1+scale_init,-angle_init*CV_PI/180,  
  103.                                 angle_init*CV_PI/180,-angle_init*CV_PI/180,angle_init*CV_PI/180);  
  104.     
  105.   //此函數根據傳入的box(目標邊界框),在整幀圖像中的全部窗口中尋找與該box距離最小(即最相似,  
  106.   //重疊度最大)的num_closest_init個窗口,然後把這些窗口 歸入good_boxes容器  
  107.   //同時,把重疊度小於0.2的,歸入 bad_boxes 容器  
  108.   //首先根據overlap的比例信息選出重複區域比例大於60%並且前num_closet_init= 10個的最接近box的RectBox,  
  109.   //相當於對RectBox進行篩選。並通過BBhull函數得到這些RectBox的最大邊界。  
  110.   getOverlappingBoxes(box, num_closest_init);  
  111.   printf("Found %d good boxes, %d bad boxes\n",(int)good_boxes.size(),(int)bad_boxes.size());  
  112.   printf("Best Box: %d %d %d %d\n",best_box.x, best_box.y, best_box.width, best_box.height);  
  113.   printf("Bounding box hull: %d %d %d %d\n", bbhull.x, bbhull.y, bbhull.width, bbhull.height);  
  114.     
  115.   //Correct Bounding Box  
  116.   lastbox=best_box;  
  117.   lastconf=1;  
  118.   lastvalid=true;  
  119.   //Print  
  120.   fprintf(bb_file,"%d,%d,%d,%d,%f\n",lastbox.x,lastbox.y,lastbox.br().x,lastbox.br().y,lastconf);  
  121.     
  122.   //Prepare Classifier 準備分類器  
  123.   //scales容器裏是所有掃描窗口的尺度,由buildGrid()函數初始化  
  124.   classifier.prepare(scales);  
  125.     
  126.   ///Generate Data  
  127.   // Generate positive data  
  128.   generatePositiveData(frame1, num_warps_init);  
  129.     
  130.   // Set variance threshold  
  131.   Scalar stdev, mean;  
  132.   //統計best_box的均值和標準差  
  133.   ////例如需要提取圖像A的某個ROI(感興趣區域,由矩形框)的話,用Mat類的B=img(ROI)即可提取  
  134.   //frame1(best_box)就表示在frame1中提取best_box區域(目標區域)的圖像片  
  135.   meanStdDev(frame1(best_box), mean, stdev);  
  136.     
  137.   //利用積分圖像去計算每個待檢測窗口的方差  
  138.   //cvIntegral( const CvArr* image, CvArr* sum, CvArr* sqsum=NULL, CvArr* tilted_sum=NULL );  
  139.   //計算積分圖像,輸入圖像,sum積分圖像, W+1×H+1,sqsum對象素值平方的積分圖像,tilted_sum旋轉45度的積分圖像  
  140.   //利用積分圖像,可以計算在某象素的上-右方的或者旋轉的矩形區域中進行求和、求均值以及標準方差的計算,  
  141.   //並且保證運算的複雜度爲O(1)。    
  142.   integral(frame1, iisum, iisqsum);  
  143.   //級聯分類器模塊一:方差檢測模塊,利用積分圖計算每個待檢測窗口的方差,方差大於var閾值(目標patch方差的50%)的,  
  144.   //則認爲其含有前景目標方差;var 爲標準差的平方  
  145.   var = pow(stdev.val[0],2) * 0.5; //getVar(best_box,iisum,iisqsum);  
  146.   cout << "variance: " << var << endl;  
  147.     
  148.   //check variance  
  149.   //getVar函數通過積分圖像計算輸入的best_box的方差  
  150.   double vr =  getVar(best_box, iisum, iisqsum)*0.5;  
  151.   cout << "check variance: " << vr << endl;  
  152.     
  153.   // Generate negative data  
  154.   generateNegativeData(frame1);  
  155.     
  156.   //Split Negative Ferns into Training and Testing sets (they are already shuffled)  
  157.   //將負樣本放進 訓練和測試集  
  158.   int half = (int)nX.size()*0.5f;  
  159.   //vector::assign函數將區間[start, end)中的值賦值給當前的vector.  
  160.   //將一半的負樣本集 作爲 測試集  
  161.   nXT.assign(nX.begin()+half, nX.end());  //nXT; //negative data to Test  
  162.   //然後將剩下的一半作爲訓練集  
  163.   nX.resize(half);  
  164.     
  165.   ///Split Negative NN Examples into Training and Testing sets  
  166.   half = (int)nEx.size()*0.5f;  
  167.   nExT.assign(nEx.begin()+half,nEx.end());  
  168.   nEx.resize(half);  
  169.     
  170.   //Merge Negative Data with Positive Data and shuffle it  
  171.   //將負樣本和正樣本合併,然後打亂  
  172.   vector<pair<vector<int>,int> > ferns_data(nX.size()+pX.size());  
  173.   vector<int> idx = index_shuffle(0, ferns_data.size());  
  174.   int a=0;  
  175.   for (int i=0;i<pX.size();i++){  
  176.       ferns_data[idx[a]] = pX[i];  
  177.       a++;  
  178.   }  
  179.   for (int i=0;i<nX.size();i++){  
  180.       ferns_data[idx[a]] = nX[i];  
  181.       a++;  
  182.   }  
  183.     
  184.   //Data already have been shuffled, just putting it in the same vector  
  185.   vector<cv::Mat> nn_data(nEx.size()+1);  
  186.   nn_data[0] = pEx;  
  187.   for (int i=0;i<nEx.size();i++){  
  188.       nn_data[i+1]= nEx[i];  
  189.   }  
  190.     
  191.   ///Training    
  192.   //訓練 集合分類器(森林) 和 最近鄰分類器   
  193.   classifier.trainF(ferns_data, 2); //bootstrap = 2  
  194.   classifier.trainNN(nn_data);  
  195.     
  196.   ///Threshold Evaluation on testing sets  
  197.   //用樣本在上面得到的 集合分類器(森林) 和 最近鄰分類器 中分類,評價得到最好的閾值  
  198.   classifier.evaluateTh(nXT, nExT);  
  199. }  
  200.   
  201. /* Generate Positive data 
  202.  * Inputs: 
  203.  * - good_boxes (bbP) 
  204.  * - best_box (bbP0) 
  205.  * - frame (im0) 
  206.  * Outputs: 
  207.  * - Positive fern features (pX) 
  208.  * - Positive NN examples (pEx) 
  209.  */  
  210. void TLD::generatePositiveData(const Mat& frame, int num_warps){  
  211.     /* 
  212.     CvScalar定義可存放1—4個數值的數值,常用來存儲像素,其結構體如下: 
  213.     typedef struct CvScalar 
  214.     { 
  215.         double val[4]; 
  216.     }CvScalar; 
  217.     如果使用的圖像是1通道的,則s.val[0]中存儲數據 
  218.     如果使用的圖像是3通道的,則s.val[0],s.val[1],s.val[2]中存儲數據 
  219.     */  
  220.   Scalar mean;   //均值  
  221.   Scalar stdev;   //標準差  
  222.     
  223.   //此函數將frame圖像best_box區域的圖像片歸一化爲均值爲0的15*15大小的patch,存在pEx正樣本中  
  224.   getPattern(frame(best_box), pEx, mean, stdev);  
  225.     
  226.   //Get Fern features on warped patches  
  227.   Mat img;  
  228.   Mat warped;  
  229.   //void GaussianBlur(InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY=0,   
  230.   //                                    int borderType=BORDER_DEFAULT ) ;  
  231.   //功能:對輸入的圖像src進行高斯濾波後用dst輸出。  
  232.   //src和dst當然分別是輸入圖像和輸出圖像。Ksize爲高斯濾波器模板大小,sigmaX和sigmaY分別爲高斯濾  
  233.   //波在橫向和豎向的濾波係數。borderType爲邊緣擴展點插值類型。  
  234.   //用9*9高斯核模糊輸入幀,存入img  去噪??  
  235.   GaussianBlur(frame, img, Size(9,9), 1.5);  
  236.     
  237.   //在img圖像中截取bbhull信息(bbhull是包含了位置和大小的矩形框)的圖像賦給warped  
  238.   //例如需要提取圖像A的某個ROI(感興趣區域,由矩形框)的話,用Mat類的B=img(ROI)即可提取  
  239.   warped = img(bbhull);  
  240.   RNG& rng = theRNG();  //生成一個隨機數  
  241.   Point2f pt(bbhull.x + (bbhull.width-1)*0.5f, bbhull.y+(bbhull.height-1)*0.5f);  //取矩形框中心的座標  int i(2)  
  242.     
  243.   //nstructs樹木(由一個特徵組構建,每組特徵代表圖像塊的不同視圖表示)的個數  
  244.   //fern[nstructs] nstructs棵樹的森林的數組??  
  245.   vector<int> fern(classifier.getNumStructs());  
  246.   pX.clear();  
  247.   Mat patch;  
  248.   
  249.   //pX爲處理後的RectBox最大邊界處理後的像素信息,pEx最近鄰的RectBox的Pattern,bbP0爲最近鄰的RectBox。  
  250.   if (pX.capacity() < num_warps * good_boxes.size())  
  251.     pX.reserve(num_warps * good_boxes.size());  //pX正樣本個數爲 仿射變換個數 * good_box的個數,故需分配至少這麼大的空間  
  252.   int idx;  
  253.   for (int i=0; i< num_warps; i++){  
  254.      if (i>0)  
  255.      //PatchGenerator類用來對圖像區域進行仿射變換,先RNG一個隨機因子,再調用()運算符產生一個變換後的正樣本。  
  256.        generator(frame, pt, warped, bbhull.size(), rng);  
  257.        for (int b=0; b < good_boxes.size(); b++){  
  258.          idx = good_boxes[b];  //good_boxes容器保存的是 grid 的索引  
  259.          patch = img(grid[idx]);  //把img的 grid[idx] 區域(也就是bounding box重疊度高的)這一塊圖像片提取出來  
  260.          //getFeatures函數得到輸入的patch的用於樹的節點,也就是特徵組的特徵fern(13位的二進制代碼)  
  261.          classifier.getFeatures(patch, grid[idx].sidx, fern);  //grid[idx].sidx 對應的尺度索引  
  262.          pX.push_back(make_pair(fern, 1));   //positive ferns <features, labels=1>  正樣本  
  263.      }  
  264.   }  
  265.   printf("Positive examples generated: ferns:%d NN:1\n",(int)pX.size());  
  266. }  
  267.   
  268. //先對最接近box的RectBox區域得到其patch ,然後將像素信息轉換爲Pattern,  
  269. //具體的說就是歸一化RectBox對應的patch的size(放縮至patch_size = 15*15),將2維的矩陣變成一維的向量信息,  
  270. //然後將向量信息均值設爲0,調整爲zero mean and unit variance(ZMUV)  
  271. //Output: resized Zero-Mean patch  
  272. void TLD::getPattern(const Mat& img, Mat& pattern, Scalar& mean, Scalar& stdev){  
  273.   //將img放縮至patch_size = 15*15,存到pattern中  
  274.   resize(img, pattern, Size(patch_size, patch_size));  
  275.     
  276.   //計算pattern這個矩陣的均值和標準差  
  277.   //Computes a mean value and a standard deviation of matrix elements.  
  278.   meanStdDev(pattern, mean, stdev);  
  279.   pattern.convertTo(pattern, CV_32F);  
  280.     
  281.   //opencv中Mat的運算符有重載, Mat可以 + Mat; + Scalar; + int / float / double 都可以  
  282.   //將矩陣所有元素減去其均值,也就是把patch的均值設爲零  
  283.   pattern = pattern - mean.val[0];  
  284. }  
  285.   
  286. /* Inputs: 
  287.  * - Image 
  288.  * - bad_boxes (Boxes far from the bounding box) 
  289.  * - variance (pEx variance) 
  290.  * Outputs 
  291.  * - Negative fern features (nX) 
  292.  * - Negative NN examples (nEx) 
  293.  */  
  294. void TLD::generateNegativeData(const Mat& frame){  
  295.   //由於之前重疊度小於0.2的,都歸入 bad_boxes了,所以數量挺多,下面的函數用於打亂順序,也就是爲了  
  296.   //後面隨機選擇bad_boxes  
  297.   random_shuffle(bad_boxes.begin(), bad_boxes.end());//Random shuffle bad_boxes indexes  
  298.   int idx;  
  299.   //Get Fern Features of the boxes with big variance (calculated using integral images)  
  300.   int a=0;  
  301.   //int num = std::min((int)bad_boxes.size(),(int)bad_patches*100); //limits the size of bad_boxes to try  
  302.   printf("negative data generation started.\n");  
  303.   vector<int> fern(classifier.getNumStructs());  
  304.   nX.reserve(bad_boxes.size());  
  305.   Mat patch;  
  306.   for (int j=0;j<bad_boxes.size();j++){  //把方差較大的bad_boxes加入負樣本  
  307.       idx = bad_boxes[j];  
  308.           if (getVar(grid[idx],iisum,iisqsum)<var*0.5f)  
  309.             continue;  
  310.       patch =  frame(grid[idx]);  
  311.       classifier.getFeatures(patch, grid[idx].sidx, fern);  
  312.       nX.push_back(make_pair(fern, 0)); //得到負樣本  
  313.       a++;  
  314.   }  
  315.   printf("Negative examples generated: ferns: %d ", a);  
  316.     
  317.   //random_shuffle(bad_boxes.begin(),bad_boxes.begin()+bad_patches);//Randomly selects 'bad_patches' and get the patterns for NN;  
  318.   Scalar dum1, dum2;  
  319.   //bad_patches = (int)file["num_patches"]; 在參數文件中 num_patches = 100  
  320.   nEx=vector<Mat>(bad_patches);  
  321.   for (int i=0;i<bad_patches;i++){  
  322.       idx=bad_boxes[i];  
  323.       patch = frame(grid[idx]);  
  324.       //具體的說就是歸一化RectBox對應的patch的size(放縮至patch_size = 15*15)  
  325.       //由於負樣本不需要均值和方差,所以就定義dum,將其捨棄  
  326.       getPattern(patch,nEx[i],dum1,dum2);  
  327.   }  
  328.   printf("NN: %d\n",(int)nEx.size());  
  329. }  
  330.   
  331. //該函數通過積分圖像計算輸入的box的方差  
  332. double TLD::getVar(const BoundingBox& box, const Mat& sum, const Mat& sqsum){  
  333.   double brs = sum.at<int>(box.y+box.height, box.x+box.width);  
  334.   double bls = sum.at<int>(box.y+box.height, box.x);  
  335.   double trs = sum.at<int>(box.y,box.x + box.width);  
  336.   double tls = sum.at<int>(box.y,box.x);  
  337.   double brsq = sqsum.at<double>(box.y+box.height,box.x+box.width);  
  338.   double blsq = sqsum.at<double>(box.y+box.height,box.x);  
  339.   double trsq = sqsum.at<double>(box.y,box.x+box.width);  
  340.   double tlsq = sqsum.at<double>(box.y,box.x);  
  341.     
  342.   double mean = (brs+tls-trs-bls)/((double)box.area());  
  343.   double sqmean = (brsq+tlsq-trsq-blsq)/((double)box.area());  
  344.   //方差=E(X^2)-(EX)^2   EX表示均值  
  345.   return sqmean-mean*mean;  
  346. }  
  347.   
  348. void TLD::processFrame(const cv::Mat& img1,const cv::Mat& img2,vector<Point2f>& points1,vector<Point2f>& points2,BoundingBox& bbnext, bool& lastboxfound, bool tl, FILE* bb_file){  
  349.   vector<BoundingBox> cbb;  
  350.   vector<float> cconf;  
  351.   int confident_detections=0;  
  352.   int didx; //detection index  
  353.     
  354.   ///Track  跟蹤模塊  
  355.   if(lastboxfound && tl){   //tl: train and learn  
  356.       //跟蹤  
  357.       track(img1, img2, points1, points2);  
  358.   }  
  359.   else{  
  360.       tracked = false;  
  361.   }  
  362.     
  363.   ///Detect   檢測模塊  
  364.   detect(img2);  
  365.     
  366.   ///Integration   綜合模塊  
  367.   //TLD只跟蹤單目標,所以綜合模塊綜合跟蹤器跟蹤到的單個目標和檢測器檢測到的多個目標,然後只輸出保守相似度最大的一個目標  
  368.   if (tracked){  
  369.       bbnext=tbb;  
  370.       lastconf=tconf;   //表示相關相似度的閾值  
  371.       lastvalid=tvalid;  //表示保守相似度的閾值  
  372.       printf("Tracked\n");  
  373.       if(detected){                                               //   if Detected  
  374.           //通過 重疊度 對檢測器檢測到的目標bounding box進行聚類,每個類其重疊度小於0.5  
  375.           clusterConf(dbb, dconf, cbb, cconf);                       //   cluster detections  
  376.           printf("Found %d clusters\n",(int)cbb.size());  
  377.           for (int i=0;i<cbb.size();i++){  
  378.               //找到與跟蹤器跟蹤到的box距離比較遠的類(檢測器檢測到的box),而且它的相關相似度比跟蹤器的要大  
  379.               if (bbOverlap(tbb, cbb[i])<0.5 && cconf[i]>tconf){  //  Get index of a clusters that is far from tracker and are more confident than the tracker  
  380.                   confident_detections++;  //記錄滿足上述條件,也就是可信度比較高的目標box的個數  
  381.                   didx=i; //detection index  
  382.               }  
  383.           }  
  384.           //如果只有一個滿足上述條件的box,那麼就用這個目標box來重新初始化跟蹤器(也就是用檢測器的結果去糾正跟蹤器)  
  385.           if (confident_detections==1){                                //if there is ONE such a cluster, re-initialize the tracker  
  386.               printf("Found a better match..reinitializing tracking\n");  
  387.               bbnext=cbb[didx];  
  388.               lastconf=cconf[didx];  
  389.               lastvalid=false;  
  390.           }  
  391.           else {  
  392.               printf("%d confident cluster was found\n", confident_detections);  
  393.               int cx=0,cy=0,cw=0,ch=0;  
  394.               int close_detections=0;  
  395.               for (int i=0;i<dbb.size();i++){  
  396.                   //找到檢測器檢測到的box與跟蹤器預測到的box距離很近(重疊度大於0.7)的box,對其座標和大小進行累加  
  397.                   if(bbOverlap(tbb,dbb[i])>0.7){                     // Get mean of close detections  
  398.                       cx += dbb[i].x;  
  399.                       cy +=dbb[i].y;  
  400.                       cw += dbb[i].width;  
  401.                       ch += dbb[i].height;  
  402.                       close_detections++;   //記錄最近鄰box的個數  
  403.                       printf("weighted detection: %d %d %d %d\n",dbb[i].x,dbb[i].y,dbb[i].width,dbb[i].height);  
  404.                   }  
  405.               }  
  406.               if (close_detections>0){  
  407.                   //對與跟蹤器預測到的box距離很近的box 和 跟蹤器本身預測到的box 進行座標與大小的平均作爲最終的  
  408.                   //目標bounding box,但是跟蹤器的權值較大  
  409.                   bbnext.x = cvRound((float)(10*tbb.x+cx)/(float)(10+close_detections));   // weighted average trackers trajectory with the close detections  
  410.                   bbnext.y = cvRound((float)(10*tbb.y+cy)/(float)(10+close_detections));  
  411.                   bbnext.width = cvRound((float)(10*tbb.width+cw)/(float)(10+close_detections));  
  412.                   bbnext.height =  cvRound((float)(10*tbb.height+ch)/(float)(10+close_detections));  
  413.                   printf("Tracker bb: %d %d %d %d\n",tbb.x,tbb.y,tbb.width,tbb.height);  
  414.                   printf("Average bb: %d %d %d %d\n",bbnext.x,bbnext.y,bbnext.width,bbnext.height);  
  415.                   printf("Weighting %d close detection(s) with tracker..\n",close_detections);  
  416.               }  
  417.               else{  
  418.                 printf("%d close detections were found\n",close_detections);  
  419.   
  420.               }  
  421.           }  
  422.       }  
  423.   }  
  424.   else{                                       //   If NOT tracking  
  425.       printf("Not tracking..\n");  
  426.       lastboxfound = false;  
  427.       lastvalid = false;  
  428.       //如果跟蹤器沒有跟蹤到目標,但是檢測器檢測到了一些可能的目標box,那麼同樣對其進行聚類,但只是簡單的  
  429.       //將聚類的cbb[0]作爲新的跟蹤目標box(不比較相似度了??還是裏面已經排好序了??),重新初始化跟蹤器  
  430.       if(detected){                           //  and detector is defined  
  431.           clusterConf(dbb,dconf,cbb,cconf);   //  cluster detections  
  432.           printf("Found %d clusters\n",(int)cbb.size());  
  433.           if (cconf.size()==1){  
  434.               bbnext=cbb[0];  
  435.               lastconf=cconf[0];  
  436.               printf("Confident detection..reinitializing tracker\n");  
  437.               lastboxfound = true;  
  438.           }  
  439.       }  
  440.   }  
  441.   lastbox=bbnext;  
  442.   if (lastboxfound)  
  443.     fprintf(bb_file,"%d,%d,%d,%d,%f\n",lastbox.x,lastbox.y,lastbox.br().x,lastbox.br().y,lastconf);  
  444.   else  
  445.     fprintf(bb_file,"NaN,NaN,NaN,NaN,NaN\n");  
  446.       
  447.   ///learn 學習模塊  
  448.   if (lastvalid && tl)  
  449.     learn(img2);  
  450. }  
  451.   
  452. /*Inputs: 
  453. * -current frame(img2), last frame(img1), last Bbox(bbox_f[0]). 
  454. *Outputs: 
  455. *- Confidence(tconf), Predicted bounding box(tbb), Validity(tvalid), points2 (for display purposes only) 
  456. */  
  457. void TLD::track(const Mat& img1, const Mat& img2, vector<Point2f>& points1, vector<Point2f>& points2){  
  458.     
  459.   //Generate points  
  460.   //網格均勻撒點(均勻採樣),在lastbox中共產生最多10*10=100個特徵點,存於points1  
  461.   bbPoints(points1, lastbox);  
  462.   if (points1.size()<1){  
  463.       printf("BB= %d %d %d %d, Points not generated\n",lastbox.x,lastbox.y,lastbox.width,lastbox.height);  
  464.       tvalid=false;  
  465.       tracked=false;  
  466.       return;  
  467.   }  
  468.   vector<Point2f> points = points1;  
  469.     
  470.   //Frame-to-frame tracking with forward-backward error cheking  
  471.   //trackf2f函數完成:跟蹤、計算FB error和匹配相似度sim,然後篩選出 FB_error[i] <= median(FB_error) 和   
  472.   //sim_error[i] > median(sim_error) 的特徵點(跟蹤結果不好的特徵點),剩下的是不到50%的特徵點  
  473.   tracked = tracker.trackf2f(img1, img2, points, points2);  
  474.   if (tracked){  
  475.       //Bounding box prediction  
  476.       //利用剩下的這不到一半的跟蹤點輸入來預測bounding box在當前幀的位置和大小 tbb  
  477.       bbPredict(points, points2, lastbox, tbb);  
  478.       //跟蹤失敗檢測:如果FB error的中值大於10個像素(經驗值),或者預測到的當前box的位置移出圖像,則  
  479.       //認爲跟蹤錯誤,此時不返回bounding box;Rect::br()返回的是右下角的座標  
  480.       //getFB()返回的是FB error的中值  
  481.       if (tracker.getFB()>10 || tbb.x>img2.cols ||  tbb.y>img2.rows || tbb.br().x < 1 || tbb.br().y <1){  
  482.           tvalid =false//too unstable prediction or bounding box out of image  
  483.           tracked = false;  
  484.           printf("Too unstable predictions FB error=%f\n", tracker.getFB());  
  485.           return;  
  486.       }  
  487.         
  488.       //Estimate Confidence and Validity  
  489.       //評估跟蹤確信度和有效性  
  490.       Mat pattern;  
  491.       Scalar mean, stdev;  
  492.       BoundingBox bb;  
  493.       bb.x = max(tbb.x,0);  
  494.       bb.y = max(tbb.y,0);  
  495.       bb.width = min(min(img2.cols-tbb.x,tbb.width), min(tbb.width, tbb.br().x));  
  496.       bb.height = min(min(img2.rows-tbb.y,tbb.height),min(tbb.height,tbb.br().y));  
  497.       //歸一化img2(bb)對應的patch的size(放縮至patch_size = 15*15),存入pattern  
  498.       getPattern(img2(bb),pattern,mean,stdev);  
  499.       vector<int> isin;  
  500.       float dummy;  
  501.       //計算圖像片pattern到在線模型M的保守相似度  
  502.       classifier.NNConf(pattern,isin,dummy,tconf); //Conservative Similarity  
  503.       tvalid = lastvalid;  
  504.       //保守相似度大於閾值,則評估跟蹤有效  
  505.       if (tconf>classifier.thr_nn_valid){  
  506.           tvalid =true;  
  507.       }  
  508.   }  
  509.   else  
  510.     printf("No points tracked\n");  
  511.   
  512. }  
  513.   
  514. //網格均勻撒點,box共10*10=100個特徵點  
  515. void TLD::bbPoints(vector<cv::Point2f>& points, const BoundingBox& bb){  
  516.   int max_pts=10;  
  517.   int margin_h=0; //採樣邊界  
  518.   int margin_v=0;  
  519.   //網格均勻撒點  
  520.   int stepx = ceil((bb.width-2*margin_h)/max_pts);  //ceil返回大於或者等於指定表達式的最小整數  
  521.   int stepy = ceil((bb.height-2*margin_v)/max_pts);  
  522.   //網格均勻撒點,box共10*10=100個特徵點  
  523.   for (int y=bb.y+margin_v; y<bb.y+bb.height-margin_v; y+=stepy){  
  524.       for (int x=bb.x+margin_h;x<bb.x+bb.width-margin_h;x+=stepx){  
  525.           points.push_back(Point2f(x,y));  
  526.       }  
  527.   }  
  528. }  
  529.   
  530. //利用剩下的這不到一半的跟蹤點輸入來預測bounding box在當前幀的位置和大小  
  531. void TLD::bbPredict(const vector<cv::Point2f>& points1,const vector<cv::Point2f>& points2,  
  532.                     const BoundingBox& bb1,BoundingBox& bb2)    {  
  533.   int npoints = (int)points1.size();  
  534.   vector<float> xoff(npoints);  //位移  
  535.   vector<float> yoff(npoints);  
  536.   printf("tracked points : %d\n", npoints);  
  537.   for (int i=0;i<npoints;i++){   //計算每個特徵點在兩幀之間的位移  
  538.       xoff[i]=points2[i].x - points1[i].x;  
  539.       yoff[i]=points2[i].y - points1[i].y;  
  540.   }  
  541.   float dx = median(xoff);   //計算位移的中值  
  542.   float dy = median(yoff);  
  543.   float s;  
  544.   //計算bounding box尺度scale的變化:通過計算 當前特徵點相互間的距離 與 先前(上一幀)特徵點相互間的距離 的  
  545.   //比值,以比值的中值作爲尺度的變化因子  
  546.   if (npoints>1){  
  547.       vector<float> d;  
  548.       d.reserve(npoints*(npoints-1)/2);  //等差數列求和:1+2+...+(npoints-1)  
  549.       for (int i=0;i<npoints;i++){  
  550.           for (int j=i+1;j<npoints;j++){  
  551.           //計算 當前特徵點相互間的距離 與 先前(上一幀)特徵點相互間的距離 的比值(位移用絕對值)  
  552.               d.push_back(norm(points2[i]-points2[j])/norm(points1[i]-points1[j]));  
  553.           }  
  554.       }  
  555.       s = median(d);  
  556.   }  
  557.   else {  
  558.       s = 1.0;  
  559.   }  
  560.   
  561.   float s1 = 0.5*(s-1)*bb1.width;  
  562.   float s2 = 0.5*(s-1)*bb1.height;  
  563.   printf("s= %f s1= %f s2= %f \n", s, s1, s2);  
  564.     
  565.   //得到當前bounding box的位置與大小信息  
  566.   //當前box的x座標 = 前一幀box的x座標 + 全部特徵點位移的中值(可理解爲box移動近似的位移) - 當前box寬的一半  
  567.   bb2.x = round( bb1.x + dx - s1);  
  568.   bb2.y = round( bb1.y + dy -s2);  
  569.   bb2.width = round(bb1.width*s);  
  570.   bb2.height = round(bb1.height*s);  
  571.   printf("predicted bb: %d %d %d %d\n",bb2.x,bb2.y,bb2.br().x,bb2.br().y);  
  572. }  
  573.   
  574. void TLD::detect(const cv::Mat& frame){  
  575.   //cleaning  
  576.   dbb.clear();  
  577.   dconf.clear();  
  578.   dt.bb.clear();  
  579.   //GetTickCount返回從操作系統啓動到現在所經過的時間  
  580.   double t = (double)getTickCount();  
  581.   Mat img(frame.rows, frame.cols, CV_8U);  
  582.   integral(frame,iisum,iisqsum);   //計算frame的積分圖   
  583.   GaussianBlur(frame,img,Size(9,9),1.5);  //高斯模糊,去噪?  
  584.   int numtrees = classifier.getNumStructs();  
  585.   float fern_th = classifier.getFernTh(); //getFernTh()返回thr_fern; 集合分類器的分類閾值  
  586.   vector <int> ferns(10);  
  587.   float conf;  
  588.   int a=0;  
  589.   Mat patch;  
  590.   //級聯分類器模塊一:方差檢測模塊,利用積分圖計算每個待檢測窗口的方差,方差大於var閾值(目標patch方差的50%)的,  
  591.   //則認爲其含有前景目標  
  592.   for (int i=0; i<grid.size(); i++){  //FIXME: BottleNeck 瓶頸  
  593.       if (getVar(grid[i],iisum,iisqsum) >= var){  //計算每一個掃描窗口的方差  
  594.           a++;  
  595.           //級聯分類器模塊二:集合分類器檢測模塊  
  596.           patch = img(grid[i]);  
  597.           classifier.getFeatures(patch,grid[i].sidx,ferns); //得到該patch特徵(13位的二進制代碼)  
  598.           conf = classifier.measure_forest(ferns);  //計算該特徵值對應的後驗概率累加值  
  599.           tmp.conf[i]=conf;   //Detector data中定義TempStruct tmp;   
  600.           tmp.patt[i]=ferns;  
  601.           //如果集合分類器的後驗概率的平均值大於閾值fern_th(由訓練得到),就認爲含有前景目標  
  602.           if (conf > numtrees*fern_th){    
  603.               dt.bb.push_back(i);  //將通過以上兩個檢測模塊的掃描窗口記錄在detect structure中  
  604.           }  
  605.       }  
  606.       else  
  607.         tmp.conf[i]=0.0;  
  608.   }  
  609.   int detections = dt.bb.size();  
  610.   printf("%d Bounding boxes passed the variance filter\n",a);  
  611.   printf("%d Initial detection from Fern Classifier\n", detections);  
  612.     
  613.   //如果通過以上兩個檢測模塊的掃描窗口數大於100個,則只取後驗概率大的前100個  
  614.   if (detections>100){   //CComparator(tmp.conf)指定比較方式???  
  615.       nth_element(dt.bb.begin(), dt.bb.begin()+100, dt.bb.end(), CComparator(tmp.conf));  
  616.       dt.bb.resize(100);  
  617.       detections=100;  
  618.   }  
  619. //  for (int i=0;i<detections;i++){  
  620. //        drawBox(img,grid[dt.bb[i]]);  
  621. //    }  
  622. //  imshow("detections",img);  
  623.   if (detections==0){  
  624.         detected=false;  
  625.         return;  
  626.       }  
  627.   printf("Fern detector made %d detections ",detections);  
  628.     
  629.   //兩次使用getTickCount(),然後再除以getTickFrequency(),計算出來的是以秒s爲單位的時間(opencv 2.0 以前是ms)  
  630.   t=(double)getTickCount()-t;    
  631.   printf("in %gms\n", t*1000/getTickFrequency());  //打印以上代碼運行使用的毫秒數  
  632.     
  633.   //  Initialize detection structure  
  634.   dt.patt = vector<vector<int> >(detections,vector<int>(10,0));        //  Corresponding codes of the Ensemble Classifier  
  635.   dt.conf1 = vector<float>(detections);                                //  Relative Similarity (for final nearest neighbour classifier)  
  636.   dt.conf2 =vector<float>(detections);                                 //  Conservative Similarity (for integration with tracker)  
  637.   dt.isin = vector<vector<int> >(detections,vector<int>(3,-1));        //  Detected (isin=1) or rejected (isin=0) by nearest neighbour classifier  
  638.   dt.patch = vector<Mat>(detections,Mat(patch_size,patch_size,CV_32F));//  Corresponding patches  
  639.   int idx;  
  640.   Scalar mean, stdev;  
  641.   float nn_th = classifier.getNNTh();  
  642.   //級聯分類器模塊三:最近鄰分類器檢測模塊  
  643.   for (int i=0;i<detections;i++){                                         //  for every remaining detection  
  644.       idx=dt.bb[i];                                                       //  Get the detected bounding box index  
  645.       patch = frame(grid[idx]);  
  646.       getPattern(patch,dt.patch[i],mean,stdev);                //  Get pattern within bounding box  
  647.       //計算圖像片pattern到在線模型M的相關相似度和保守相似度  
  648.       classifier.NNConf(dt.patch[i],dt.isin[i],dt.conf1[i],dt.conf2[i]);  //  Evaluate nearest neighbour classifier  
  649.       dt.patt[i]=tmp.patt[idx];  
  650.       //printf("Testing feature %d, conf:%f isin:(%d|%d|%d)\n",i,dt.conf1[i],dt.isin[i][0],dt.isin[i][1],dt.isin[i][2]);  
  651.       //相關相似度大於閾值,則認爲含有前景目標  
  652.       if (dt.conf1[i]>nn_th){                                               //  idx = dt.conf1 > tld.model.thr_nn; % get all indexes that made it through the nearest neighbour  
  653.           dbb.push_back(grid[idx]);                                         //  BB    = dt.bb(:,idx); % bounding boxes  
  654.           dconf.push_back(dt.conf2[i]);                                     //  Conf  = dt.conf2(:,idx); % conservative confidences  
  655.       }  
  656.   }  
  657.   //打印檢測到的可能存在目標的掃描窗口數(可以通過三個級聯檢測器的)  
  658.   if (dbb.size()>0){  
  659.       printf("Found %d NN matches\n",(int)dbb.size());  
  660.       detected=true;  
  661.   }  
  662.   else{  
  663.       printf("No NN matches found.\n");  
  664.       detected=false;  
  665.   }  
  666. }  
  667.   
  668. //作者已經用python腳本../datasets/evaluate_vis.py來完成算法評估功能,具體見README  
  669. void TLD::evaluate(){  
  670. }  
  671.   
  672. void TLD::learn(const Mat& img){  
  673.   printf("[Learning] ");  
  674.     
  675.   ///Check consistency  
  676.   //檢測一致性  
  677.   BoundingBox bb;  
  678.   bb.x = max(lastbox.x,0);  
  679.   bb.y = max(lastbox.y,0);  
  680.   bb.width = min(min(img.cols-lastbox.x,lastbox.width),min(lastbox.width,lastbox.br().x));  
  681.   bb.height = min(min(img.rows-lastbox.y,lastbox.height),min(lastbox.height,lastbox.br().y));  
  682.   Scalar mean, stdev;  
  683.   Mat pattern;  
  684.   //歸一化img(bb)對應的patch的size(放縮至patch_size = 15*15),存入pattern  
  685.   getPattern(img(bb), pattern, mean, stdev);  
  686.   vector<int> isin;  
  687.   float dummy, conf;  
  688.   //計算輸入圖像片(跟蹤器的目標box)與在線模型之間的相關相似度conf  
  689.   classifier.NNConf(pattern,isin,conf,dummy);  
  690.   if (conf<0.5) {   //如果相似度太小了,就不訓練  
  691.       printf("Fast change..not training\n");  
  692.       lastvalid =false;  
  693.       return;  
  694.   }  
  695.   if (pow(stdev.val[0], 2)< var){  //如果方差太小了,也不訓練  
  696.       printf("Low variance..not training\n");  
  697.       lastvalid=false;  
  698.       return;  
  699.   }  
  700.   if(isin[2]==1){   //如果被被識別爲負樣本,也不訓練  
  701.       printf("Patch in negative data..not traing");  
  702.       lastvalid=false;  
  703.       return;  
  704.   }  
  705.     
  706.   /// Data generation  樣本產生  
  707.   for (int i=0;i<grid.size();i++){   //計算所有的掃描窗口與目標box的重疊度  
  708.       grid[i].overlap = bbOverlap(lastbox, grid[i]);  
  709.   }  
  710.   //集合分類器  
  711.   vector<pair<vector<int>,int> > fern_examples;  
  712.   good_boxes.clear();    
  713.   bad_boxes.clear();  
  714.   //此函數根據傳入的lastbox,在整幀圖像中的全部窗口中尋找與該lastbox距離最小(即最相似,  
  715.   //重疊度最大)的num_closest_update個窗口,然後把這些窗口 歸入good_boxes容器(只是把網格數組的索引存入)  
  716.   //同時,把重疊度小於0.2的,歸入 bad_boxes 容器  
  717.   getOverlappingBoxes(lastbox, num_closest_update);  
  718.   if (good_boxes.size()>0)  
  719.     generatePositiveData(img, num_warps_update);  //用仿射模型產生正樣本(類似於第一幀的方法,但只產生10*10=100個)  
  720.   else{  
  721.     lastvalid = false;  
  722.     printf("No good boxes..Not training");  
  723.     return;  
  724.   }  
  725.   fern_examples.reserve(pX.size() + bad_boxes.size());  
  726.   fern_examples.assign(pX.begin(), pX.end());  
  727.   int idx;  
  728.   for (int i=0;i<bad_boxes.size();i++){  
  729.       idx=bad_boxes[i];  
  730.       if (tmp.conf[idx]>=1){   //加入負樣本,相似度大於1??相似度不是出於0和1之間嗎?  
  731.           fern_examples.push_back(make_pair(tmp.patt[idx],0));  
  732.       }  
  733.   }  
  734.   //最近鄰分類器  
  735.   vector<Mat> nn_examples;  
  736.   nn_examples.reserve(dt.bb.size()+1);  
  737.   nn_examples.push_back(pEx);  
  738.   for (int i=0;i<dt.bb.size();i++){  
  739.       idx = dt.bb[i];  
  740.       if (bbOverlap(lastbox,grid[idx]) < bad_overlap)  
  741.         nn_examples.push_back(dt.patch[i]);  
  742.   }  
  743.     
  744.   /// Classifiers update  分類器訓練  
  745.   classifier.trainF(fern_examples,2);  
  746.   classifier.trainNN(nn_examples);  
  747.   classifier.show(); //把正樣本庫(在線模型)包含的所有正樣本顯示在窗口上  
  748. }  
  749.   
  750. //檢測器採用掃描窗口的策略  
  751. //此函數根據傳入的box(目標邊界框)在傳入的圖像中構建全部的掃描窗口,並計算每個窗口與box的重疊度  
  752. void TLD::buildGrid(const cv::Mat& img, const cv::Rect& box){  
  753.   const float SHIFT = 0.1;  //掃描窗口步長爲 寬高的 10%  
  754.   //尺度縮放係數爲1.2 (0.16151*1.2=0.19381),共21種尺度變換  
  755.   const float SCALES[] = {0.16151,0.19381,0.23257,0.27908,0.33490,0.40188,0.48225,  
  756.                           0.57870,0.69444,0.83333,1,1.20000,1.44000,1.72800,  
  757.                           2.07360,2.48832,2.98598,3.58318,4.29982,5.15978,6.19174};  
  758.   int width, height, min_bb_side;  
  759.   //Rect bbox;  
  760.   BoundingBox bbox;  
  761.   Size scale;  
  762.   int sc=0;  
  763.     
  764.   for (int s=0; s < 21; s++){  
  765.     width = round(box.width*SCALES[s]);  
  766.     height = round(box.height*SCALES[s]);  
  767.     min_bb_side = min(height,width);  //bounding box最短的邊  
  768.     //由於圖像片(min_win 爲15x15像素)是在bounding box中採樣得到的,所以box必須比min_win要大  
  769.     //另外,輸入的圖像肯定得比 bounding box 要大了  
  770.     if (min_bb_side < min_win || width > img.cols || height > img.rows)  
  771.       continue;  
  772.     scale.width = width;  
  773.     scale.height = height;  
  774.     //push_back在vector類中作用爲在vector尾部加入一個數據  
  775.     //scales在類TLD中定義:std::vector<cv::Size> scales;  
  776.     scales.push_back(scale);  //把該尺度的窗口存入scales容器,避免在掃描時計算,加快檢測速度  
  777.     for (int y=1; y<img.rows-height; y+=round(SHIFT*min_bb_side)){  //按步長移動窗口  
  778.       for (int x=1; x<img.cols-width; x+=round(SHIFT*min_bb_side)){  
  779.         bbox.x = x;  
  780.         bbox.y = y;  
  781.         bbox.width = width;  
  782.         bbox.height = height;  
  783.         //判斷傳入的bounding box(目標邊界框)與 傳入圖像中的此時窗口的 重疊度,  
  784.         //以此來確定該圖像窗口是否含有目標  
  785.         bbox.overlap = bbOverlap(bbox, BoundingBox(box));  
  786.         bbox.sidx = sc;  //屬於第幾個尺度  
  787.         //grid在類TLD中定義:std::vector<BoundingBox> grid;  
  788.         //把本位置和本尺度的掃描窗口存入grid容器  
  789.         grid.push_back(bbox);  
  790.       }  
  791.     }  
  792.     sc++;  
  793.   }  
  794. }  
  795.   
  796. //此函數計算兩個bounding box 的重疊度  
  797. //重疊度定義爲 兩個box的交集 與 它們的並集 的比  
  798. float TLD::bbOverlap(const BoundingBox& box1, const BoundingBox& box2){  
  799.   //先判斷座標,假如它們都沒有重疊的地方,就直接返回0  
  800.   if (box1.x > box2.x + box2.width) { return 0.0; }  
  801.   if (box1.y > box2.y + box2.height) { return 0.0; }  
  802.   if (box1.x + box1.width < box2.x) { return 0.0; }  
  803.   if (box1.y + box1.height < box2.y) { return 0.0; }  
  804.   
  805.   float colInt =  min(box1.x + box1.width, box2.x + box2.width) - max(box1.x, box2.x);  
  806.   float rowInt =  min(box1.y + box1.height, box2.y + box2.height) - max(box1.y, box2.y);  
  807.   
  808.   float intersection = colInt * rowInt;  
  809.   float area1 = box1.width * box1.height;  
  810.   float area2 = box2.width * box2.height;  
  811.   return intersection / (area1 + area2 - intersection);  
  812. }  
  813.   
  814. //此函數根據傳入的box1(目標邊界框),在整幀圖像中的全部窗口中尋找與該box1距離最小(即最相似,  
  815. //重疊度最大)的num_closest個窗口,然後把這些窗口 歸入good_boxes容器(只是把網格數組的索引存入)  
  816. //同時,把重疊度小於0.2的,歸入 bad_boxes 容器  
  817. void TLD::getOverlappingBoxes(const cv::Rect& box1,int num_closest){  
  818.   float max_overlap = 0;  
  819.   for (int i=0;i<grid.size();i++){  
  820.       if (grid[i].overlap > max_overlap) {  //找出重疊度最大的box  
  821.           max_overlap = grid[i].overlap;  
  822.           best_box = grid[i];         
  823.       }  
  824.       if (grid[i].overlap > 0.6){   //重疊度大於0.6的,歸入 good_boxes  
  825.           good_boxes.push_back(i);  
  826.       }  
  827.       else if (grid[i].overlap < bad_overlap){  //重疊度小於0.2的,歸入 bad_boxes  
  828.           bad_boxes.push_back(i);  
  829.       }  
  830.   }  
  831.   //Get the best num_closest (10) boxes and puts them in good_boxes  
  832.   if (good_boxes.size()>num_closest){  
  833.   //STL中的nth_element()方法找出一個數列中排名第n(下面爲第num_closest)的那個數。這個函數運行後  
  834.   //在good_boxes[num_closest]前面num_closest個數都比他大,也就是找到最好的num_closest個box了  
  835.     std::nth_element(good_boxes.begin(), good_boxes.begin() + num_closest, good_boxes.end(), OComparator(grid));  
  836.     //重新壓縮good_boxes爲num_closest大小  
  837.     good_boxes.resize(num_closest);  
  838.   }  
  839.   //獲取good_boxes 的 Hull殼,也就是窗口的邊框  
  840.   getBBHull();  
  841. }  
  842.   
  843. //此函數獲取good_boxes 的 Hull殼,也就是窗口(圖像)的邊框 bounding box  
  844. void TLD::getBBHull(){  
  845.   int x1=INT_MAX, x2=0;  //INT_MAX 最大的整形數  
  846.   int y1=INT_MAX, y2=0;  
  847.   int idx;  
  848.   for (int i=0;i<good_boxes.size();i++){  
  849.       idx= good_boxes[i];  
  850.       x1=min(grid[idx].x,x1);   //防止出現負數??  
  851.       y1=min(grid[idx].y,y1);  
  852.       x2=max(grid[idx].x + grid[idx].width,x2);  
  853.       y2=max(grid[idx].y + grid[idx].height,y2);  
  854.   }  
  855.   bbhull.x = x1;  
  856.   bbhull.y = y1;  
  857.   bbhull.width = x2-x1;  
  858.   bbhull.height = y2 -y1;  
  859. }  
  860.   
  861. //如果兩個box的重疊度小於0.5,返回false,否則返回true  
  862. bool bbcomp(const BoundingBox& b1,const BoundingBox& b2){  
  863.   TLD t;  
  864.     if (t.bbOverlap(b1,b2)<0.5)  
  865.       return false;  
  866.     else  
  867.       return true;  
  868. }  
  869.   
  870. int TLD::clusterBB(const vector<BoundingBox>& dbb,vector<int>& indexes){  
  871.   //FIXME: Conditional jump or move depends on uninitialised value(s)  
  872.   const int c = dbb.size();  
  873.   //1. Build proximity matrix  
  874.   Mat D(c,c,CV_32F);  
  875.   float d;  
  876.   for (int i=0;i<c;i++){  
  877.       for (int j=i+1;j<c;j++){  
  878.         d = 1-bbOverlap(dbb[i],dbb[j]);  
  879.         D.at<float>(i,j) = d;  
  880.         D.at<float>(j,i) = d;  
  881.       }  
  882.   }  
  883.   //2. Initialize disjoint clustering  
  884.  float L[c-1]; //Level  
  885.  int nodes[c-1][2];  
  886.  int belongs[c];  
  887.  int m=c;  
  888.  for (int i=0;i<c;i++){  
  889.     belongs[i]=i;  
  890.  }  
  891.  for (int it=0;it<c-1;it++){  
  892.  //3. Find nearest neighbor  
  893.      float min_d = 1;  
  894.      int node_a, node_b;  
  895.      for (int i=0;i<D.rows;i++){  
  896.          for (int j=i+1;j<D.cols;j++){  
  897.              if (D.at<float>(i,j)<min_d && belongs[i]!=belongs[j]){  
  898.                  min_d = D.at<float>(i,j);  
  899.                  node_a = i;  
  900.                  node_b = j;  
  901.              }  
  902.          }  
  903.      }  
  904.      if (min_d>0.5){  
  905.          int max_idx =0;  
  906.          bool visited;  
  907.          for (int j=0;j<c;j++){  
  908.              visited = false;  
  909.              for(int i=0;i<2*c-1;i++){  
  910.                  if (belongs[j]==i){  
  911.                      indexes[j]=max_idx;  
  912.                      visited = true;  
  913.                  }  
  914.              }  
  915.              if (visited)  
  916.                max_idx++;  
  917.          }  
  918.          return max_idx;  
  919.      }  
  920.   
  921.  //4. Merge clusters and assign level  
  922.      L[m]=min_d;  
  923.      nodes[it][0] = belongs[node_a];  
  924.      nodes[it][1] = belongs[node_b];  
  925.      for (int k=0;k<c;k++){  
  926.          if (belongs[k]==belongs[node_a] || belongs[k]==belongs[node_b])  
  927.            belongs[k]=m;  
  928.      }  
  929.      m++;  
  930.  }  
  931.  return 1;  
  932.   
  933. }  
  934.   
  935. //對檢測器檢測到的目標bounding box進行聚類  
  936. //聚類(Cluster)分析是由若干模式(Pattern)組成的,通常,模式是一個度量(Measurement)的向量,或者是多維空間中的  
  937. //一個點。聚類分析以相似性爲基礎,在一個聚類中的模式之間比不在同一聚類中的模式之間具有更多的相似性。  
  938. void TLD::clusterConf(const vector<BoundingBox>& dbb,const vector<float>& dconf,vector<BoundingBox>& cbb,vector<float>& cconf){  
  939.   int numbb =dbb.size();  
  940.   vector<int> T;  
  941.   float space_thr = 0.5;  
  942.   int c=1;    //記錄 聚類的類個數  
  943.   switch (numbb){  //檢測到的含有目標的bounding box個數  
  944.   case 1:  
  945.     cbb=vector<BoundingBox>(1,dbb[0]);  //如果只檢測到一個,那麼這個就是檢測器檢測到的目標  
  946.     cconf=vector<float>(1,dconf[0]);  
  947.     return;  
  948.     break;  
  949.   case 2:  
  950.     T =vector<int>(2,0);  
  951.     //此函數計算兩個bounding box 的重疊度  
  952.     if (1 - bbOverlap(dbb[0],dbb[1]) > space_thr){  //如果只檢測到兩個box,但他們的重疊度小於0.5  
  953.       T[1]=1;  
  954.       c=2;  //重疊度小於0.5的box,屬於不同的類  
  955.     }  
  956.     break;  
  957.   default:  //檢測到的box數目大於2個,則篩選出重疊度大於0.5的  
  958.     T = vector<int>(numbb, 0);  
  959.     //stable_partition()重新排列元素,使得滿足指定條件的元素排在不滿足條件的元素前面。它維持着兩組元素的順序關係。  
  960.     //STL partition就是把一個區間中的元素按照某個條件分成兩類。返回第二類子集的起點  
  961.     //bbcomp()函數判斷兩個box的重疊度小於0.5,返回false,否則返回true (分界點是重疊度:0.5)  
  962.     //partition() 將dbb劃分爲兩個子集,將滿足兩個box的重疊度小於0.5的元素移動到序列的前面,爲一個子集,重疊度大於0.5的,  
  963.     //放在序列後面,爲第二個子集,但兩個子集的大小不知道,返回第二類子集的起點  
  964.     c = partition(dbb, T, (*bbcomp));   //重疊度小於0.5的box,屬於不同的類,所以c是不同的類別個數  
  965.     //c = clusterBB(dbb,T);  
  966.     break;  
  967.   }  
  968.     
  969.   cconf=vector<float>(c);   
  970.   cbb=vector<BoundingBox>(c);  
  971.   printf("Cluster indexes: ");  
  972.   BoundingBox bx;  
  973.   for (int i=0;i<c;i++){   //類別個數  
  974.       float cnf=0;  
  975.       int N=0,mx=0,my=0,mw=0,mh=0;  
  976.       for (int j=0;j<T.size();j++){  //檢測到的bounding box個數  
  977.           if (T[j]==i){   //將聚類爲同一個類別的box的座標和大小進行累加  
  978.               printf("%d ",i);  
  979.               cnf=cnf+dconf[j];  
  980.               mx=mx+dbb[j].x;  
  981.               my=my+dbb[j].y;  
  982.               mw=mw+dbb[j].width;  
  983.               mh=mh+dbb[j].height;  
  984.               N++;  
  985.           }  
  986.       }  
  987.       if (N>0){   //然後求該類的box的座標和大小的平均值,將平均值作爲該類的box的代表  
  988.           cconf[i]=cnf/N;  
  989.           bx.x=cvRound(mx/N);  
  990.           bx.y=cvRound(my/N);  
  991.           bx.width=cvRound(mw/N);  
  992.           bx.height=cvRound(mh/N);  
  993.           cbb[i]=bx;  //返回的是聚類,每一個類都有一個代表的bounding box  
  994.       }  
  995.   }  
  996.   printf("\n");  
  997. }  



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章