Compressed tracing compressive tracking source code

Source: Internet
Author: User

Compressed tracing compressive tracking source code

Zouxy09@qq.com

Http://blog.csdn.net/zouxy09

 

In the previous blog that introduced paper's perception tracking algorithm "real-time compressive tracking", I said that I would learn its c ++ source code later, but at that time, due to some issues, so I did not read it. Today, I went to my blog and saw a friend comment in this blog post saying that I don't quite understand anything. Then, I felt it was time to fulfill my promise and learn the source code. So I spent just a few hours reading the C ++ source code and made a detailed comment. I hope it will be helpful to you. Thanks to this friend. Of course, because I have just been in touch with this field, I also have many questions that I don't understand or understand, and I am eager for your guidance.

The following is the Engineering website of this algorithm: it contains the above paper, the code of MATLAB and C ++, as well as the test data and demo.

Http://www4.comp.polyu.edu.hk /~ Cslzhang/ct/ct.htm

Previously, I learned the sensor tracking algorithm introduced in "real-time compressive tracking:

Http://blog.csdn.net/zouxy09/article/details/8118360

 

I am very grateful to paper real-time compressive tracking, such as Kaihua, for writing C ++ code and contributing Yang.
Xian.

This C ++ code is very concise, clear, and beautiful. In addition, as prompted by the original author, the comments of the original author in this blog post can be viewed for areas that are not understood in the code comment (where I put a question mark. Thank you very much, Yang.
Xian guidance.

Okay, I don't have to talk about it anymore. The following is the Source Code Annotated by yourself. Because the code writing process is very clear, I will not summarize the process. This project contains three files: compressivetracker. CPP, compressivetracker. H and runtracker. CPP, because runtracker. CPP is similar to run_tld.cpp in TLD algorithms. I will not comment on it here. You can refer to my previous:

TLD (tracking-Learning-detection) learning and source code understanding (4)

Http://blog.csdn.net/zouxy09/article/details/7893032

 

The following is the specific source code:

Compressivetracker. h

/*************************************** * ********************************** File: compressivetracker. H * brief: C ++ demo for paper: Kaihua Zhang, Lei Zhang, Ming-Hsuan Yang, "real-time compressive tracking," eccv 2012. * version: 1.0 * Author: Yang Xian * Email: yang_xian521@163.com * Date: 2012/08/03 * History: * revised by Kaihua Zhang on 14/8/2012 * Email: zhkhua@gmail.com * homepage: http://www4.comp.polyu. Edu.hk /~ Cskhzhang /************************************** * ******************************** // This is a comparison common C/C ++ hybrid injection, you only need to add this note at the beginning of the header file to ensure that the header file is only inserted and compiled once # pragma once # include <opencv2/opencv. HPP> # include <vector> Using STD: vector; using namespace CV; // compute class compressivetracker {public: compressivetracker (void );~ Compressivetracker (void); Private: int featureminnumrect; int featuremaxnumrect; int featurenum; // Number of Harr features of each box (that is, number of weak classifiers) vector <rect> features; vector <vector <float> featuresweight; int routerpositive; // a positive sample vector <rect> samplepositivebox is collected within the range from the target location tracked from the previous frame to the routerpositive; // sample box set vector <rect> samplenegativebox; // The negative sample box set int rsearchwindow; // the size of the scan window, or the size of the check box mat imageintegral; // figure Image integral graph mat samplepositivefeaturevalue; // Harr feature value of the acquired positive sample mat samplenegativefeaturevalue; // Harr feature value of the acquired negative sample // for each sample Z (m-dimensional vector ), its low-dimensional representation is V (n-dimensional vector, where n is far smaller than m ). Assume that the elements in V are independently distributed. // Assume that the conditional probabilities P (Vi | y = 1) and P (Vi | Y = 0) in the classifier H (v) belong to Gaussian distribution, the following four parameters can be used to describe the mean U and variance sigmavector <float> mupositive; vector <float> sigmapositive of Gaussian distribution of positive and negative samples; vector <float> munegative; vector <float> sigmanegative; float learnrate; // learning rate, control the step size of classifier parameter update vector <rect> detectbox; // The boxmat detectfeaturevalue to be detected; RNG; // random number private: void haarfeature (rect & _ objectbox, int _ numfeature); void samplerect (MAT & _ image, rect & _ objectbox, float _ rinner, float _ router, int _ maxsamplenum, vector <rect> & _ samplebox); void samplerect (MAT & _ image, rect & _ objectbox, float _ SRW, vector <rect> & _ samplebox); void getfeaturevalue (MAT & _ imageintegral, vector <rect> & _ samplebox, mat & _ samplefeaturevalue); void classifierupdate (MAT & _ samplefeaturevalue, vector <float> & _ Mu, vector <float> & _ Sigma, float _ learnrate); void radioclassifier (vector <float> & _ mupos, vector <float> & _ sigmapos, vector <float> & _ muneg, vector <float> & _ sigmaneg, mat & _ samplefeaturevalue, float & _ radiomax, Int & _ radiomaxindex); public: void processframe (MAT & _ frame, rect & _ objectbox); void Init (MAT & _ frame, rect & _ objectbox );};

Compressivetracker. cpp

# Include "compressivetracker. H "# include <math. h ># include <iostream> using namespace CV; using namespace STD; // initiate the constructor to initialize the compressivetracker: compressivetracker (void) {featureminnumrect = 2; featuremaxnumrect = 4; // Number of rectangle from 2 to 4 featurenum = 50; // Number of all weaker classifiers, I. e, feature poolrouterpositive = 4; // radical scope of P Ositive samplesrsearchwindow = 25; // size of search windowmupositive = vector <float> (featurenum, 0.0f); munegative = vector <float> (featurenum, 0.0f ); sigmapositive = vector <float> (featurenum, 1.0f); sigmanegative = vector <float> (featurenum, 1.0f); learnrate = 0.85f; // learning rate parameter} compressivetracker ::~ Compressivetracker (void) {}// use the integral graph to calculate the Harr features of each collected sample, this feature is multiplied by featuresweight. // It is equivalent to projection to the random measurement matrix, that is, sparse expression. If you don't understand it here, you can see Figure 2 in the // thesis, which is more intuitive. // Another point: in fact, what we use here is not really a Harr feature. The translation in my blog is incorrect. Here, the calculated is // the gray-scale weighted sum of the different rectangular boxes sampled in the box (when the weight is negative, it is the gray-scale difference) // for convenience of expression, I will describe it using the Harr features below. // Each sample has 50 Harr features, and each Harr feature consists of two to three randomly selected rectangular frames, // The grayscale weighted sum of these rectangular boxes is used as the feature value of this Harr feature. Void compressivetracker: haarfeature (rect & _ objectbox, int _ numfeature)/* Description: Compute Haar features arguments:-_ objectbox: [x y width height] object rectangle-_ numfeature: total number of features. the default is 50. */{// _ numfeature is the number of Harr features of a sample box, 50 in total. As mentioned above, // each Harr feature is composed of two to three randomly selected rectangular boxes (vector <rect> () type. Features = vector <rect> (_ numfeature, vector <rect> (); // The rectangular frame of each reaction feature corresponds to a weight, in fact, it is the corresponding element in the random measurement matrix. It is used to multiply the corresponding feature // to indicate that the feature is perceived based on the weight. In other words, featuresweight is a random measurement matrix. // The assignment of the element of this matrix is shown in the second part of the paper. Or you can also refer to my blog: (Oh, it seems that the blog did not clearly) // http://blog.csdn.net/zouxy09/article/details/8118360featuresWeight = vector <float> (_ numfeature, vector <float> ()); // does numrect indicate the number of rectangular frames for each feature or the number of S in the random measurement matrix described in the paper? Are there two other functions available? // When S is set to 2 or 3, the matrix satisfies Johnson-lindenstrauss's inference. Int numrect; rect recttemp; float weighttemp; For (INT I = 0; I <_ numfeature; I ++) {// how to generate a random number (or sample) that follows a probability distribution). // For example, if you want to get 100 samples from a random variable that follows a normal distribution, the probability of a sample that is close to its mean is much higher, as a result, many samples are concentrated nearby. // RNG. uniform () returns a random number uniformly sampled from the range [1, 2), that is, the random number is evenly distributed within [2, 2) (the probability of different values is the same) // The following function is to obtain a random number in the range of [2, 4), and then use cvfloor to return the maximum integer not greater than the parameter, which is either 2 or 3. Numrect = cvfloor (RNG. uniform (double) featureminnumrect, (double) featuremaxnumrect); // int c = 1; for (Int J = 0; j <numrect; j ++) {// I randomly generate a rectangle box in a box, which has nothing to do with the X and Y coordinates of your box, however, I must ensure that the rectangular box I select will not be beyond the range of your box, right? // But what do I mean by 3 and 2 below? I don't understand. My personal understanding is to avoid this rectangular box being too close to the edge of the box. // it should be at least two pixels away from the edge. I don't know if this is correct. please instruct recttemp. X = cvfloor (RNG. uniform (0.0, (double) (_ objectbox. width-3); recttemp. y = cvfloor (RNG. uniform (0.0, (double) (_ objectbox. height-3); // cvceil returns the recttemp value not less than the minimum integer of the parameter. width = cvceil (RNG. uniform (0.0, (double) (_ objectbox. width-recttemp. x-2); recttemp. height = cvceil (RNG. uniform (0.0, (double) (_ objectbox. height-recttemp. y-2 )));// Save the Feature Template. Note: The rectangle here is relative to the box. It is not for the whole image. features [I]. push_back (recttemp); // weighttemp = (float) Pow (-1.0, c); // POW (-1.0, c) is the power of-1 to C, c randomly takes 0 or 1, that is, weighttemp is random positive or negative. // In the random measurement matrix, the matrix element contains three types: SQRT (s),-SQRT (s), and zero. The probability of positive and negative values is equal. // This is why [2, 4) Even sampling is the same as that of 0 or 1. // But why is one of SQRT (s) points? When is it 0? Isn't the probability of being 0 quite high in the paper? // If there is no zero element, which of the following is sparse expression and compression? Thank you for your guidance! (Of course, another benefit of sparse expression // you only need to save non-zero elements. But is it related to this ?) Weighttemp = (float) Pow (-1.0, cvfloor (RNG. uniform (0.0, 2.0)/SQRT (float (numrect); // Save the weight featuresweight [I] for each Feature Template. push_back (weighttemp) ;}}// collect positive and negative samples around the target box of the last frame to initialize or update the void compressivetracker of the classifier :: samplerect (MAT & _ image, rect & _ objectbox, float _ rinner, float _ router, int _ maxsamplenum, vector <rect> & _ samplebox)/* description: compute the coordinate of positive and negative sample im Age templates arguments:-_ image: processing frame-_ objectbox: Recent object position-_ rinner: inner sampling radius-_ router: outer sampling radius-_ maxsamplenum: maximal number of Sampled images-_ samplebox: storing the rectangle coordinates of the sampled images. */{int rowsz = _ image. rows-_ objectbox. height-1; int colsz = _ image. cols-_ objectbox. width-1; // We Collect positive and negative samples around the target box tracked in the previous frame. The circle is represented by two circles centered on //. the radius of the two circles is _ rinner and _ router. // We Collect positive samples within the range of _ rinner distance from the target box of the last frame, // collect negative samples within a distance greater than _ router (there is an upper bound in the paper, but it seems that // there is no such upper bound. In fact, it seems that there is no need to collect negative samples) float inradsq = _ rinner * _ rinner; float outradsq = _ router * _ router; int Dist; // these four boxes are used to prevent the collected boxes from exceeding the image range, limit the X and Y coordinates of the collected box to int minrow = max (0, (INT) _ objectbox. y-(INT) _ rinner); int maxrow = min (INT) rowsz-1, (INT) _ objectbox. Y + (INT) _ rinner); int mincol = max (0, (INT) _ objectbox. x-(INT) _ rinner); int maxcol = min (INT) colsz-1, (INT) _ objectbox. X + (INT) _ rinner); int I = 0; // the denominator is equivalent to the range X can collect multiplied by the range y can collect, that is, the maximum number of boxes that can be collected, // then _ maxsamplenum (the maximum number of boxes to be collected) must be smaller than or equal to it. // What does this prob do? In the following example, float prob = (float) (_ maxsamplenum)/(maxrow-minrow + 1)/(maxcol-mincol + 1); int R; int C; _ samplebox. clear (); // important rect Rec (0, 0, 0); For (r = minrow; r <= (INT) maxrow; r ++) for (C = mincol; c <= (INT) maxcol; C ++) {// calculate the distance from the generated box to the target box Dist = (_ objectbox. y-R) * (_ objectbox. y-R) + (_ objectbox. x-C) * (_ objectbox. x-C); // The last two conditions are to ensure that the distance must be within the range of _ rinner and _ router. // then RNG. uniform (0 ., 1 .) <prob: Why? // As shown above, if _ maxsamplenum is greater than the maximum number, then prob is greater than 1. // RNG. uniform (0 ., 1 .) <The condition prob can always be met, indicating that the/box generated in this range is required (because I want more, but you cannot give me so much, so you can give it to me ). // If you give too much, I don't need so much, that is, prob <1, then I will randomly skip a few steps. If (RNG. uniform (0 ., 1 .) <prob & Dist <inradsq & Dist> = outradsq) {rec. X = C; Rec. y = r; Rec. width = _ objectbox. width; // is the scale unchanged? So far, the size of the final box has not changed rec. height = _ objectbox. height; _ samplebox. push_back (REC); I ++;} _ samplebox. resize (I);} // This samplerect overload function is used to collect a number of boxes around the target box (distance less than _ SRW) of the last frame to be detected. // Unlike the one above, the one above collects positive and negative samples to update the classifier based on the target detected in this frame. // The above is the fourth step of the algorithm mentioned in the paper. This is the first step. Then the process is almost the same. Void compressivetracker: samplerect (MAT & _ image, rect & _ objectbox, float _ SRW, vector <rect> & _ samplebox) /* Description: Compute the coordinate of samples when detecting the object. */{int rowsz = _ image. rows-_ objectbox. height-1; int colsz = _ image. cols-_ objectbox. width-1; float inradsq = _ SRW * _ SRW; int Dist; int minrow = max (0, (INT) _ objectbox. y-(INT) _ SRW); int maxrow = min (INT) Row Sz-1, (INT) _ objectbox. Y + (INT) _ SRW); int mincol = max (0, (INT) _ objectbox. x-(INT) _ SRW); int maxcol = min (INT) colsz-1, (INT) _ objectbox. X + (INT) _ SRW); int I = 0; int R; int C; rect Rec (0, 0, 0); _ samplebox. clear (); // importantfor (r = minrow; r <= (INT) maxrow; r ++) for (C = mincol; C <= (INT) maxcol; c ++) {Dist = (_ objectbox. y-R) * (_ objectbox. y-R) + (_ objectbox. x-C) * (_ objectbox. x-C); If (Dist <inradsq) {rec. X = C; Rec. y = R; Rec. width = _ objectbox. width; Rec. height = _ objectbox. height; _ samplebox. push_back (REC); I ++;} _ samplebox. resize (I);} // compute the features of samples // calculate the Harr features of each sample collected through the integral graph, this feature is multiplied by featuresweight. // It is equivalent to projection to the random measurement matrix, that is, sparse expression. If you don't understand it here, you can see Figure 2 in the // thesis, which is more intuitive. So what we get here is: The Harr feature after sparse expression of each sample. // Another point: in fact, what we use here is not really a Harr feature. The translation in my blog is incorrect. Here, the weighted sum void compressivetracker: getfeaturevalue (MAT & _ imageintegral, vector <rect> & _ samplebox, mat & _ samplefeaturevalue) {int sampleboxsize = _ samplebox. size (); _ samplefeaturevalue. create (featurenum, sampleboxsize, cv_32f); float tempvalue; int xmin; int xmax; int ymin; int Ymax; For (INT I = 0; I <featurenum; I ++) {for (Int J = 0; j <sampleboxsize; j ++) {tempvalue = 0.0f; For (size_t K = 0; k <Features [I]. size (); k ++) {// The saved Feature Template (rectangular box) in features is relative to the box, // Therefore, the box coordinate must be added to the coordinate xmin = _ samplebox [J] of the entire image. X + features [I] [K]. x; xmax = _ samplebox [J]. X + features [I] [K]. X + features [I] [K]. width; ymin = _ samplebox [J]. Y + features [I] [K]. y; Ymax = _ samplebox [J]. Y + features [I] [K]. Y + features [I] [K]. height; // Through the integral graph to quickly calculate the pixels of a rectangle box and integral graph do not understand, you can see my blog: // http://blog.csdn.net/zouxy09/article/details/7929570/ /Here, tempvalue is the grayscale sum after weighting by the dilution matrix. // Each Harr feature consists of two to three rectangular frames. The gray-scale weighted sum of these rectangular frames // serves as the characteristic value of this Harr feature. Then a sample has 50 Harr features tempvalue + = featuresweight [I] [k] * (_ imageintegral. at <float> (ymin, xmin) + _ imageintegral. at <float> (Ymax, xmax)-_ imageintegral. at <float> (ymin, xmax)-_ imageintegral. at <float> (Ymax, xmin);} _ samplefeaturevalue. at <float> (I, j) = tempvalue ;}}} // update the mean and variance of the Gaussian classifier // the probability distribution of each Harr feature of the sample is described by Gaussian distribution. Gaussian distribution can be characterized by expectation and variance. Then, the logarithm ratio of Gaussian probability distribution of each Harr feature of positive and negative samples is used to construct the Classifier Decision-Making // whether the box belongs to the target or the background. Calculate the expected and standard deviation of the newly acquired positive and negative samples, and use it to update the classifierupdate (MAT & _ samplefeaturevalue, vector <float> & _ Mu, vector <float> & _ Sigma, float _ learnrate) {scalar mutemp; scalar sigmatemp; For (INT I = 0; I <featurenum; I ++) {// calculate the expectation and standard deviation of a Harr feature of a positive or negative sample meanstddev (_ samplefeaturevalue. row (I), mutemp, sigmatemp); // For the formula for updating the model parameters, see the formula 6_sigma [I] = (float) SQRT (_ learnrate * _ Sigma [I] * _ Sigma [I] + (1.0f-_ L Earnrate) * sigmatemp. val [0] * sigmatemp. val [0] + _ learnrate * (1.0f-_ learnrate) * (_ Mu [I]-mutemp. val [0]) * (_ Mu [I]-mutemp. val [0]); // equation 6 in paper_mu [I] = _ Mu [I] * _ learnrate + (1.0f-_ learnrate) * mutemp. val [0]; // equation 6 in paper} // compute the ratio classifier void compressivetracker: radioclassifier (vector <float> & _ mupos, vector <float> & _ sigmapos, vector <float> & _ muneg, vector <float> & _ sigmaneg, Mat & _ samplefeaturevalue, float & _ radiomax, Int & _ radiomaxindex) {float sumradio; // flt_max is the macro definition of the largest floating point number, -flt_max is the smallest floating point number. // This is the _ radiomax =-flt_max used to store the largest classification scores in so many boxes. // This corresponds to the above one, it is the box with the largest classification score. The _ radiomaxindex = 0; float PPOs; float PNEG; int sampleboxnum = _ samplefeaturevalue. cols; For (Int J = 0; j <sampleboxnum; j ++) // the box to be tested after each frame sampling {sumradio = 0.0f; For (INT I = 0; I <featurenum; I ++) // number of features to be matched for each box {// Calculate the probability of each feature. The feature distribution is similar to Gaussian distribution. Therefore, the mean and standard deviation of the feature can be obtained by inputting it into the Gaussian Model, what is the probability of a feature on the basis of positive and negative samples. If the probability of a positive sample is high, // we will say that the sample corresponding to this feature is a positive sample. The mathematical comparison is the subtraction or division. Here we take the logarithm ratio PPOs = exp (_ samplefeaturevalue. at <float> (I, j)-_ mupos [I]) * (_ samplefeaturevalue. at <float> (I, j)-_ mupos [I])/-(2.0f * _ sigmapos [I] * _ sigmapos [I] + 1e-30 )) /(_ sigmapos [I] + 1e-30); PNEG = exp (_ samplefeaturevalue. at <float> (I, j)-_ muneg [I]) * (_ samplefeaturevalue. at <float> (I, j)-_ muneg [I])/-(2.0f * _ sigmaneg [I] * _ sigmaneg [I] + 1e-30 )) /(_ sigmaneg [I] + 1e-30); // equation 4 of Paper: Calculate the classification result and obtain a score. The number is the sum of the results (strong classification?) obtained from 50 features (weak classification) of a sample or box ?). It represents the potential size of the current box feature that belongs to the positive sample (target. Which has the largest score? Naturally, I think you are the target. (Of course, some policies need to be added to a specific application to improve false tracking. For example, if the highest score does not reach a threshold value, there is no target.) sumradio + = Log (PPOs + 1e-30)-log (PNEG + 1e-30 ); // equation 4} If (_ radiomax <sumradio) // obtain the maximum score and the corresponding box index {_ radiomax = sumradio; _ radiomaxindex = J ;}}} // input the first frame and the target box to be tracked (read by the file or selected by the user's mouse) to initialize the void compressivetracker: Init (MAT & _ frame, rect & _ objectbox) {// compute Feature Template // calculate the Harr Feature Template of the box, first having haarfeature (_ objectbox, featurenum ); // compute sample templates // because this is the first frame, the target box is read by the file or selected by the user's mouse box. It is known, // so we can use it around the target box, we collect positive and negative samples to initialize our classifier samplerect (_ frame, _ objectbox, routerpositive, 0, 1000000, samplepositivebox); samplerect (_ frame, _ objectbox, rsearchwindow * 1.5, routerpositive + 4.0, 100, samplenegativebox); // calculate the integral graph to quickly calculate the Harr feature integral (_ frame, imageintegral, cv_32f); // use the integral graph above, calculate the Harr feature getfeaturevalue (imageintegral, samplepositivebox, samplepositivefeaturevalue) of the box of the positive and negative samples we have sampled; getfeaturevalue (imageintegral, samplenegativebox, callback ); // initialize classifierupdate (samplepositivefeaturevalue, mupositive, sigmapositive, learnrate) by using the features of the preceding positive and negative samples; classifierupdate (delimiter, munegative, sigmanegative, learnrate );} // input the box tracked by the previous frame to handle a new void compressivetracker: processframe (MAT & _ frame, rect & _ objectbox) {// predict // collect the box boxes samplerect (_ frame, _ objectbox, rsearchwindow, detectbox) to be detected around the boxbox that is tracked in the previous frame ); // calculate the integral graph of this frame (_ frame, imageintegral, cv_32f); // use the integral graph to calculate the Harr feature getfeaturevalue (imageintegral, detectbox, numeric); int radiomaxindex; float radiomax; // match and classify each of the preceding boxes. radioclassifier (mupositive, sigmapositive, munegative, sigmanegative, reverse, radiomax, radiomaxindex ); // The target with the highest score: box_objectbox = detectbox [radiomaxindex]; // update // The target box that is newly tracked, we collect positive and negative samples to update our classifier samplerect (_ frame, _ objectbox, routerpositive, 0.0, 1000000, samplepositivebox); samplerect (_ frame, _ objectbox, rsearchwindow * 1.5, routerpositive + 4.0, 100, samplenegativebox); // calculate the Harr feature getfeaturevalue (imageintegral, samplepositivebox, samplepositivefeaturevalue) of the box of positive and negative samples from the integral graph above ); getfeaturevalue (imageintegral, neural, natural); // use the features of the preceding positive and negative samples to update our classifierupdate (neural, mupositive, sigmapositive, learnrate); classifierupdate (neural, munegative, sigmanegative, learnrate );}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.