svm java opencv 3

asked 2015-06-09 13:15:54 -0600

iamprivate gravatar image

Hi, I am trying to implement BoW model using opencv java, but I am facing an issue while using SVM.Kindly help me to debug it. My code goes as follows

     SVM classifier = SVM.create();
     TermCriteria criteria = new TermCriteria(TermCriteria.EPS + TermCriteria.MAX_ITER,100,0.1);
 classifier.setKernel(SVM.LINEAR);
 classifier.setType(SVM.C_SVC);
 classifier.setGamma(0.5);
 classifier.setNu(0.5);
 classifier.setC(1);
 classifier.setTermCriteria(criteria);

 //data is N x 64 trained data Mat , labels is N x 1 label Mat with integer values;
 classifier.train(data, Ml.ROW_SAMPLE, labels);

 Mat results = new Mat();
 int label = (int) classifier.predict(testSamples, results, 0);
return label;

But while excecuting classifier.train() its throwing this error OpenCV Error: Bad argument (in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses) in cv::ml::SVMImpl::train, file C:\builds\master_PackSlaveAddon-win64-vc12-static\opencv\modules\ml\src\svm.cpp, line 1610owing this error

edit retag flag offensive close merge delete

Comments

1

can you show, how you build your 'labels' array ?

berak gravatar imageberak ( 2015-06-10 01:11:57 -0600 )edit
1

Thanks I got the mistake. I original kept the data type of label as 32FC1 . Now I changed it to 32SC1. Now it works :)

     Mat labels = new Mat(new Size(1,totalSamples),CvType.CV_32SC1);        
    for (int i = 0; i < labels.rows(); i++) {
        int label =(i/40)+1;
                    // value 40 is number of samples per class
        labels.put(i, 0, label);
    }
    return labels;
iamprivate gravatar imageiamprivate ( 2015-06-10 03:07:10 -0600 )edit

^^ ah, that looks ok now.

still, curious about how you handle the BOW training. (i don't think, that you can use opencv's BOWKMeansTrainer or such.)

berak gravatar imageberak ( 2015-06-10 05:15:48 -0600 )edit

I didnt use any inbuilt function for BoW , but implemented manually , using features and kmeans, and then saving the histograms in text file

iamprivate gravatar imageiamprivate ( 2015-06-20 09:22:41 -0600 )edit

^^ ahh, ok, makes a lot of sense.

( i was just asking, because some months ago, we tried to wrap the BowKmeansTrainer to opencv's scripting, and failed due to some warts in the java feature2d api. so - good, you found your own way doing so !)

berak gravatar imageberak ( 2015-06-20 09:34:42 -0600 )edit

Can u send the complete code for svm in java

alduaa gravatar imagealduaa ( 2016-02-20 23:11:32 -0600 )edit