Ask Your Question

Revision history [back]

I will try to sum up:

string YourImagesDirectory="D:\\Cars\\";
vector<string> files=listFilesInDirectory(YourImagesDirectory+"*.jpg");
//Load NOT cars!
string YourImagesDirectory="D:\\NOTCars\\";
vector<string> files_no=listFilesInDirectory(YourImagesDirectory+"*.jpg");
// Initialize constant values
const int nb_cars = files.size();
const int num_img = nb_cars + filens_no.size(); // Get the number of images
const int image_area = 30*40;
// Initialize your training set.
Mat training_mat(num_img,image_area,CV_32FC1);
Mat labels(num_img,1,CV_32FC1);
// Set temp matrices
Mat tmp_img;
Mat tmp_dst( 30, 40, CV_8UC1 ); // to the right size for resize
// Load image and add them to the training set
for( int i = 0 ;  i < num_img ; ++i )
{
    tmp_img = imread( files[i], 0 ); // load in grayscale.
    resize( tmp_img, tmp_dst, dst.size() );
    Mat row_img = tmp_dst.reshape( 1, 1 ); // get a one line image.
    // copy line and convert to float
    row_img.convertTo( training_mat.row(i), CV_32FC1 );
    labels.at< float >(i, 0) = (i<nb_cars)?1:-1; // 1 for car, -1 otherwise
}
// Train your SVM
CvSVMParams Params;
Params.svm_type=CvSVM::C_SVC;
Params.kernel_type=CvSVM::LINEAR;
Params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, 1e-6);
Params.gamma=3;
CvSVM svm;
svm.train(training_mat,labels,Mat(),Mat(),Params);

Some explanations:

  • Load your car images and NOT car images. To determine what is a car, you need to know what is not a car! You should have many different images here, from almost anything.
  • Convert your image to smaller size, and add them to the training set matrix. This will work with very small image (like in the link provided) but you must have to extract HOG (for example) for real application, like if you want to set a car detector like the pedestrians detector in OpenCV.
  • I use a trick to convert images: First I resize, then I reshape to be a vector (the V in SVM is for Vector, and it's dealing only with vectors!), and finally, I copy the vector to the training_mat with a float conversion.
  • Train your SVM. In your post, you only have car images, and all samples have the same label. Therefore SVM can not discriminate anything if it only know one category.