MatchTemplateExample.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using System.Collections;
  4. using OpenCVForUnity.CoreModule;
  5. using OpenCVForUnity.ImgprocModule;
  6. using OpenCVForUnity.UnityUtils;
  7. namespace OpenCVForUnityExample
  8. {
  9. /// <summary>
  10. /// MatchTemplate Example
  11. /// An example of template matching using the Imgproc.matchTemplate function.
  12. /// http://docs.opencv.org/3.2.0/de/da9/tutorial_template_matching.html
  13. /// </summary>
  14. public class MatchTemplateExample : MonoBehaviour
  15. {
  16. // Use this for initialization
  17. void Start ()
  18. {
  19. Texture2D imgTexture = Resources.Load ("lena") as Texture2D;
  20. Texture2D tempTexture = Resources.Load ("template") as Texture2D;
  21. Mat imgMat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC4);
  22. Mat tempMat = new Mat (tempTexture.height, tempTexture.width, CvType.CV_8UC4);
  23. Utils.texture2DToMat (imgTexture, imgMat);
  24. Utils.texture2DToMat (tempTexture, tempMat);
  25. //Create the result mat
  26. int result_cols = imgMat.cols () - tempMat.cols () + 1;
  27. int result_rows = imgMat.rows () - tempMat.rows () + 1;
  28. Mat result = new Mat (result_rows, result_cols, CvType.CV_32FC1);
  29. int match_method = Imgproc.TM_CCOEFF_NORMED;
  30. Imgproc.matchTemplate (imgMat, tempMat, result, match_method);
  31. Imgproc.threshold (result, result, 0.8, 1.0, Imgproc.THRESH_TOZERO);//threshold = 0.8
  32. for (int i = 0; i < result.rows (); i++) {
  33. for (int j = 0; j < result.cols (); j++) {
  34. if (result.get (i, j) [0] > 0) {
  35. Imgproc.rectangle (imgMat, new Point (j, i), new Point (j + tempMat.cols (), i + tempMat.rows ()), new Scalar (255, 0, 0, 255), 2);
  36. Debug.Log ("value" + result.get (i, j) [0]);
  37. }
  38. }
  39. }
  40. Texture2D texture = new Texture2D (imgMat.cols (), imgMat.rows (), TextureFormat.RGBA32, false);
  41. Utils.matToTexture2D (imgMat, texture);
  42. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  43. }
  44. // Update is called once per frame
  45. void Update ()
  46. {
  47. }
  48. /// <summary>
  49. /// Raises the back button click event.
  50. /// </summary>
  51. public void OnBackButtonClick ()
  52. {
  53. SceneManager.LoadScene ("OpenCVForUnityExample");
  54. }
  55. }
  56. }