简体   繁体   English

java OpenCV查找k最近邻居C ++到Java转换

[英]java OpenCV find k nearest neighbor c++ to java conversion

I am trying to find the k nearest neighbors with the Knn classifier in OpenCV. 我试图用OpenCV中的Knn分类器找到k个最近的邻居。 I found this C++ Code: 我找到了这个C ++代码:

class atsKNN{
public :
void knn(cv::Mat& trainingData, cv::Mat& trainingClasses, cv::Mat& testData, cv::Mat& testClasses, int K) 
{
    cv::KNearest knn(trainingData, trainingClasses, cv::Mat(), false, K);
    cv::Mat predicted(testClasses.rows, 1, CV_32F);
    for(int i = 0; i < testData.rows; i++) {
            const cv::Mat sample = testData.row(i);
            predicted.at<float>(i,0) = knn.find_nearest(sample, K);
    }

    float percentage = evaluate(predicted, testClasses) * 100;
    cout << "K Nearest Neighbor Evaluated Accuracy = " << percentage << "%" << endl;
    prediction = predicted;
}
void showplot(cv::Mat testData)
{
    plot_binary(testData, prediction, "Predictions Backpropagation");
}
private:
cv::Mat prediction;

};

The comments mention it works really good but i am having problems Converting it to Java. 评论提到它确实很好,但是我在将其转换为Java时遇到了问题。 There is no Documentation for Java. 没有Java文档。 I tried using a C++ to Java Converter but the resulting Code does not work. 我尝试使用C ++到Java转换器,但是生成的代码不起作用。

here is the code it produced: 这是它产生的代码:

public class atsKNN
{
public final void knn(cv.Mat trainingData, cv.Mat trainingClasses, cv.Mat testData, cv.Mat testClasses, int K)
{
    cv.KNearest knn = new cv.KNearest(trainingData, trainingClasses, cv.Mat(), false, K);
    cv.Mat predicted = new cv.Mat(testClasses.rows, 1, CV_32F);
    for (int i = 0; i < testData.rows; i++)
    {
            final cv.Mat sample = testData.row(i);
            predicted.<Float>at(i,0) = knn.find_nearest(sample, K);
    }

    float percentage = evaluate(predicted, testClasses) * 100;
    System.out.print("K Nearest Neighbor Evaluated Accuracy = ");
    System.out.print(percentage);
    System.out.print("%");
    System.out.print("\n");
    prediction = predicted;
}
public final void showplot(cv.Mat testData)
{
    plot_binary(testData, prediction, "Predictions Backpropagation");
}
private cv.Mat prediction = new cv.Mat();

}

edit: The line predicted.at(i,0) = knn.find_nearest(sample, K); 编辑:这行预测。at(i,0)= knn.find_nearest(sample,K); has most definitely to be wrong. 肯定是错的。 There is now function at in object Mat. 现在在对象Mat中有功能。 Also there is no "evaluate function". 也没有“评估功能”。 Another thing is where does the prediction Mat belong to?In java you can not just put it in the end of the class. 另一件事是预测Mat属于什么地方?在Java中,您不能只将其放在类的末尾。 Thanks=) 谢谢=)

The following code is for finding the digits 以下代码用于查找数字

here's some code to try: 这是一些代码尝试:

import org.opencv.core.*;
import org.opencv.imgproc.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.ml.*;
import org.opencv.utils.*;
import java.util.*;


class SimpleSample {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }

public static void main(String[] args) {
    // samples/data/digits.png, have a look at it.
    Mat digits = Imgcodecs.imread("digits.png", 0);
    // setup train/test data:
    Mat trainData = new Mat(),
        testData = new Mat();
    List<Integer> trainLabs = new ArrayList<Integer>(),
        testLabs = new ArrayList<Integer>();
    // 10 digits a 5 rows:
    for (int r=0; r<50; r++) { 
        // 100 digits per row:
        for (int c=0; c<100; c++) {
            // crop out 1 digit:
            Mat num = digits.submat(new Rect(c*20,r*20,20,20));
            // we need float data for knn:
            num.convertTo(num, CvType.CV_32F);
            // 50/50 train/test split:
            if (c % 2 == 0) {
                // for opencv ml, each feature has to be a single row:
                trainData.push_back(num.reshape(1,1));
                // add a label for that feature (the digit number):
                trainLabs.add(r/5);
            } else {
                testData.push_back(num.reshape(1,1));
                testLabs.add(r/5);
            }
        }                
    }

    // make a Mat of the train labels, and train knn:
    KNearest knn = KNearest.create();
    knn.train(trainData, Ml.ROW_SAMPLE, Converters.vector_int_to_Mat(trainLabs));
    // now test predictions:
    for (int i=0; i<testData.rows(); i++)
    {
        Mat one_feature = testData.row(i);
        int testLabel = testLabs.get(i);

        Mat res = new Mat();
        float p = knn.findNearest(one_feature, 1, res);
        System.out.println(testLabel + " " + p + " " + res.dump());
    }

    //// hmm, the 'real world' test case probably looks more like this:
    //// make sure, you follow the very same preprocessing steps used in the train phase:
    //  Mat one_feature = Imgcodecs.imread("one_digit.png", 0);
    //  Mat feature; one_feature.convertTo(feature, CvTypes.CV_32F);
    //  Imgproc.resize(feature, feature, Size(20,20));
    //  int predicted = knn.findNearest(feature.reshape(1,1), 1);
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM