我试图实现KNN findNearest函数 . 我的程序应识别图片中的数字,但如果程序使用findNearest,我会收到错误 . 这是代码:

`private void searchingData() {

    img_gray = new Mat();
    img_blur = new Mat();
    img_thres = new Mat();

    Imgproc.cvtColor(img, img_gray, Imgproc.COLOR_BGR2GRAY);
    Imgproc.GaussianBlur(img_gray, img_blur, new Size(5,5), 0);
    //Imgproc.adaptiveThreshold(img_blur, img_thres, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 7, 5);
    Imgproc.Canny(img_blur, img_thres, 10, 100); 

    Imgproc.findContours(img_thres, contours, new Mat(), Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE);

    for(int i=0; i< contours.size();i++){

        Rect rect = Imgproc.boundingRect(contours.get(i));

        if (rect.height < 50 && rect.height > 20){ 

            System.out.println(rect.x +","+rect.y+","+rect.height+","+rect.width);

            Mat subImg = new Mat();
            Imgproc.resize(img.submat(rect), subImg, new Size(10,10));

            //Found numbers then try to recognize it
            recognize(subImg);
        }
    }
}

public void learn() { //get the training data and train the KNN

    Mat sample, training_img = new Mat(), res = new Mat();

    for (int i = 1; i < 10; i++) {

        String path = String.format(".../Documents/numbers/%03d.png", i);
        sample = Imgcodecs.imread(path, Imgcodecs.CV_LOAD_IMAGE_GRAYSCALE);

        Mat m = new Mat(new Size(1,1), CvType.CV_32FC1);
        m.setTo(new Scalar(i));
        res.push_back(m);

        training_img.push_back(prepareImg(sample));
    }

    model = KNearest.create();
    model.train(training_img, Ml.ROW_SAMPLE, res);

}

private Mat prepareImg(Mat img) { //change image in the right format
    Mat sample = new Mat(), sized = new Mat();

    Imgproc.resize(img, sized, new Size(10,10));
    sized.reshape(1,1).convertTo(sample, CvType.CV_32FC1);

    return sample;
}

public void recognize(Mat getImg) {

    Mat results = new Mat();
    Mat dists   = new Mat();

    float result = model.findNearest(prepareImg(getImg), 2, results, new Mat(), dists);

    //result should be the number in getImg
    System.out.println(result);
}`

OpenCV错误:断言失败(test_samples.type()== CV_32F && test_samples.cols == samples.cols)在cv :: ml :: BruteForceImpl :: findNearest中,文件C:\ builds \ master_PackSlaveAddon-win64-vc12-static \ opencv \ modules \ ml \ src \ knearest.cpp,第325行线程“main”中的异常CvException [org.opencv.core.CvException:cv :: Exception:C:\ builds \ master_PackSlaveAddon-win64-vc12-static \ opencv \ modules \ ml \ src \ knearest.cpp:325:错误:(-215)test_samples.type()== CV_32F && test_samples.cols == samples.cols in function cv :: ml :: BruteForceImpl :: findNearest]

非常感谢!