To test SVM trained data is whether reliable or not. (example source code)

After training SVM, we should test the trained XML data is reliable or not..

The method to extract HOG feature is refer to -> http://feelmare.blogspot.kr/2014/04/example-source-code-of-extract-hog.html
The method to training SVM of HOG feature is refer to -> http://feelmare.blogspot.kr/2014/04/example-source-code-hog-feature-to.html

The method is using training data.
Again training data make HOG feature, and check the feature is positive or not using trained SVM data.

The example source code is like that.
...
#include < stdio.h>
#include < opencv2\opencv.hpp>
//#include < opencv2\gpu\gpu.hpp>

using namespace cv;
using namespace std;


#ifdef _DEBUG        
#pragma comment(lib, "opencv_core247d.lib")         
#pragma comment(lib, "opencv_imgproc247d.lib")   //MAT processing        
#pragma comment(lib, "opencv_objdetect247d.lib") //HOGDescriptor
//#pragma comment(lib, "opencv_gpu247d.lib")        
//#pragma comment(lib, "opencv_features2d247d.lib")        
#pragma comment(lib, "opencv_highgui247d.lib")        
#pragma comment(lib, "opencv_ml247d.lib")      
//#pragma comment(lib, "opencv_stitching247d.lib");      
//#pragma comment(lib, "opencv_nonfree247d.lib");      
  
#else        
#pragma comment(lib, "opencv_core247.lib")        
#pragma comment(lib, "opencv_imgproc247.lib")        
#pragma comment(lib, "opencv_objdetect247.lib")        
//#pragma comment(lib, "opencv_gpu247.lib")        
//#pragma comment(lib, "opencv_features2d247.lib")        
#pragma comment(lib, "opencv_highgui247.lib")        
#pragma comment(lib, "opencv_ml247.lib")        
//#pragma comment(lib, "opencv_stitching247.lib");      
//#pragma comment(lib, "opencv_nonfree247.lib");      
#endif 


void main()
{

 //variables
 char FullFileName[100];
 char FirstFileName[100]="./images/upperbody"; //"./NegaImages/Negative";      // 
 int FileNum=96; //262;

 //Load trained SVM xml data
 CvSVM svm;
 svm.load("trainedSVM.xml");

 //count variable
 int nnn=0, ppp=0;

 for(int i=0; i< FileNum; ++i)
 {
  sprintf_s(FullFileName, "%s%d.png", FirstFileName, i+1);
  //printf("%s\n", FullFileName);

  //read image file
  Mat img, img_gray;
  img = imread(FullFileName);
  
  //resizing
  //resize(img, img, Size(16,8) ); //Size(64,48) ); //Size(32*2,16*2)); //Size(80,72) ); 
  resize(img, img, Size(64,48) ); //Size(32*2,16*2)); //Size(80,72) ); 
  //gray
  cvtColor(img, img_gray, CV_RGB2GRAY);

  //Extract HogFeature
  HOGDescriptor d( Size(32,16), Size(8,8), Size(4,4), Size(4,4), 9);
  vector< float> descriptorsValues;
  vector< Point> locations;
  d.compute( img_gray, descriptorsValues, Size(0,0), Size(0,0), locations);
  //vector to Mat
  Mat fm = Mat(descriptorsValues);
  
  //Classification whether data is positive or negative
  int result = svm.predict(fm);
  printf("%s - > %d\n", FullFileName, result);

  //Count data
  if(result == 1)
   ppp++;
  else
   nnn++;

  //show image
  imshow("origin", img);

  waitKey(5);
 }

 printf(" positive/negative = (%d/%d) \n", ppp, nnn);

}
---


Comments

  1. 안녕하세요" 또 질문드리게 되네요;;
    영어로 답변해주시는데;; 질문을 계속 한글로 드려 죄송합니다;;

    블로그에 설명해주신대로 따라 하면서 trainedSVM.xml 파일을 얻을 수 있었습니다.
    위 xml파일을 사용해서 보행자를 검출해보고자 합니다. 그래서

    HOGDescriptor hog;
    hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
    --> hog.load("trainedSVM.xml");
    getDefaultPeopleDetector()를 사용하지 않고 학습한 xml을 사용하기 위해서
    위와 같이 수정하였습니다. 그리고 hog.detectMultiScale()을 수행하였는데
    에러가 발생하였습니다;; 중간에 다른 코드가 필요한지... 아니면... 학습된 xml데이터 포멧을 수정해야 하는지;; 궁금합니다...

    HOGDescriptor hog;
    hog.load("trainedSVM.xml");
    hog.detectMultiScale(matImage, Peds, 0, cv::Size(8, 8), cv::Size(0, 0), 1.05, 1);
    for(int i=0; i<(int)Peds.size(); i++)
    {
    rectangle(matImage, Peds[i], Scalar(0,255,0), 1);
    }
    이런 식으로 사용했습니다.

    OpenCV Error : Assertion failed (dsize.area() || (in_scale_x >0 && inv_scale_y > 0))
    in cv::resize, file ..\..\..\soureces\modules\imgproc\src\imgwarp.cpp, line 1835
    에러는 위와 같이 발생했습니다;;

    오늘도 많이 배워갑니다. 감사합니다.

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. You need to convert "trainedSVM.xml" file learned by SVM to 1D vector for using function of hog.detectMultiscale().

      After training by SVM, use this source code.

      --
      //make firstly, inherited class to access alpha vector and value
      int svmVectorSize = svm.get_support_vector_count();
      int featureSize = pCol;
      //prepare, variables


      Mat sv = Mat(svmVectorSize, featureSize, CV_32FC1, 0.0);
      Mat alp = Mat(1, svmVectorSize, CV_32FC1, 0.0);
      Mat re = Mat(1, featureSize, CV_32FC1, 0.0);
      Mat re2 = Mat(1, featureSize+1, CV_32FC1, 0.0);



      //set value to variables
      for(int i=0; i< svmVectorSize; ++i)
      memcpy( (sv.data + i*featureSize), svm.get_support_vector(i), featureSize*sizeof(float) ); //ok


      double * alphaArr = svm.get_alpha();
      int alphaCount = svm.get_alpha_count();

      for(int i=0; i< svmVectorSize; ++i)
      {
      alp.at< float>(0, i) = (float)alphaArr[i];
      //printf("alpha[%d] = %lf \n", i, (float)alphaArr[i] );
      }

      //cvMatMul(alp, sv, re);
      re = alp * sv;

      for(int i=0; i< featureSize; ++i)
      re2.at< float>(0,i) = re.at< float>(0,i) * -1;
      re2.at< float>(0,featureSize) = svm.get_rho();

      //save to 1d vector to XML format!!
      FileStorage svmSecondXML(SVM_HOGDetectorFile, FileStorage::WRITE);
      svmSecondXML << "SecondSVMd" << re2 ;

      svmSecondXML.release();

      --

      Delete
    2. SVM_HOGDetectorFile means new name of xml file.
      ex) AA.xml

      thank you

      Delete
    3. 답변해주셔서 감사합니다!!
      염치없지만...;; 또 질문드립니다;;
      http://feelmare.blogspot.kr/2014/04/example-source-code-hog-feature-to.html
      블로그의 위 내용에 이어서 올려주신 코드를 작성하였고,
      저는 opencv 2.4.9. 버전을 사용해서 lib만 2.4.7에서 2.4.9. 로 바꿔서 예제를 실행보았습니다

      위 코드에서 svm구조체의 멤버(?)를 읽지 못하는 부분이 발생하였습니다. svm.get_alpha(), svm.get_alpha_count(), svm.get_rho()
      이 세 가지입니다.

      그리고 SVM_HOGDetectorFile이 새로운 *.xml파일의 이름이라고 하셨는
      데, 이부분도 에러가 발생합니다;;

      도움주셔서 감사합니다""

      Delete
    4. I'm sorry, I don't teach you exact description.
      I will post about the article(hog.detectMultiscale) tomorrow.
      Thank you.


      Delete
    5. 네" 답변 감사합니다""

      Delete
    6. refer to this page
      http://feelmare.blogspot.kr/2014/11/opencv-svm-learning-method-and-xml.html
      thank you.

      Delete
  3. Anonymous25/2/16 09:54

    Hey i have problem , when i get to svm.predict it throw me some exception. Looks like its even don t load svm from xml.
    Any idea why ? I just copypaste your codes, even extracting hog and train svm

    ReplyDelete
    Replies
    1. Could you show your code or send source code to me?
      Thank you.

      Delete
    2. Anonymous26/2/16 14:35

      Oh... i find out that i changed size of hog descriptor in training source code(that was the problem - i am new in this so i am littlebit confused in some things)...
      Just if i could ask another things:
      Should be training images for svm in same aspect ratio ? I saw in source codes befor ... that you resizing them, so i gues it should be in same ratio as you resize them.Am i right ?
      Nex question: after i have converted it in 1d vector like in upper comments i just load big image , use detectmultiscale and it returns some vector of rectangles(or what is return of detectmultiscale)? Didn t find topic of it here, but maybe i am blind.
      Sorry for too much questions. By the way a really appreciate this site and all codes here. I learned much more than anywhere else.
      Thank you

      Delete
    3. Anonymous26/2/16 14:41

      Sorry there is topic, but with gpu, so i will check it

      Delete
  4. Hi, how can I use this algorithm to see exactly what kind of images I have ? For example If I trained 30 photo with cars, 30 with planes and 30 with houses, and another 100 negative images, when I read an image with a car to figure out that in my pictures I have a car. Here we find out only if it is a positive picture or negative. Thanks.

    ReplyDelete

Post a Comment

Popular posts from this blog

(OpenCV Study) Background subtractor MOG, MOG2, GMG example source code (BackgroundSubtractorMOG, BackgroundSubtractorMOG2, BackgroundSubtractorGMG)

OpenCV Stitching example (Stitcher class, Panorama)

Example source code of extract HOG feature from images, save descriptor values to xml file, using opencv (using HOGDescriptor )

Real-time N camera stitching Class.

Optical Flow sample source code using OpenCV

OpenCV Drawing Example, (line, circle, rectangle, ellipse, polyline, fillConvexPoly, putText, drawContours)

Video Stabilization example source code, (using cvFindHomography, cvWarpPerspective functions in openCV)

SICK LMS511 sensor data acquisition interface (source code, C++/MFC)

8 point algorithm (Matlab source code) / The method to get the Fundamental Matrix and the Essential matrix

Image warping (using opencv findHomography, warpPerspective)