HoughLinesPExample.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. {
  34. 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);
  35. }
  36. Texture2D texture = new Texture2D(imgMat.cols(), imgMat.rows(), TextureFormat.RGBA32, false);
  37. Utils.matToTexture2D(imgMat, texture);
  38. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  39. }
  40. // Update is called once per frame
  41. void Update()
  42. {
  43. }
  44. /// <summary>
  45. /// Raises the back button click event.
  46. /// </summary>
  47. public void OnBackButtonClick()
  48. {
  49. SceneManager.LoadScene("OpenCVForUnityExample");
  50. }
  51. }
  52. }