OpenCV matchTemplate提供不正确的结果

时间:2018-12-09 09:33:42

标签: java android android-studio opencv opencv4android

我一直在尝试比较两个图像,并获得显示图像之间差异的输出。该代码似乎可以在具有相同逻辑的python环境下完美运行。但它似乎在Android Studio上不起作用。在此过程中,compareHist的值返回1,变量“准确性”变为1。总之,可以说此代码匹配了任何两个不同的图像。我该如何解决?

private void compare_image(){
    Mat image_1 = Imgcodecs.imread(getResources().getDrawable(R.drawable.real10tk).toString());
    Mat image_2 = Imgcodecs.imread(getResources().getDrawable(R.drawable.noteicon).toString());
    double commutativeImageDiff = this.get_image_difference(image_1, image_2);
    TextView t = findViewById(R.id.textView10);

    int minImgDiff = 1;
    if (commutativeImageDiff < minImgDiff) {
        TextView text = findViewById(R.id.textView11);
        text.setText("M");
        t.setText("" + commutativeImageDiff);
    }
    else t.setText("" + 10000);
}

@SuppressLint("SetTextI18n")
private double get_image_difference(Mat image_1, Mat image_2) {
    MatOfFloat ranges = new MatOfFloat(0f, 256f);
    MatOfInt histsize = new MatOfInt(256);

    calcHist(Arrays.asList(image_1), new MatOfInt(0), new Mat(), image_1, histsize, ranges);
    calcHist(Arrays.asList(image_2), new MatOfInt(0), new Mat(), image_2, histsize, ranges);

    double img_hist_diff = compareHist(image_1, image_2, HISTCMP_BHATTACHARYYA);// img_hist_diff = 0

    int result_cols = image_1.cols() - image_2.cols() + 1;
    int result_rows = image_1.rows() - image_2.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);
    Imgproc.matchTemplate(image_1, image_2, result, TM_CCOEFF_NORMED);

    Core.MinMaxLocResult minMaxLocRes = Core.minMaxLoc(result);

    double accuracy = minMaxLocRes.maxVal;
    Point location = minMaxLocRes.maxLoc;

    double img_template_diff = 1 - accuracy;    //accuracy = 1

    return (img_hist_diff / 10) + img_template_diff;
}

0 个答案:

没有答案