HoughLinesPExample.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. /// HoughLinesP Example
  11. /// An example of straight line detection using the Imgproc.HoughLinesP function.
  12. /// http://docs.opencv.org/3.1.0/d9/db0/tutorial_hough_lines.html
  13. /// </summary>
  14. public class HoughLinesPExample : MonoBehaviour
  15. {
  16. // Use this for initialization
  17. void Start ()
  18. {
  19. Texture2D imgTexture = Resources.Load ("chessboard") as Texture2D;
  20. Mat imgMat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC3);
  21. Utils.texture2DToMat (imgTexture, imgMat);
  22. Debug.Log ("imgMat.ToString() " + imgMat.ToString ());
  23. Mat grayMat = new Mat ();
  24. Imgproc.cvtColor (imgMat, grayMat, Imgproc.COLOR_RGB2GRAY);
  25. Imgproc.Canny (grayMat, grayMat, 50, 200);
  26. Mat lines = new Mat ();
  27. Imgproc.HoughLinesP (grayMat, lines, 1, Mathf.PI / 180, 50, 50, 10);
  28. // Debug.Log ("lines.toStirng() " + lines.ToString ());
  29. // Debug.Log ("lines.dump()" + lines.dump ());
  30. int[] linesArray = new int[lines.cols () * lines.rows () * lines.channels ()];
  31. lines.get (0, 0, linesArray);
  32. for (int i = 0; i < linesArray.Length; i = i + 4) {
  33. Imgproc.line (imgMat, new Point (linesArray [i + 0], linesArray [i + 1]), new Point (linesArray [i + 2], linesArray [i + 3]), new Scalar (255, 0, 0), 2);
  34. }
  35. Texture2D texture = new Texture2D (imgMat.cols (), imgMat.rows (), TextureFormat.RGBA32, false);
  36. Utils.matToTexture2D (imgMat, texture);
  37. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  38. }
  39. // Update is called once per frame
  40. void Update ()
  41. {
  42. }
  43. /// <summary>
  44. /// Raises the back button click event.
  45. /// </summary>
  46. public void OnBackButtonClick ()
  47. {
  48. SceneManager.LoadScene ("OpenCVForUnityExample");
  49. }
  50. }
  51. }