/samples/TemplateMatching.java

https://gitlab.com/cvtung/javacv · Java · 80 lines · 47 code · 15 blank · 18 comment · 0 complexity · 3d734f760d73584bc4321713ff229c88 MD5 · raw file

  1. import org.bytedeco.javacv.*;
  2. import org.bytedeco.javacpp.*;
  3. import static org.bytedeco.javacpp.opencv_core.*;
  4. import static org.bytedeco.javacpp.opencv_imgproc.*;
  5. import static org.bytedeco.javacpp.opencv_highgui.*;
  6. import static org.bytedeco.javacpp.opencv_imgcodecs.*;
  7. import static org.bytedeco.javacpp.opencv_calib3d.*;
  8. import static org.bytedeco.javacpp.opencv_objdetect.*;
  9. /**
  10. * Example of template javacv (opencv) template matching using the last java build
  11. *
  12. * We need 4 default parameters like this
  13. * "C:\Users\Waldema\Desktop\bg.jpg" "C:\Users\Waldema\Desktop\logosiemens.jpg" "C:\Users\Waldema\Desktop\imageToFind.jpg" 100 200
  14. *
  15. * @author Waldemar Neto
  16. */
  17. public class TemplateMatching {
  18. public static void main(String[] args) throws Exception {
  19. int width = Integer.parseInt(args[3]);
  20. int height = Integer.parseInt(args[4]);
  21. IplImage src = cvLoadImage(
  22. args[0], 0);
  23. IplImage tmp = cvLoadImage(
  24. args[1], 0);
  25. IplImage result = cvCreateImage(
  26. cvSize(src.width() - tmp.width() + 1,
  27. src.height() - tmp.height() + 1), IPL_DEPTH_32F, src.nChannels());
  28. cvZero(result);
  29. // Match Template Function from OpenCV
  30. cvMatchTemplate(src, tmp, result, CV_TM_CCORR_NORMED);
  31. // double[] min_val = new double[2];
  32. // double[] max_val = new double[2];
  33. DoublePointer min_val = new DoublePointer();
  34. DoublePointer max_val = new DoublePointer();
  35. CvPoint minLoc = new CvPoint();
  36. CvPoint maxLoc = new CvPoint();
  37. cvMinMaxLoc(result, min_val, max_val, minLoc, maxLoc, null);
  38. // Get the Max or Min Correlation Value
  39. // System.out.println(Arrays.toString(min_val));
  40. // System.out.println(Arrays.toString(max_val));
  41. CvPoint point = new CvPoint();
  42. point.x(maxLoc.x() + tmp.width());
  43. point.y(maxLoc.y() + tmp.height());
  44. // cvMinMaxLoc(src, min_val, max_val,0,0,result);
  45. cvRectangle(src, maxLoc, point, CvScalar.RED, 2, 8, 0); // Draw a
  46. // Rectangle for
  47. // Matched
  48. // Region
  49. CvRect rect = new CvRect();
  50. rect.x(maxLoc.x());
  51. rect.y(maxLoc.y());
  52. rect.width(tmp.width() + width);
  53. rect.height(tmp.width() + height);
  54. cvSetImageROI(src, rect);
  55. IplImage imageNew = cvCreateImage(cvGetSize(src), src.depth(),
  56. src.nChannels());
  57. cvCopy(src, imageNew);
  58. cvSaveImage(args[2], imageNew);
  59. cvShowImage("Lena Image", src);
  60. cvWaitKey(0);
  61. cvReleaseImage(src);
  62. cvReleaseImage(tmp);
  63. cvReleaseImage(result);
  64. }
  65. }