ConvexHullExample.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using System.Collections.Generic;
  4. using OpenCVForUnity.CoreModule;
  5. using OpenCVForUnity.ImgprocModule;
  6. using OpenCVForUnity.UnityUtils;
  7. namespace OpenCVForUnityExample
  8. {
  9. /// <summary>
  10. /// ConvexHull Example
  11. /// http://docs.opencv.org/trunk/d7/d1d/tutorial_hull.html
  12. /// </summary>
  13. public class ConvexHullExample : MonoBehaviour
  14. {
  15. // Use this for initialization
  16. void Start ()
  17. {
  18. Mat imgMat = new Mat (500, 500, CvType.CV_8UC3, new Scalar (0, 0, 0));
  19. Debug.Log ("imgMat.ToString() " + imgMat.ToString ());
  20. int rand_num = 50;
  21. MatOfPoint pointsMat = new MatOfPoint ();
  22. pointsMat.alloc (rand_num);
  23. Core.randu (pointsMat, 100, 400);
  24. Point[] points = pointsMat.toArray ();
  25. for (int i = 0; i < rand_num; ++i) {
  26. Imgproc.circle (imgMat, points [i], 2, new Scalar (255, 255, 255), -1);
  27. }
  28. MatOfInt hullInt = new MatOfInt ();
  29. Imgproc.convexHull (pointsMat, hullInt);
  30. List<Point> pointMatList = pointsMat.toList ();
  31. List<int> hullIntList = hullInt.toList ();
  32. List<Point> hullPointList = new List<Point> ();
  33. for (int j = 0; j < hullInt.toList ().Count; j++) {
  34. hullPointList.Add (pointMatList [hullIntList [j]]);
  35. }
  36. MatOfPoint hullPointMat = new MatOfPoint ();
  37. hullPointMat.fromList (hullPointList);
  38. List<MatOfPoint> hullPoints = new List<MatOfPoint> ();
  39. hullPoints.Add (hullPointMat);
  40. Imgproc.drawContours (imgMat, hullPoints, -1, new Scalar (0, 255, 0), 2);
  41. Imgproc.cvtColor (imgMat, imgMat, Imgproc.COLOR_BGR2RGB);
  42. Texture2D texture = new Texture2D (imgMat.cols (), imgMat.rows (), TextureFormat.RGBA32, false);
  43. Utils.matToTexture2D (imgMat, texture);
  44. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  45. }
  46. // Update is called once per frame
  47. void Update ()
  48. {
  49. }
  50. /// <summary>
  51. /// Raises the back button click event.
  52. /// </summary>
  53. public void OnBackButtonClick ()
  54. {
  55. SceneManager.LoadScene ("OpenCVForUnityExample");
  56. }
  57. }
  58. }