在Android中使用OpenCV进行模板匹配的示例

27

我是OpenCV的初学者。我正在尝试创建一个示例Android应用程序,使用OpenCV模板匹配在给定图像中匹配模板图像。我在互联网上搜索,但找不到适合我要求的Android或Java代码。但是我有C++代码,我不知道如何将其翻译成Java。

http://docs.opencv.org/doc/tutorials/imgproc/histograms/template_matching/template_matching.html

你能帮我找到适合的Java或Android代码吗?否则,请帮我将这个C++代码翻译成Java,以便我可以在Android应用程序中使用它。

谢谢您提前。

C ++代码

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>
#include <stdio.h>

using namespace std;
using namespace cv;

/// Global Variables
Mat img; Mat templ; Mat result;
char* image_window = "Source Image";
char* result_window = "Result window";

int match_method;
int max_Trackbar = 5;

/// Function Headers
void MatchingMethod( int, void* );

/** @function main */
int main( int argc, char** argv )
{
  /// Load image and template
  img = imread( argv[1], 1 );
  templ = imread( argv[2], 1 );

  /// Create windows
  namedWindow( image_window, CV_WINDOW_AUTOSIZE );
  namedWindow( result_window, CV_WINDOW_AUTOSIZE );

  /// Create Trackbar
  char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED";
  createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod );

  MatchingMethod( 0, 0 );

  waitKey(0);
  return 0;
}

/**
 * @function MatchingMethod
 * @brief Trackbar callback
 */
void MatchingMethod( int, void* )
{
  /// Source image to display
  Mat img_display;
  img.copyTo( img_display );

  /// Create the result matrix
  int result_cols =  img.cols - templ.cols + 1;
  int result_rows = img.rows - templ.rows + 1;

  result.create( result_cols, result_rows, CV_32FC1 );

  /// Do the Matching and Normalize
  matchTemplate( img, templ, result, match_method );
  normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() );

  /// Localizing the best match with minMaxLoc
  double minVal; double maxVal; Point minLoc; Point maxLoc;
  Point matchLoc;

  minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() );

  /// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
  if( match_method  == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
    { matchLoc = minLoc; }
  else
    { matchLoc = maxLoc; }

  /// Show me what you got
  rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );
  rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 );

  imshow( image_window, img_display );
  imshow( result_window, result );

  return;
}

谷歌的 Android NDK。 - user784435
你已经运行了Android SDK的示例吗? - user784435
是的,那些东西就是不起作用。 - ssdehero
让我们在聊天中继续这个讨论:http://chat.stackoverflow.com/rooms/31481/discussion-between-ssdehero-and-bounder-and-a-cad - ssdehero
使用相关系数匹配,一个好的匹配返回1,没有匹配返回0,而不匹配则返回低至-1。 - Mel Void
显示剩余4条评论
2个回答

47

我也遇到了与你相同的问题。 Java 中没有可用的源代码。 通过 JavaDoc 的一些搜索以及对常量值的某些提示,我编写了以下代码,几乎与上面的示例代码相同:

package opencv;

import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

class MatchingDemo {
    public void run(String inFile, String templateFile, String outFile, int match_method) {
        System.out.println("\nRunning Template Matching");

        Mat img = Highgui.imread(inFile);
        Mat templ = Highgui.imread(templateFile);

        // / Create the result matrix
        int result_cols = img.cols() - templ.cols() + 1;
        int result_rows = img.rows() - templ.rows() + 1;
        Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

        // / Do the Matching and Normalize
        Imgproc.matchTemplate(img, templ, result, match_method);
        Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

        // / Localizing the best match with minMaxLoc
        MinMaxLocResult mmr = Core.minMaxLoc(result);

        Point matchLoc;
        if (match_method == Imgproc.TM_SQDIFF || match_method == Imgproc.TM_SQDIFF_NORMED) {
            matchLoc = mmr.minLoc;
        } else {
            matchLoc = mmr.maxLoc;
        }

        // / Show me what you got
        Core.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
                matchLoc.y + templ.rows()), new Scalar(0, 255, 0));

        // Save the visualized detection.
        System.out.println("Writing "+ outFile);
        Highgui.imwrite(outFile, img);

    }
}

public class TemplateMatching {
    public static void main(String[] args) {
        System.loadLibrary("opencv_java246");
        new MatchingDemo().run(args[0], args[1], args[2], Imgproc.TM_CCOEFF);
    }
}

现在使用以下选项运行程序:lena.png template.png templatematch.png,你应该会得到和我一样的结果。确保这些文件可以被你的运行时访问,并且当然,opencv 2.4.6库已经注册到你的类路径中。

lena.pngtemplate.pngtemplatematch.png


我使用了你的代码,但当我将其与另一张图片匹配时,即使图像不匹配,矩形也会被绘制? 我要如何知道是否存在匹配项,例如一个布尔变量来说明是否有匹配(我的意思是是否有类似的东西)? - Girish Nair
我不知道。请发布一个新的问题以便让更多的人来查看。这可能会引起更多人的兴趣。 - micfra
使用matchTemplate(...)不会出现“错误”匹配。结果只会给出“最佳匹配(潜在)对象在此位置”的信息。因此,您需要添加一个检查mmr.minValmmr.maxVal的阈值,如答案https://dev59.com/4HTYa4cB1Zd3GeqPyLyM#17785075中所述。是的,我编写了这个JAVA端口。 - micfra
1
这不适用于从相机拍摄的照片。我的情况是我有一个预定义的模板,并且我想从捕获的图像中检测模板区域。有什么办法可以让它与相机捕获的图像一起工作? - TharakaNirmana
我发布了一个新问题:https://dev59.com/NnjZa4cB1Zd3GeqPaSIT - TharakaNirmana
显示剩余7条评论

7

如果您想使用OpenCV 3及以上版本,则应使用以下代码

因为在OpenCV 3中没有Highgui,您应该使用imgcodecs代替。

import org.opencv.core.Core;
import org.opencv.core.Core.MinMaxLocResult;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

class MatchingDemo {
    public void run(String inFile, String templateFile, String outFile,
        int match_method) {
    System.out.println("\nRunning Template Matching");

    Mat img = Imgcodecs.imread(inFile);
    Mat templ = Imgcodecs.imread(templateFile);

    // / Create the result matrix
    int result_cols = img.cols() - templ.cols() + 1;
    int result_rows = img.rows() - templ.rows() + 1;
    Mat result = new Mat(result_rows, result_cols, CvType.CV_32FC1);

    // / Do the Matching and Normalize
    Imgproc.matchTemplate(img, templ, result, match_method);
    Core.normalize(result, result, 0, 1, Core.NORM_MINMAX, -1, new Mat());

    // / Localizing the best match with minMaxLoc
    MinMaxLocResult mmr = Core.minMaxLoc(result);

    Point matchLoc;
    if (match_method == Imgproc.TM_SQDIFF
            || match_method == Imgproc.TM_SQDIFF_NORMED) {
        matchLoc = mmr.minLoc;
    } else {
        matchLoc = mmr.maxLoc;
    }

    // / Show me what you got
    Imgproc.rectangle(img, matchLoc, new Point(matchLoc.x + templ.cols(),
            matchLoc.y + templ.rows()), new Scalar(0, 255, 0));

    // Save the visualized detection.
    System.out.println("Writing " + outFile);
    Imgcodecs.imwrite(outFile, img);

}
}

public class TemplateMatching {

public static void main(String[] args) {
    System.loadLibrary("opencv_java300");
    new MatchingDemo().run(args[0], args[1], args[2], Imgproc.TM_CCOEFF);
}

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接