How to train an SVM with opencv based on a set of images?

asked 2017-02-16 18:25:34 -0500

Tomna gravatar image

the following code is based on someone else code i want to know how to convert some of the lines to java's SVM class

the lines are

 CvSVMParams params = new CvSVMParams();
 params.set_kernel_type(CvSVM.LINEAR);
  clasificador = new CvSVM(trainingData, classes, new Mat(), new Mat(), params);

is i clasificador.train(); ?

Mat classes = new Mat(); Mat trainingData = new Mat();

Mat trainingImages = new Mat();
Mat trainingLabels = new Mat();

CvSVM clasificador;

for (File file : new File(path + "positives/").listFiles()) {
        Mat img = Highgui.imread(file.getAbsolutePath());
        img.reshape(1, 1);

        trainingImages.push_back(img);
        trainingLabels.push_back(Mat.ones(new Size(1, 1), CvType.CV_32FC1));
    }

    for (File file : new File(path + "negatives/").listFiles()) {
        Mat img = Highgui.imread(file.getAbsolutePath());
        img.reshape(1, 1);

        trainingImages.push_back(img);
        trainingLabels.push_back(Mat.zeros(new Size(1, 1), CvType.CV_32FC1));
    }

    trainingImages.copyTo(trainingData);
    trainingData.convertTo(trainingData, CvType.CV_32FC1);
    trainingLabels.copyTo(classes);

    CvSVMParams params = new CvSVMParams();
    params.set_kernel_type(CvSVM.LINEAR);

    clasificador = new CvSVM(trainingData, classes, new Mat(), new Mat(), params);

here is an attempt by me

public static void train() {

    trainingImages.copyTo(trainingData);
    trainingData.convertTo(trainingData, CvType.CV_32FC1);
    trainingLabels.copyTo(classes);

    clasificador.setKernel(SVM.LINEAR);
    clasificador.train(trainingData, 0, classes);
    clasificador.save(XML);
}
edit retag flag offensive close merge delete

Comments

1

for a classification, you need integer labels.

berak gravatar imageberak ( 2017-02-17 01:30:18 -0500 )edit

@berak could you check my attempt and tell me how to make it do the same function like above 3 lines of code. and classification is either 1 or 0 right?

Tomna gravatar imageTomna ( 2017-02-17 05:24:44 -0500 )edit

at a glance, it looks correct, but i neither have opencv2.4, nor java, save your images, so i cannot reproduce it, sorry.

berak gravatar imageberak ( 2017-02-17 06:12:21 -0500 )edit