StereoBMExample.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using System.Collections;
  4. using OpenCVForUnity.CoreModule;
  5. using OpenCVForUnity.Calib3dModule;
  6. using OpenCVForUnity.UnityUtils;
  7. using OpenCVForUnity.ImgcodecsModule;
  8. namespace OpenCVForUnityExample
  9. {
  10. /// <summary>
  11. /// StereoBM Example
  12. /// An example of stereo correspondence using the block matching algorithm.
  13. /// Referring to http://docs.opencv.org/trunk/tutorial_py_depthmap.html#gsc.tab=0.
  14. /// </summary>
  15. public class StereoBMExample : MonoBehaviour
  16. {
  17. // Use this for initialization
  18. void Start ()
  19. {
  20. //Read the left and right images
  21. Texture2D texLeft = Resources.Load ("tsukuba_l") as Texture2D;
  22. Texture2D texRight = Resources.Load ("tsukuba_r") as Texture2D;
  23. Mat imgLeft = new Mat (texLeft.height, texLeft.width, CvType.CV_8UC1);
  24. Mat imgRight = new Mat (texRight.height, texRight.width, CvType.CV_8UC1);
  25. Utils.texture2DToMat (texLeft, imgLeft);
  26. Utils.texture2DToMat (texRight, imgRight);
  27. //or
  28. //Mat imgLeft = Imgcodecs.imread (Utils.getFilePath ("tsukuba_l.png"), Imgcodecs.IMREAD_GRAYSCALE);
  29. //Mat imgRight = Imgcodecs.imread (Utils.getFilePath ("tsukuba_r.png"), Imgcodecs.IMREAD_GRAYSCALE);
  30. Mat imgDisparity16S = new Mat (imgLeft.rows (), imgLeft.cols (), CvType.CV_16S);
  31. Mat imgDisparity8U = new Mat (imgLeft.rows (), imgLeft.cols (), CvType.CV_8UC1);
  32. // if (imgLeft.empty () || imgRight.empty ()) {
  33. // Debug.Log ("Error reading images ");
  34. // }
  35. StereoBM sbm = StereoBM.create (16, 15);
  36. sbm.compute (imgLeft, imgRight, imgDisparity16S);
  37. //normalize to CvType.CV_8U
  38. Core.normalize (imgDisparity16S, imgDisparity8U, 0, 255, Core.NORM_MINMAX, CvType.CV_8U);
  39. Texture2D texture = new Texture2D (imgDisparity8U.cols (), imgDisparity8U.rows (), TextureFormat.RGBA32, false);
  40. Utils.matToTexture2D (imgDisparity8U, texture);
  41. gameObject.GetComponent<Renderer> ().material.mainTexture = texture;
  42. }
  43. // Update is called once per frame
  44. void Update ()
  45. {
  46. }
  47. /// <summary>
  48. /// Raises the back button click event.
  49. /// </summary>
  50. public void OnBackButtonClick ()
  51. {
  52. SceneManager.LoadScene ("OpenCVForUnityExample");
  53. }
  54. }
  55. }