WebCamTextureToMatExample.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. using OpenCVForUnity.CoreModule;
  2. using OpenCVForUnity.ImgprocModule;
  3. using OpenCVForUnity.UnityUtils;
  4. using System;
  5. using System.Collections;
  6. using UnityEngine;
  7. using UnityEngine.SceneManagement;
  8. namespace OpenCVForUnityExample
  9. {
  10. /// <summary>
  11. /// WebCamTextureToMat Example
  12. /// An example of converting a WebCamTexture image to OpenCV's Mat format.
  13. /// </summary>
  14. public class WebCamTextureToMatExample : MonoBehaviour
  15. {
  16. /// <summary>
  17. /// Set the name of the device to use.
  18. /// </summary>
  19. [SerializeField, TooltipAttribute("Set the name of the device to use.")]
  20. public string requestedDeviceName = null;
  21. /// <summary>
  22. /// Set the width of WebCamTexture.
  23. /// </summary>
  24. [SerializeField, TooltipAttribute("Set the width of WebCamTexture.")]
  25. public int requestedWidth = 640;
  26. /// <summary>
  27. /// Set the height of WebCamTexture.
  28. /// </summary>
  29. [SerializeField, TooltipAttribute("Set the height of WebCamTexture.")]
  30. public int requestedHeight = 480;
  31. /// <summary>
  32. /// Set FPS of WebCamTexture.
  33. /// </summary>
  34. [SerializeField, TooltipAttribute("Set FPS of WebCamTexture.")]
  35. public int requestedFPS = 30;
  36. /// <summary>
  37. /// Set whether to use the front facing camera.
  38. /// </summary>
  39. [SerializeField, TooltipAttribute("Set whether to use the front facing camera.")]
  40. public bool requestedIsFrontFacing = false;
  41. /// <summary>
  42. /// The webcam texture.
  43. /// </summary>
  44. WebCamTexture webCamTexture;
  45. /// <summary>
  46. /// The webcam device.
  47. /// </summary>
  48. WebCamDevice webCamDevice;
  49. /// <summary>
  50. /// The rgba mat.
  51. /// </summary>
  52. Mat rgbaMat;
  53. /// <summary>
  54. /// The colors.
  55. /// </summary>
  56. Color32[] colors;
  57. /// <summary>
  58. /// The texture.
  59. /// </summary>
  60. Texture2D texture;
  61. /// <summary>
  62. /// Indicates whether this instance is waiting for initialization to complete.
  63. /// </summary>
  64. bool isInitWaiting = false;
  65. /// <summary>
  66. /// Indicates whether this instance has been initialized.
  67. /// </summary>
  68. bool hasInitDone = false;
  69. /// <summary>
  70. /// The FPS monitor.
  71. /// </summary>
  72. FpsMonitor fpsMonitor;
  73. // Use this for initialization
  74. void Start()
  75. {
  76. fpsMonitor = GetComponent<FpsMonitor>();
  77. Initialize();
  78. }
  79. /// <summary>
  80. /// Initializes webcam texture.
  81. /// </summary>
  82. private void Initialize()
  83. {
  84. if (isInitWaiting)
  85. return;
  86. #if UNITY_ANDROID && !UNITY_EDITOR
  87. // Set the requestedFPS parameter to avoid the problem of the WebCamTexture image becoming low light on some Android devices (e.g. Google Pixel, Pixel2).
  88. // https://forum.unity.com/threads/android-webcamtexture-in-low-light-only-some-models.520656/
  89. // https://forum.unity.com/threads/released-opencv-for-unity.277080/page-33#post-3445178
  90. if (requestedIsFrontFacing)
  91. {
  92. int rearCameraFPS = requestedFPS;
  93. requestedFPS = 15;
  94. StartCoroutine(_Initialize());
  95. requestedFPS = rearCameraFPS;
  96. }
  97. else
  98. {
  99. StartCoroutine(_Initialize());
  100. }
  101. #else
  102. StartCoroutine(_Initialize());
  103. #endif
  104. }
  105. /// <summary>
  106. /// Initializes webcam texture by coroutine.
  107. /// </summary>
  108. private IEnumerator _Initialize()
  109. {
  110. if (hasInitDone)
  111. Dispose();
  112. isInitWaiting = true;
  113. // Checks camera permission state.
  114. #if (UNITY_IOS || UNITY_WEBGL) && UNITY_2018_1_OR_NEWER
  115. UserAuthorization mode = UserAuthorization.WebCam;
  116. if (!Application.HasUserAuthorization(mode))
  117. {
  118. isUserRequestingPermission = true;
  119. yield return Application.RequestUserAuthorization(mode);
  120. float timeElapsed = 0;
  121. while (isUserRequestingPermission)
  122. {
  123. if (timeElapsed > 0.25f)
  124. {
  125. isUserRequestingPermission = false;
  126. break;
  127. }
  128. timeElapsed += Time.deltaTime;
  129. yield return null;
  130. }
  131. }
  132. if (!Application.HasUserAuthorization(mode))
  133. {
  134. if (fpsMonitor != null)
  135. {
  136. fpsMonitor.consoleText = "Camera permission is denied.";
  137. }
  138. isInitWaiting = false;
  139. yield break;
  140. }
  141. #elif UNITY_ANDROID && UNITY_2018_3_OR_NEWER
  142. string permission = UnityEngine.Android.Permission.Camera;
  143. if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(permission))
  144. {
  145. isUserRequestingPermission = true;
  146. UnityEngine.Android.Permission.RequestUserPermission(permission);
  147. float timeElapsed = 0;
  148. while (isUserRequestingPermission)
  149. {
  150. if (timeElapsed > 0.25f)
  151. {
  152. isUserRequestingPermission = false;
  153. break;
  154. }
  155. timeElapsed += Time.deltaTime;
  156. yield return null;
  157. }
  158. }
  159. if (!UnityEngine.Android.Permission.HasUserAuthorizedPermission(permission))
  160. {
  161. if (fpsMonitor != null)
  162. {
  163. fpsMonitor.consoleText = "Camera permission is denied.";
  164. }
  165. isInitWaiting = false;
  166. yield break;
  167. }
  168. #endif
  169. // Creates the camera
  170. var devices = WebCamTexture.devices;
  171. if (!String.IsNullOrEmpty(requestedDeviceName))
  172. {
  173. int requestedDeviceIndex = -1;
  174. if (Int32.TryParse(requestedDeviceName, out requestedDeviceIndex))
  175. {
  176. if (requestedDeviceIndex >= 0 && requestedDeviceIndex < devices.Length)
  177. {
  178. webCamDevice = devices[requestedDeviceIndex];
  179. webCamTexture = new WebCamTexture(webCamDevice.name, requestedWidth, requestedHeight, requestedFPS);
  180. }
  181. }
  182. else
  183. {
  184. for (int cameraIndex = 0; cameraIndex < devices.Length; cameraIndex++)
  185. {
  186. if (devices[cameraIndex].name == requestedDeviceName)
  187. {
  188. webCamDevice = devices[cameraIndex];
  189. webCamTexture = new WebCamTexture(webCamDevice.name, requestedWidth, requestedHeight, requestedFPS);
  190. break;
  191. }
  192. }
  193. }
  194. if (webCamTexture == null)
  195. Debug.Log("Cannot find camera device " + requestedDeviceName + ".");
  196. }
  197. if (webCamTexture == null)
  198. {
  199. // Checks how many and which cameras are available on the device
  200. for (int cameraIndex = 0; cameraIndex < devices.Length; cameraIndex++)
  201. {
  202. #if UNITY_2018_3_OR_NEWER
  203. if (devices[cameraIndex].kind != WebCamKind.ColorAndDepth && devices[cameraIndex].isFrontFacing == requestedIsFrontFacing)
  204. #else
  205. if (devices[cameraIndex].isFrontFacing == requestedIsFrontFacing)
  206. #endif
  207. {
  208. webCamDevice = devices[cameraIndex];
  209. webCamTexture = new WebCamTexture(webCamDevice.name, requestedWidth, requestedHeight, requestedFPS);
  210. break;
  211. }
  212. }
  213. }
  214. if (webCamTexture == null)
  215. {
  216. if (devices.Length > 0)
  217. {
  218. webCamDevice = devices[0];
  219. webCamTexture = new WebCamTexture(webCamDevice.name, requestedWidth, requestedHeight, requestedFPS);
  220. }
  221. else
  222. {
  223. Debug.LogError("Camera device does not exist.");
  224. isInitWaiting = false;
  225. yield break;
  226. }
  227. }
  228. // Starts the camera.
  229. webCamTexture.Play();
  230. while (true)
  231. {
  232. if (webCamTexture.didUpdateThisFrame)
  233. {
  234. Debug.Log("name:" + webCamTexture.deviceName + " width:" + webCamTexture.width + " height:" + webCamTexture.height + " fps:" + webCamTexture.requestedFPS);
  235. Debug.Log("videoRotationAngle:" + webCamTexture.videoRotationAngle + " videoVerticallyMirrored:" + webCamTexture.videoVerticallyMirrored + " isFrongFacing:" + webCamDevice.isFrontFacing);
  236. isInitWaiting = false;
  237. hasInitDone = true;
  238. OnInited();
  239. break;
  240. }
  241. else
  242. {
  243. yield return null;
  244. }
  245. }
  246. }
  247. #if ((UNITY_IOS || UNITY_WEBGL) && UNITY_2018_1_OR_NEWER) || (UNITY_ANDROID && UNITY_2018_3_OR_NEWER)
  248. bool isUserRequestingPermission;
  249. IEnumerator OnApplicationFocus(bool hasFocus)
  250. {
  251. yield return null;
  252. if (isUserRequestingPermission && hasFocus)
  253. isUserRequestingPermission = false;
  254. }
  255. #endif
  256. /// <summary>
  257. /// Releases all resource.
  258. /// </summary>
  259. private void Dispose()
  260. {
  261. isInitWaiting = false;
  262. hasInitDone = false;
  263. if (webCamTexture != null)
  264. {
  265. webCamTexture.Stop();
  266. WebCamTexture.Destroy(webCamTexture);
  267. webCamTexture = null;
  268. }
  269. if (rgbaMat != null)
  270. {
  271. rgbaMat.Dispose();
  272. rgbaMat = null;
  273. }
  274. if (texture != null)
  275. {
  276. Texture2D.Destroy(texture);
  277. texture = null;
  278. }
  279. }
  280. /// <summary>
  281. /// Raises the webcam texture initialized event.
  282. /// </summary>
  283. private void OnInited()
  284. {
  285. if (colors == null || colors.Length != webCamTexture.width * webCamTexture.height)
  286. colors = new Color32[webCamTexture.width * webCamTexture.height];
  287. if (texture == null || texture.width != webCamTexture.width || texture.height != webCamTexture.height)
  288. texture = new Texture2D(webCamTexture.width, webCamTexture.height, TextureFormat.RGBA32, false);
  289. rgbaMat = new Mat(webCamTexture.height, webCamTexture.width, CvType.CV_8UC4, new Scalar(0, 0, 0, 255));
  290. Utils.matToTexture2D(rgbaMat, texture, colors);
  291. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  292. gameObject.transform.localScale = new Vector3(webCamTexture.width, webCamTexture.height, 1);
  293. Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);
  294. if (fpsMonitor != null)
  295. {
  296. fpsMonitor.Add("width", rgbaMat.width().ToString());
  297. fpsMonitor.Add("height", rgbaMat.height().ToString());
  298. fpsMonitor.Add("orientation", Screen.orientation.ToString());
  299. }
  300. float width = rgbaMat.width();
  301. float height = rgbaMat.height();
  302. float widthScale = (float)Screen.width / width;
  303. float heightScale = (float)Screen.height / height;
  304. if (widthScale < heightScale)
  305. {
  306. Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
  307. }
  308. else
  309. {
  310. Camera.main.orthographicSize = height / 2;
  311. }
  312. }
  313. // Update is called once per frame
  314. void Update()
  315. {
  316. if (hasInitDone && webCamTexture.isPlaying && webCamTexture.didUpdateThisFrame)
  317. {
  318. Utils.webCamTextureToMat(webCamTexture, rgbaMat, colors);
  319. //Imgproc.putText (rgbaMat, "W:" + rgbaMat.width () + " H:" + rgbaMat.height () + " SO:" + Screen.orientation, new Point (5, rgbaMat.rows () - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
  320. Utils.matToTexture2D(rgbaMat, texture, colors);
  321. }
  322. }
  323. /// <summary>
  324. /// Raises the destroy event.
  325. /// </summary>
  326. void OnDestroy()
  327. {
  328. Dispose();
  329. }
  330. /// <summary>
  331. /// Raises the back button click event.
  332. /// </summary>
  333. public void OnBackButtonClick()
  334. {
  335. SceneManager.LoadScene("OpenCVForUnityExample");
  336. }
  337. /// <summary>
  338. /// Raises the play button click event.
  339. /// </summary>
  340. public void OnPlayButtonClick()
  341. {
  342. if (hasInitDone)
  343. webCamTexture.Play();
  344. }
  345. /// <summary>
  346. /// Raises the pause button click event.
  347. /// </summary>
  348. public void OnPauseButtonClick()
  349. {
  350. if (hasInitDone)
  351. webCamTexture.Pause();
  352. }
  353. /// <summary>
  354. /// Raises the stop button click event.
  355. /// </summary>
  356. public void OnStopButtonClick()
  357. {
  358. if (hasInitDone)
  359. webCamTexture.Stop();
  360. }
  361. /// <summary>
  362. /// Raises the change camera button click event.
  363. /// </summary>
  364. public void OnChangeCameraButtonClick()
  365. {
  366. if (hasInitDone)
  367. {
  368. requestedDeviceName = null;
  369. requestedIsFrontFacing = !requestedIsFrontFacing;
  370. Initialize();
  371. }
  372. }
  373. }
  374. }