训练SVM时出现OpenCV错误(错误的参数)

时间:2015-04-07 23:03:18

标签: java opencv svm

我用训练图像创建了Mat(150图像大小为144x33)所以我的垫子宽度为4752,高度为150。另一种带标签的垫子是1个宽度和150个高度。现在,当我尝试使用这两个Mat的svm.train()时,我遇到了以下错误:

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]

这是我的代码片段,有人可以告诉我什么可能是错的吗?

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");

尺寸数据显示:宽度= 4752,高度= 150

尺寸标签显示:width = 1,height = 150

我做错了什么?

1 个答案:

答案 0 :(得分:2)

Mat labels定义为CV_32FC1,但您可以使用int[] trainLabels中的整数对其进行扩展。
您应该使用浮点trainLabelsCV_32SC1类型labels代替。