Tomek
Tomek

Reputation: 121

OpenCV error while training SVM (bad argument)

I have created Mat with training images (150 images size of 144x33) so my Mat is 4752 width and 150 height. Another mat with labels is 1 width and 150 height. And now when I am trying svm.train() with these two Mat's, I am getting following error:

OpenCV Error: Bad argument (response #2 is not integral) in cvPreprocessCategoricalResponses, file ..\..\..\..\opencv\modules\ml\src\inner_functions.cpp, line 715
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\ml\src\inner_functions.cpp:715: error: (-5) response #2 is not integral in function cvPreprocessCategoricalResponses]

Here is piece of my code, can somebody tell me what could be wrong?

Mat trainingImages = new Mat(0, imageWidth * imageHeight, CvType.CV_32FC1);
    Mat labels = new Mat(amountOfPlates + amountOfNoPlates, 1, CvType.CV_32FC1);
    List<Integer> trainingLabels = new ArrayList<>();

    for (int i = 0; i < amountOfPlates; i++) {
        int index = i + 1;
        String file = pathPlates + index + ".jpg";

        Mat img = Highgui.imread(file, 0);
        img.convertTo(img, CvType.CV_32FC1);
        img = img.reshape(1, 1);
        trainingImages.push_back(img);
        trainingLabels.add(1);
    }

    for (int i = 0; i < amountOfNoPlates; i++) {
        int index = i + 1;
        String file = pathNoPlates + index + ".jpg";
        Mat img = Highgui.imread(file, 0);
        img.convertTo(img, CvType.CV_32FC1);
        img = img.reshape(1, 1);
        trainingImages.push_back(img);
        trainingLabels.add(0);
    }

    Integer[] array = trainingLabels.toArray(new Integer[trainingLabels.size()]);

    int[] trainLabels = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        trainLabels[i] = array[i];
    }

    for (int i = 0; i < trainingLabels.size(); i++) {
        labels.put(i, 1, trainLabels[i]);
    }

    CvSVMParams params = new CvSVMParams();
    params.set_svm_type(CvSVM.C_SVC);
    params.set_kernel_type(CvSVM.LINEAR);
    params.set_degree(0);
    params.set_gamma(1);
    params.set_coef0(0);
    params.set_C(1);
    params.set_nu(0);
    params.set_p(0);
    TermCriteria tc = new TermCriteria(opencv_core.CV_TERMCRIT_ITER, 1000, 0.01);
    params.set_term_crit(tc);

    Size data = trainingImages.size();
    Size label = labels.size();


    CvSVM svmClassifier = new CvSVM();
    svmClassifier.train(trainingImages, labels, new Mat(), new Mat(), params);
    svmClassifier.save("test.xml");

Size data shows: width = 4752, height = 150

Size labels shows: width = 1, height = 150

What am I doing wrong?

Upvotes: 3

Views: 1344

Answers (1)

Kornel
Kornel

Reputation: 5354

Mat labels was defined as CV_32FC1, but you extend it with integers from int[] trainLabels.
You should use floating point trainLabels or CV_32SC1 type labels instead.

Upvotes: 3

Related Questions