OpenCV(3.4.1) Error: Assertion failed (samples.cols == var

tech2024-08-02  52

Java调用OpenCV中的SVM报错:

OpenCV(3.4.1) Error: Assertion failed (samples.cols == var_count && samples.type() == 5) in cv::ml::SVMImpl::predict, file C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\ml\src\svm.cpp, line 2005 Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: OpenCV(3.4.1) C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\ml\src\svm.cpp:2005: error: (-215) samples.cols == var_count && samples.type() == 5 in function cv::ml::SVMImpl::predict ] at org.opencv.ml.StatModel.predict_0(Native Method) at org.opencv.ml.StatModel.predict(StatModel.java:128) at com.springdemo.table_classification.Train.main(Train.java:119)

问题分析:OpenCV调用SVM时,要对训练数据和测试数据进行相同的预处理。

先贴网上down的问题代码

训练的核心代码:

Mat input = Imgcodecs.imdecode(new MatOfByte(filebyte), Imgcodecs.IMREAD_UNCHANGED); input = ImageUtil.gray(input); Mat dst = new Mat(); Imgproc.resize(input,dst,new Size(640,800)); dst.convertTo(dst, CvType.CV_32FC1); Mat reshape = dst.reshape(0, 1); train.trainingImages.add(reshape); train.trainingLabels.add(flag);

测试的完整代码:

public void test() { // 测试训练的效果 SVM svm = SVM.load(".../svm_model.xml"); Mat responseMat = new Mat(); Mat imread = Imgcodecs.imread(".../test.jpg", 0); imread.convertTo(imread, CvType.CV_32FC1); Mat reshape = imread.reshape(0, 1); svm.predict(reshape, responseMat, 0); System.out.println(responseMat.dump()); }

可以发现在训练中对图片进行了预处理:灰度化和缩放(ImageUtil.gray & Imgproc.resize),而在测试数据的预处理却没有这两步。对此,修改了训练数据预处理的代码,贴出来重点部分已经用上下空行标出了:

public void test1() { // 测试训练的效果 SVM svm = SVM.load(".../svm_model.xml"); Mat responseMat = new Mat(); String path = ".../test.jpg"; byte[] bytes = getBytes(new File(path)); Mat imread = Imgcodecs.imdecode(new MatOfByte(bytes), Imgcodecs.IMREAD_UNCHANGED); imread = ImageUtil.gray(imread); Mat dst = new Mat(); Imgproc.resize(imread,dst,new Size(640,800)); dst.convertTo(dst, CvType.CV_32FC1); Mat reshape = dst.reshape(0, 1); svm.predict(reshape, responseMat, 0); System.out.println(responseMat.dump()); }

大功告成!

最新回复(0)