I need to implement a template matching method with Java. I found OpenCV and JavaCV for this problem. To start with OpenCV I found some Tutorials at http://www.tutorialspoint.com/ (Don´t know why, but the most only create a black image). No matter...
Now I wanted to try this:
http://docs.opencv.org/doc/tutorials/imgproc/histograms/template_matching/template_matching.html
But I have no Idea how I can use it with Java (OpenCV and JavaCV are furnished in Eclipse).
For the case of JavaCV, I found the following Code:
IplImage src = cvLoadImage("new.png");
IplImage tmp = cvLoadImage("old.png");
IplImage result = cvCreateImage(cvSize(src.width()-tmp.width()+1, src.height()- tmp.height()+1), IPL_DEPTH_32F, 1);
cvZero(result);
//Match Template Function from OpenCV
cvMatchTemplate(src, tmp, result, CV_TM_CCORR_NORMED);
double[] min_val = new double[2];
double[] max_val = new double[2];
CvPoint minLoc = new CvPoint();
CvPoint maxLoc = new CvPoint();
//Get the Max or Min Correlation Value
cvMinMaxLoc(result, min_val, max_val, minLoc, maxLoc, null);
System.out.println(Arrays.toString(min_val));
System.out.println(Arrays.toString(max_val));
CvPoint point = new CvPoint();
point.x(maxLoc.x()+tmp.width());
point.y(maxLoc.y()+tmp.height());
cvRectangle(src, maxLoc, point, CvScalar.WHITE, 2, 8, 0);//Draw a Rectangle for Matched Region
cvShowImage("Lena Image", src);
cvWaitKey(0);
cvReleaseImage(src);
cvReleaseImage(tmp);
cvReleaseImage(result);
But however I pass the files I get a NullPointerException.
Has anyone an example how I can use template matching with OpenCV or JavaCV or is there a simple approach doing this task without any library?
Personally I try to do everything with OpenCV's Java bindings if possible. I fall back to JavaCV when something doesn't work with OpenCV's Java bindings. JavaCV seems nice and it's developer seems to put out new releases soon after OpenCV releases, but in the long run my guess is that OpenCV's java bindings will be better supported.
The only area I've found so far that doesn't work in OpenCV are some facial recognition and classification features.
Here's a little OpenCV Java for Template matching. I've left out the loop to swap in multiple templates and find the best match by looking at the results in mmr.
Mat mat = ...
Mat matTemplate = ...
// Create the result matrix
int resultCols = mat.cols() - matTemplate.cols() + 1;
int resultRows = mat.rows() - matTemplate.rows() + 1;
if ( resultCols > 0 && resultRows > 0 ) {
Mat result = new Mat(resultRows, resultCols, CvType.CV_8UC1);
// Do the Matching
Imgproc.matchTemplate(mat, matTemplate, result, Imgproc.TM_CCOEFF_NORMED);
// Normalize???
// Localizing the best match with minMaxLoc
MinMaxLocResult mmr = Core.minMaxLoc(result);
I'm sure you can find some good resources on how to with Template Matching with OpenCV in Java. I know I did.