Texture2DToMatExample.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using OpenCVForUnity.CoreModule;
  4. using OpenCVForUnity.UnityUtils;
  5. namespace OpenCVForUnityExample
  6. {
  7. /// <summary>
  8. /// Texture2DToMat Example
  9. /// An example of converting a Texture2D image to OpenCV's Mat format.
  10. /// </summary>
  11. public class Texture2DToMatExample : MonoBehaviour
  12. {
  13. // Use this for initialization
  14. void Start()
  15. {
  16. // if true, The error log of the Native side OpenCV will be displayed on the Unity Editor Console.
  17. Utils.setDebugMode(true);
  18. // Load the image texture from the Resources folder
  19. Texture2D imgTexture = Resources.Load("face") as Texture2D;
  20. // Create a new Mat object with the same dimensions and color format as the texture
  21. Mat imgMat = new Mat(imgTexture.height, imgTexture.width, CvType.CV_8UC4);
  22. // Convert the Texture2D image to Mat format
  23. Utils.texture2DToMat(imgTexture, imgMat);
  24. Debug.Log("imgMat.ToString() " + imgMat.ToString());
  25. // Create a new Texture2D with the same dimensions and color format as the Mat
  26. Texture2D texture = new Texture2D(imgMat.cols(), imgMat.rows(), TextureFormat.RGBA32, false);
  27. // Convert the Mat back to Texture2D format
  28. Utils.matToTexture2D(imgMat, texture);
  29. // Assign the created texture to the mainTexture of the game object's material
  30. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  31. Utils.setDebugMode(false);
  32. }
  33. // Update is called once per frame
  34. void Update()
  35. {
  36. // Update logic (not used in this example)
  37. }
  38. /// <summary>
  39. /// Raises the back button click event.
  40. /// </summary>
  41. public void OnBackButtonClick()
  42. {
  43. // Load the specified scene when the back button is clicked
  44. SceneManager.LoadScene("OpenCVForUnityExample");
  45. }
  46. }
  47. }