Classification of HOG+SVM objects in OpenCV

Source: Internet
Author: User
Tags sprintf svm

Here to summarize the information they found on the internet, to make a simple framework for your reference.

OpenCV The official SVM code in http://www.opencv.org.cn/opencvdoc/2.3.2/html/doc/tutorials/ml/introduction_to_svm/introduction_to_svm.html

In http://blog.csdn.net/sangni007/article/details/7471222 see a good code, the structure is clear, although the comments are relatively small, but very valuable reference, so I added some comments, look more comfortable. Less nonsense, directly on the code:

[CPP] View plaincopyprint #include "cv.h" #include "highgui.h" #include "stdafx.h" #include <ml.h> #include  
<iostream> #include <fstream> #include <string> #include <vector> using namespace CV;  
  
  
using namespace Std;  
    int main (int argc, char** argv) {vector<string> img_path;//input filename variable vector<int> IMG_CATG;  
    int nline = 0;  
    String buf;  
  
    Ifstream svm_data ("E:/svm_data.txt"); First of all, here is a file list, the training samples of the path of the picture are written in this TXT file, the use of Bat batch file can get this TXT file unsigned long n;  while (Svm_data)//reads the training sample file sequentially in {if (Getline (Svm_data, buf)) {nline  
            ++;  
                 if (nline% 2 = 0)//Here The classification is more interesting, can see that the above svm_data.txt text should be a row is the file path, then the next line is the category of the picture, you may set to 0 or 1, of course, many also do not matter {  
            Img_catg.push_back (Atoi (Buf.c_str ());//atoi converts strings to integers, flags (0,1), note that there must be at least two categories here, otherwise there will be an error} else {Img_path.push_bACK (BUF);//Image Path}}} svm_data.close ();//Close File Cvmat *data_mat, *res_mat; int nimgnum = NLINE/2; Read the number of samples, because it is every other row is the picture path, so to divide by 2////sample matrix, Nimgnum: The horizontal axis is the number of samples, WIDTH * HEIGHT: Sample eigenvector, that is, image size Data_mat = Cvcreatemat (n  Imgnum, 1764, CV_32FC1);  
    Here the second parameter, the column of the Matrix, is determined by the size of the following descriptors, which can be obtained by descriptors.size (), and for different sizes of input training pictures, this value is different Cvsetzero (Data_mat);  
    Type matrix, which stores the type flags of each sample Res_mat = Cvcreatemat (Nimgnum, 1, CV_32FC1);  
  
    Cvsetzero (Res_mat);  
    iplimage* src; iplimage* trainimg=cvcreateimage (Cvsize (64,64), 8, 3)//need to analyze the picture, where the default set picture is 64*64 size, so the above definition of 1764, if you want to change the size of the picture,  
    You can use the debug first to see how much descriptors is, and then set up to run/start hog features for (string::size_type i = 0; I!= img_path.size (); i++)  
            {Src=cvloadimage (Img_path[i].c_str (), 1); if (src = NULL) {cout<< "Can not load" image: "<descriptors;//result array hog->compute (TRAINIMG, Descripto Rs,size (1,1), Size (0,0));  
            Call the calculation function to start computing cout<< "HOG dims:" <<descriptors.size () <<endl;  
            cvmat* Svmtrainmat=cvcreatemat (Descriptors.size (), 1,CV_32FC1);  
            n=0;  
                For (Vector<float>::iterator Iter=descriptors.begin (); Iter!=descriptors.end (); iter++) {  
            Cvmset (data_mat,i,n,*iter);//hog store down n++;  
            }//cout<<svmtrainmat->rows<<endl;  
            Cvmset (Res_mat, I, 0, img_catg[i]); cout<< "End Processing" <&LT;IMG_PATH[I].C_STR () << "" < Img_tst_path; Ifstream img_tst ("e:/svm_test.txt")/input training samples, this is the same, just do not need to markWhat kind of picture does it belong while (IMG_TST) {if (Getline (IMG_TST, buf)) {Img_tst_path.push_  
        Back (BUF);  
  
  
  
    } img_tst.close ();  
    Cvmat *test_hog = Cvcreatemat (1, 1764, CV_32FC1);/note here 1764, same as above Char line[512]; Ofstream predict_txt ("Svm_predict.txt");//Store forecast results in this text for (String::size_type j = 0; J!= img_tst_path.size (); j+  
        +)//loop through all the images to be tested {test = Cvloadimage (Img_tst_path[j].c_str (), 1); if (test = = NULL) {cout<< "Can not load" image: "<descriptors;//result array hog->compute (TRAINIMG, Descriptors,size ( 1,1), Size (0,0));  
        Call the calculation function to start computing cout<< "HOG dims:" <<descriptors.size () <<endl;  
        cvmat* Svmtrainmat=cvcreatemat (1,descriptors.size (), CV_32FC1);  
        n=0;  
                For (Vector<float>::iterator Iter=descriptors.begin (); Iter!=descriptors.end (); iter++) {  
                Cvmset (Svmtrainmat,0,n,*iter);  
            n++; int ret = svm.predict (Svmtrainmat);//Get final detection results, this predict usage see OPENCV document STD::SPRINTF (line, "%s%d\r\n", I  
        Mg_tst_path[j].c_str (), ret);  
    predict_txt<<line;  
  
} predict_txt.close ();  
Cvreleaseimage (&AMP;SRC);  
Cvreleaseimage (&AMP;SAMPLEIMG);  
Cvreleaseimage (&AMP;TST);  
Cvreleaseimage (&AMP;TST_TMP);  
Cvreleasemat (&data_mat);  
  
Cvreleasemat (&res_mat);  
return 0;   }

Among them, about hog function hogdescriptor, see blog http://blog.csdn.net/raocong2010/article/details/6239431

In addition, you need to embed this program into another project, because there is the data type is mat, not cvmat, so I modified the above program, and the picture size is not fixed 64*64, need to set up their own picture size, because too lazy, directly to the modified program to put over:

#include "stdafx.h" #include "cv.h" #include "highgui.h" #include "stdafx.h" #include <ml.h> #include <i  
ostream> #include <fstream> #include <string> #include <vector> using namespace CV;  
  
  
using namespace Std;
	int main (int argc, char** argv) {int imgwidht = 120;
    int imgheight = 120;  
    Vector<string> Img_path;  
    Vector<int> IMG_CATG;  
    int nline = 0;  
    String buf;  
    Ifstream svm_data ("E:/apple/svm_data.txt");  
  
    unsigned long n;  
            while (Svm_data) {if (Getline (Svm_data, buf)) {nline + +;
				if (Nline < 5) {Img_catg.push_back (1);
				Img_path.push_back (BUF);//Image path} else {img_catg.push_back (0); Img_path.push_back (BUF);//Image Path}}} svm_data.close ();//Close File Mat Data_mat, R  
    Es_mat; int nimgnum = nline;            Read the sample number////sample Matrix, Nimgnum: The horizontal axis is the sample number, WIDTH * HEIGHT: The sample eigenvector, namely the image size//data_mat = Mat::zeros (Nimgnum, 129    
    , CV_32FC1);  
  
    Type matrix, which stores the type flags of each sample Res_mat = Mat::zeros (Nimgnum, 1, CV_32FC1);  
    Mat src; Mat trainimg = Mat::zeros (ImgHeight, IMGWIDHT, CV_8UC3);//need to analyze the picture for (String::size_type i = 0; I!= img_path.siz E ();   
  
        i++) {src = Imread (Img_path[i].c_str (), 1);  
         
		cout<< "Processing" <descriptors;//result array hog->compute (trainimg, descriptors, Size (1,1), Size (0,0));
        Call a calculated function to start computing if (i==0) {Data_mat = Mat::zeros (Nimgnum, Descriptors.size (), CV_32FC1); cout<< "HOG dims:" &Lt;<descriptors.size () <<endl;  
        n=0; For (Vector<float>::iterator Iter=descriptors.begin (); Iter!=descriptors.end (); iter++) {data_mat.at&lt  
            ;float> (i,n) = *iter;  
        n++;  
	    }//cout<<svmtrainmat->rows<<endl;  
        Res_mat.at<float> (i, 0) = Img_catg[i];  
    cout<< "End Processing" < Img_tst_path;  
    Ifstream img_tst ("E:/apple/svm_test.txt");  
        while (IMG_TST) {if (Getline (IMG_TST, buf)) {img_tst_path.push_back (BUF);  
  
	} img_tst.close ();
    Mat test;  
    Char line[512];  
    Ofstream predict_txt ("E:/apple/svm_predict.txt"); for (String::size_type j = 0; J!= Img_tst_path.size (); j + +) {test = Imread (Img_tst_path[j].c_str (), 1)       
        //Read the image resize (test, trainimg, Cv::size (Imgwidht,imgheight), 0, 0, inter_cubic);//To be able to detect the same size  Hogdescriptor *hog=new Hogdescriptor (cvsize (imgwidht,imgheight), Cvsize (16,16), Cvsize (8,8), CvSize (8,8), 9); See reference article 1,2 VECTOR&Lt;float>descriptors;//result Array Hog->compute (TRAINIMG, Descriptors,size (1,1), Size (0,0));
        Call the calculation function to start computing cout<< "The detection result:" <<endl;  
        cout<< "HOG dims:" <<descriptors.size () <<endl;  
        Mat Svmtrainmat = Mat::zeros (1,descriptors.size (), CV_32FC1);  
        n=0; For (Vector<float>::iterator Iter=descriptors.begin (); Iter!=descriptors.end (); iter++) {SVMtrainMat.at  
            <float> (0,n) = *iter;  
        n++;  
		int ret = svm.predict (Svmtrainmat); 
		std::sprintf (line, "%s%d\r\n", Img_tst_path[j].c_str (), ret);
		printf ("%s%d\r\n", Img_tst_path[j].c_str (), ret);
        GetChar ();  
    predict_txt<<line;  
  
} predict_txt.close ();  
return 0;   }
Just come here, and then tidy up the train of thought.
If there is a link error when running, there may be no additional dependencies, to add Opencv_objdetect230d.lib, my OpenCV is version 2.3, so this is 230.

Related Article

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.