Feature2DExample.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using System.Collections;
  4. using OpenCVForUnity.CoreModule;
  5. using OpenCVForUnity.ImgprocModule;
  6. using OpenCVForUnity.Features2dModule;
  7. using OpenCVForUnity.UnityUtils;
  8. namespace OpenCVForUnityExample
  9. {
  10. /// <summary>
  11. /// Feature2D Example
  12. /// An example of descriptor extraction and descriptor matching.
  13. /// http://docs.opencv.org/3.1.0/d5/dde/tutorial_feature_description.html
  14. /// </summary>
  15. public class Feature2DExample : MonoBehaviour
  16. {
  17. // Use this for initialization
  18. void Start ()
  19. {
  20. Texture2D imgTexture = Resources.Load ("lena") as Texture2D;
  21. Mat img1Mat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC3);
  22. Utils.texture2DToMat (imgTexture, img1Mat);
  23. Debug.Log ("img1Mat.ToString() " + img1Mat.ToString ());
  24. Mat img2Mat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC3);
  25. Utils.texture2DToMat (imgTexture, img2Mat);
  26. Debug.Log ("img2Mat.ToString() " + img2Mat.ToString ());
  27. float angle = UnityEngine.Random.Range (0, 360), scale = 1.0f;
  28. Point center = new Point (img2Mat.cols () * 0.5f, img2Mat.rows () * 0.5f);
  29. Mat affine_matrix = Imgproc.getRotationMatrix2D (center, angle, scale);
  30. Imgproc.warpAffine (img1Mat, img2Mat, affine_matrix, img2Mat.size ());
  31. ORB detector = ORB.create ();
  32. ORB extractor = ORB.create ();
  33. MatOfKeyPoint keypoints1 = new MatOfKeyPoint ();
  34. Mat descriptors1 = new Mat ();
  35. detector.detect (img1Mat, keypoints1);
  36. extractor.compute (img1Mat, keypoints1, descriptors1);
  37. MatOfKeyPoint keypoints2 = new MatOfKeyPoint ();
  38. Mat descriptors2 = new Mat ();
  39. detector.detect (img2Mat, keypoints2);
  40. extractor.compute (img2Mat, keypoints2, descriptors2);
  41. DescriptorMatcher matcher = DescriptorMatcher.create (DescriptorMatcher.BRUTEFORCE_HAMMINGLUT);
  42. MatOfDMatch matches = new MatOfDMatch ();
  43. matcher.match (descriptors1, descriptors2, matches);
  44. Mat resultImg = new Mat ();
  45. Features2d.drawMatches (img1Mat, keypoints1, img2Mat, keypoints2, matches, resultImg);
  46. Texture2D texture = new Texture2D (resultImg.cols (), resultImg.rows (), TextureFormat.RGBA32, false);
  47. Utils.matToTexture2D (resultImg, texture);
  48. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  49. }
  50. // Update is called once per frame
  51. void Update ()
  52. {
  53. }
  54. /// <summary>
  55. /// Raises the back button click event.
  56. /// </summary>
  57. public void OnBackButtonClick ()
  58. {
  59. SceneManager.LoadScene ("OpenCVForUnityExample");
  60. }
  61. }
  62. }