Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

SVM predict Assertion failed

For now I am trying to predict only 1 or -1

the error is

OpenCV Error: Assertion failed (samples.cols == var_count && samples.type() == CV_32F) in predict

my code

public static Mat getMat(String path) {
    Mat img = new Mat();
    Mat convert_to_gray = Imgcodecs.imread(path, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);
    convert_to_gray.convertTo(img, CvType.CV_8U);
    return img;
}

public static void test() {
    System.out.println("Testing..");
    Mat input = Imgcodecs.imread(new File(FILE_TEST).getAbsolutePath(),0);

    Mat output = new Mat();
    input.convertTo(output,CvType.CV_32SC1);
    output = output.reshape(1, 1);
    System.out.println(output);
    System.out.println(clasificador.predict(output)); <-the error points here 

}

public static void trains() {
    System.out.println("Training...");
    v_descriptors.copyTo(trainingData);
    trainingData.convertTo(trainingData, CvType.CV_32F);
    trainingLabels.copyTo(classes);
    classes.convertTo(classes, CvType.CV_32S);

    clasificador.setType(SVM.C_SVC);
    clasificador.setKernel(SVM.LINEAR);
    clasificador.setGamma(0.5);
    clasificador.setNu(0.5);
    clasificador.setC(1);
    clasificador.setTermCriteria(S);

    clasificador.train(trainingData, Ml.ROW_SAMPLE, classes);
    System.out.println("Done Training");

}

public static void trainPositives() {
    MatOfFloat descriptorsValues = new MatOfFloat();
    int count = 0;
    for (File file : new File(PATH_POSITIVE).listFiles()) {
        count++;
        Mat img = getMat(file.getAbsolutePath());
        HOGDescriptor d = new HOGDescriptor(new Size(32, 16), new Size(8, 8), new Size(4, 4), new Size(4, 4), 9);
        d.compute(img, descriptorsValues);
        Mat labelsMat = new Mat(1, 1, CvType.CV_32SC1, new Scalar(1));
        v_descriptors.push_back(descriptorsValues.reshape(1, 1));
        trainingLabels.push_back(labelsMat);
    }
    System.out.println(v_descriptors);
    System.out.println(trainingLabels);
}

public static void trainNegatives() {
    int count = 0;
    MatOfFloat descriptorsValues2 = new MatOfFloat();
    for (File file : new File(PATH_NEGATIVE).listFiles()) {
        count++;
        Mat img = getMat(file.getAbsolutePath());
        HOGDescriptor d = new HOGDescriptor(new Size(32, 16), new Size(8, 8), new Size(4, 4), new Size(4, 4), 9);
        d.compute(img, descriptorsValues2);
        Mat labelsMat = new Mat(1, 1, CvType.CV_32SC1, new Scalar(-1));

        v_descriptors.push_back(descriptorsValues2.reshape(1, 1));
        trainingLabels.push_back(labelsMat);
    }
    System.out.println(v_descriptors);
    System.out.println(trainingLabels);
}