MatchTemplateExample.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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("face") 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. {
  34. for (int j = 0; j < result.cols(); j++)
  35. {
  36. if (result.get(i, j)[0] > 0)
  37. {
  38. Imgproc.rectangle(imgMat, new Point(j, i), new Point(j + tempMat.cols(), i + tempMat.rows()), new Scalar(255, 0, 0, 255), 2);
  39. Debug.Log("value" + result.get(i, j)[0]);
  40. }
  41. }
  42. }
  43. Texture2D texture = new Texture2D(imgMat.cols(), imgMat.rows(), TextureFormat.RGBA32, false);
  44. Utils.matToTexture2D(imgMat, texture);
  45. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  46. }
  47. // Update is called once per frame
  48. void Update()
  49. {
  50. }
  51. /// <summary>
  52. /// Raises the back button click event.
  53. /// </summary>
  54. public void OnBackButtonClick()
  55. {
  56. SceneManager.LoadScene("OpenCVForUnityExample");
  57. }
  58. }
  59. }