WebCamTextureToMatHelper.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. using System;
  2. using System.Collections;
  3. using UnityEngine;
  4. using UnityEngine.Events;
  5. using UnityEngine.Serialization;
  6. using OpenCVForUnity.CoreModule;
  7. using OpenCVForUnity.UnityUtils;
  8. namespace OpenCVForUnity.UnityUtils.Helper
  9. {
  10. /// <summary>
  11. /// WebcamTexture to mat helper.
  12. /// v 1.1.0
  13. /// </summary>
  14. public class WebCamTextureToMatHelper : MonoBehaviour
  15. {
  16. /// <summary>
  17. /// Set the name of the camera device to use. (or device index number)
  18. /// </summary>
  19. [SerializeField, FormerlySerializedAs ("requestedDeviceName"), TooltipAttribute ("Set the name of the device to use. (or device index number)")]
  20. protected string _requestedDeviceName = null;
  21. public virtual string requestedDeviceName {
  22. get { return _requestedDeviceName; }
  23. set {
  24. _requestedDeviceName = value;
  25. if (hasInitDone) {
  26. Initialize ();
  27. }
  28. }
  29. }
  30. /// <summary>
  31. /// Set the width of camera.
  32. /// </summary>
  33. [SerializeField, FormerlySerializedAs ("requestedWidth"), TooltipAttribute ("Set the width of camera.")]
  34. protected int _requestedWidth = 640;
  35. public virtual int requestedWidth {
  36. get { return _requestedWidth; }
  37. set {
  38. _requestedWidth = (int)Mathf.Clamp (value, 0f, float.MaxValue);
  39. if (hasInitDone) {
  40. Initialize ();
  41. }
  42. }
  43. }
  44. /// <summary>
  45. /// Set the height of camera.
  46. /// </summary>
  47. [SerializeField, FormerlySerializedAs ("requestedHeight"), TooltipAttribute ("Set the height of camera.")]
  48. protected int _requestedHeight = 480;
  49. public virtual int requestedHeight {
  50. get { return _requestedHeight; }
  51. set {
  52. _requestedHeight = (int)Mathf.Clamp (value, 0f, float.MaxValue);
  53. if (hasInitDone) {
  54. Initialize ();
  55. }
  56. }
  57. }
  58. /// <summary>
  59. /// Set whether to use the front facing camera.
  60. /// </summary>
  61. [SerializeField, FormerlySerializedAs ("requestedIsFrontFacing"), TooltipAttribute ("Set whether to use the front facing camera.")]
  62. protected bool _requestedIsFrontFacing = false;
  63. public virtual bool requestedIsFrontFacing {
  64. get { return _requestedIsFrontFacing; }
  65. set {
  66. _requestedIsFrontFacing = value;
  67. if (hasInitDone) {
  68. Initialize (_requestedIsFrontFacing, requestedFPS, rotate90Degree);
  69. }
  70. }
  71. }
  72. /// <summary>
  73. /// Set the frame rate of camera.
  74. /// </summary>
  75. [SerializeField, FormerlySerializedAs ("requestedFPS"), TooltipAttribute ("Set the frame rate of camera.")]
  76. protected float _requestedFPS = 30f;
  77. public virtual float requestedFPS {
  78. get { return _requestedFPS; }
  79. set {
  80. _requestedFPS = Mathf.Clamp (value, -1f, float.MaxValue);
  81. if (hasInitDone) {
  82. bool isPlaying = IsPlaying ();
  83. Stop ();
  84. webCamTexture.requestedFPS = _requestedFPS;
  85. if (isPlaying)
  86. Play ();
  87. }
  88. }
  89. }
  90. /// <summary>
  91. /// Sets whether to rotate camera frame 90 degrees. (clockwise)
  92. /// </summary>
  93. [SerializeField, FormerlySerializedAs ("rotate90Degree"), TooltipAttribute ("Sets whether to rotate camera frame 90 degrees. (clockwise)")]
  94. protected bool _rotate90Degree = false;
  95. public virtual bool rotate90Degree {
  96. get { return _rotate90Degree; }
  97. set {
  98. _rotate90Degree = value;
  99. if (hasInitDone) {
  100. Initialize ();
  101. }
  102. }
  103. }
  104. /// <summary>
  105. /// Determines if flips vertically.
  106. /// </summary>
  107. [SerializeField, FormerlySerializedAs ("flipVertical"), TooltipAttribute ("Determines if flips vertically.")]
  108. protected bool _flipVertical = false;
  109. public virtual bool flipVertical {
  110. get { return _flipVertical; }
  111. set { _flipVertical = value; }
  112. }
  113. /// <summary>
  114. /// Determines if flips horizontal.
  115. /// </summary>
  116. [SerializeField, FormerlySerializedAs ("flipHorizontal"), TooltipAttribute ("Determines if flips horizontal.")]
  117. protected bool _flipHorizontal = false;
  118. public virtual bool flipHorizontal {
  119. get { return _flipHorizontal; }
  120. set { _flipHorizontal = value; }
  121. }
  122. /// <summary>
  123. /// The number of frames before the initialization process times out.
  124. /// </summary>
  125. [SerializeField, FormerlySerializedAs ("timeoutFrameCount"), TooltipAttribute ("The number of frames before the initialization process times out.")]
  126. protected int _timeoutFrameCount = 300;
  127. public virtual int timeoutFrameCount {
  128. get { return _timeoutFrameCount; }
  129. set { _timeoutFrameCount = (int)Mathf.Clamp (value, 0f, float.MaxValue); }
  130. }
  131. /// <summary>
  132. /// UnityEvent that is triggered when this instance is initialized.
  133. /// </summary>
  134. public UnityEvent onInitialized;
  135. /// <summary>
  136. /// UnityEvent that is triggered when this instance is disposed.
  137. /// </summary>
  138. public UnityEvent onDisposed;
  139. /// <summary>
  140. /// UnityEvent that is triggered when this instance is error Occurred.
  141. /// </summary>
  142. public ErrorUnityEvent onErrorOccurred;
  143. /// <summary>
  144. /// The active WebcamTexture.
  145. /// </summary>
  146. protected WebCamTexture webCamTexture;
  147. /// <summary>
  148. /// The active WebcamDevice.
  149. /// </summary>
  150. protected WebCamDevice webCamDevice;
  151. /// <summary>
  152. /// The frame mat.
  153. /// </summary>
  154. protected Mat frameMat;
  155. /// <summary>
  156. /// The rotated frame mat
  157. /// </summary>
  158. protected Mat rotatedFrameMat;
  159. /// <summary>
  160. /// The buffer colors.
  161. /// </summary>
  162. protected Color32[] colors;
  163. /// <summary>
  164. /// Indicates whether this instance is waiting for initialization to complete.
  165. /// </summary>
  166. protected bool isInitWaiting = false;
  167. /// <summary>
  168. /// Indicates whether this instance has been initialized.
  169. /// </summary>
  170. protected bool hasInitDone = false;
  171. /// <summary>
  172. /// The initialization coroutine.
  173. /// </summary>
  174. protected IEnumerator initCoroutine;
  175. /// <summary>
  176. /// The orientation of the screen.
  177. /// </summary>
  178. protected ScreenOrientation screenOrientation;
  179. /// <summary>
  180. /// The width of the screen.
  181. /// </summary>
  182. protected int screenWidth;
  183. /// <summary>
  184. /// The height of the screen.
  185. /// </summary>
  186. protected int screenHeight;
  187. /// <summary>
  188. /// Indicates whether this instance avoids the front camera low light issue that occurs in only some Android devices (e.g. Google Pixel, Pixel2).
  189. /// Sets compulsorily the requestedFPS parameter to 15 (only when using the front camera), to avoid the problem of the WebCamTexture image becoming low light.
  190. /// https://forum.unity.com/threads/android-webcamtexture-in-low-light-only-some-models.520656/
  191. /// https://forum.unity.com/threads/released-opencv-for-unity.277080/page-33#post-3445178
  192. /// </summary>
  193. public bool avoidAndroidFrontCameraLowLightIssue = false;
  194. [System.Serializable]
  195. public enum ErrorCode : int
  196. {
  197. UNKNOWN = 0,
  198. CAMERA_DEVICE_NOT_EXIST = 1,
  199. TIMEOUT = 2,
  200. }
  201. [System.Serializable]
  202. public class ErrorUnityEvent : UnityEngine.Events.UnityEvent<ErrorCode>
  203. {
  204. }
  205. protected virtual void OnValidate ()
  206. {
  207. _requestedWidth = (int)Mathf.Clamp (_requestedWidth, 0f, float.MaxValue);
  208. _requestedHeight = (int)Mathf.Clamp (_requestedHeight, 0f, float.MaxValue);
  209. _requestedFPS = Mathf.Clamp (_requestedFPS, -1f, float.MaxValue);
  210. _timeoutFrameCount = (int)Mathf.Clamp (_timeoutFrameCount, 0f, float.MaxValue);
  211. }
  212. // Update is called once per frame
  213. protected virtual void Update ()
  214. {
  215. if (hasInitDone) {
  216. // Catch the orientation change of the screen and correct the mat image to the correct direction.
  217. if (screenOrientation != Screen.orientation && (screenWidth != Screen.width || screenHeight != Screen.height)) {
  218. if (onDisposed != null)
  219. onDisposed.Invoke ();
  220. if (frameMat != null) {
  221. frameMat.Dispose ();
  222. frameMat = null;
  223. }
  224. if (rotatedFrameMat != null) {
  225. rotatedFrameMat.Dispose ();
  226. rotatedFrameMat = null;
  227. }
  228. frameMat = new Mat (webCamTexture.height, webCamTexture.width, CvType.CV_8UC4, new Scalar (0, 0, 0, 255));
  229. screenOrientation = Screen.orientation;
  230. screenWidth = Screen.width;
  231. screenHeight = Screen.height;
  232. bool isRotatedFrame = false;
  233. #if !UNITY_EDITOR && !(UNITY_STANDALONE || UNITY_WEBGL)
  234. if (screenOrientation == ScreenOrientation.Portrait || screenOrientation == ScreenOrientation.PortraitUpsideDown)
  235. {
  236. if (!rotate90Degree)
  237. isRotatedFrame = true;
  238. }
  239. else if (rotate90Degree)
  240. {
  241. isRotatedFrame = true;
  242. }
  243. #else
  244. if (rotate90Degree)
  245. isRotatedFrame = true;
  246. #endif
  247. if (isRotatedFrame)
  248. rotatedFrameMat = new Mat (webCamTexture.width, webCamTexture.height, CvType.CV_8UC4, new Scalar (0, 0, 0, 255));
  249. if (onInitialized != null)
  250. onInitialized.Invoke ();
  251. } else {
  252. screenWidth = Screen.width;
  253. screenHeight = Screen.height;
  254. }
  255. }
  256. }
  257. /// <summary>
  258. /// Raises the destroy event.
  259. /// </summary>
  260. protected virtual void OnDestroy ()
  261. {
  262. Dispose ();
  263. }
  264. /// <summary>
  265. /// Initializes this instance.
  266. /// </summary>
  267. public virtual void Initialize ()
  268. {
  269. if (isInitWaiting) {
  270. CancelInitCoroutine ();
  271. ReleaseResources ();
  272. }
  273. if (onInitialized == null)
  274. onInitialized = new UnityEvent ();
  275. if (onDisposed == null)
  276. onDisposed = new UnityEvent ();
  277. if (onErrorOccurred == null)
  278. onErrorOccurred = new ErrorUnityEvent ();
  279. initCoroutine = _Initialize ();
  280. StartCoroutine (initCoroutine);
  281. }
  282. /// <summary>
  283. /// Initializes this instance.
  284. /// </summary>
  285. /// <param name="requestedWidth">Requested width.</param>
  286. /// <param name="requestedHeight">Requested height.</param>
  287. public virtual void Initialize (int requestedWidth, int requestedHeight)
  288. {
  289. if (isInitWaiting) {
  290. CancelInitCoroutine ();
  291. ReleaseResources ();
  292. }
  293. this._requestedWidth = requestedWidth;
  294. this._requestedHeight = requestedHeight;
  295. if (onInitialized == null)
  296. onInitialized = new UnityEvent ();
  297. if (onDisposed == null)
  298. onDisposed = new UnityEvent ();
  299. if (onErrorOccurred == null)
  300. onErrorOccurred = new ErrorUnityEvent ();
  301. initCoroutine = _Initialize ();
  302. StartCoroutine (initCoroutine);
  303. }
  304. /// <summary>
  305. /// Initializes this instance.
  306. /// </summary>
  307. /// <param name="requestedIsFrontFacing">If set to <c>true</c> requested to using the front camera.</param>
  308. /// <param name="requestedFPS">Requested FPS.</param>
  309. /// <param name="rotate90Degree">If set to <c>true</c> requested to rotate camera frame 90 degrees. (clockwise)</param>
  310. public virtual void Initialize (bool requestedIsFrontFacing, float requestedFPS = 30f, bool rotate90Degree = false)
  311. {
  312. if (isInitWaiting) {
  313. CancelInitCoroutine ();
  314. ReleaseResources ();
  315. }
  316. _requestedDeviceName = null;
  317. this._requestedIsFrontFacing = requestedIsFrontFacing;
  318. this._requestedFPS = requestedFPS;
  319. this._rotate90Degree = rotate90Degree;
  320. if (onInitialized == null)
  321. onInitialized = new UnityEvent ();
  322. if (onDisposed == null)
  323. onDisposed = new UnityEvent ();
  324. if (onErrorOccurred == null)
  325. onErrorOccurred = new ErrorUnityEvent ();
  326. initCoroutine = _Initialize ();
  327. StartCoroutine (initCoroutine);
  328. }
  329. /// <summary>
  330. /// Initializes this instance.
  331. /// </summary>
  332. /// <param name="deviceName">Device name.</param>
  333. /// <param name="requestedWidth">Requested width.</param>
  334. /// <param name="requestedHeight">Requested height.</param>
  335. /// <param name="requestedIsFrontFacing">If set to <c>true</c> requested to using the front camera.</param>
  336. /// <param name="requestedFPS">Requested FPS.</param>
  337. /// <param name="rotate90Degree">If set to <c>true</c> requested to rotate camera frame 90 degrees. (clockwise)</param>
  338. public virtual void Initialize (string deviceName, int requestedWidth, int requestedHeight, bool requestedIsFrontFacing = false, float requestedFPS = 30f, bool rotate90Degree = false)
  339. {
  340. if (isInitWaiting) {
  341. CancelInitCoroutine ();
  342. ReleaseResources ();
  343. }
  344. this._requestedDeviceName = deviceName;
  345. this._requestedWidth = requestedWidth;
  346. this._requestedHeight = requestedHeight;
  347. this._requestedIsFrontFacing = requestedIsFrontFacing;
  348. this._requestedFPS = requestedFPS;
  349. this._rotate90Degree = rotate90Degree;
  350. if (onInitialized == null)
  351. onInitialized = new UnityEvent ();
  352. if (onDisposed == null)
  353. onDisposed = new UnityEvent ();
  354. if (onErrorOccurred == null)
  355. onErrorOccurred = new ErrorUnityEvent ();
  356. initCoroutine = _Initialize ();
  357. StartCoroutine (initCoroutine);
  358. }
  359. /// <summary>
  360. /// Initializes this instance by coroutine.
  361. /// </summary>
  362. protected virtual IEnumerator _Initialize ()
  363. {
  364. if (hasInitDone) {
  365. ReleaseResources ();
  366. if (onDisposed != null)
  367. onDisposed.Invoke ();
  368. }
  369. isInitWaiting = true;
  370. float requestedFPS = this.requestedFPS;
  371. // Creates the camera
  372. if (!String.IsNullOrEmpty (requestedDeviceName)) {
  373. int requestedDeviceIndex = -1;
  374. if (Int32.TryParse (requestedDeviceName, out requestedDeviceIndex)) {
  375. if (requestedDeviceIndex >= 0 && requestedDeviceIndex < WebCamTexture.devices.Length) {
  376. webCamDevice = WebCamTexture.devices [requestedDeviceIndex];
  377. if (avoidAndroidFrontCameraLowLightIssue && webCamDevice.isFrontFacing == true)
  378. requestedFPS = 15f;
  379. if (requestedFPS < 0) {
  380. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight);
  381. } else {
  382. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight, (int)requestedFPS);
  383. }
  384. }
  385. } else {
  386. for (int cameraIndex = 0; cameraIndex < WebCamTexture.devices.Length; cameraIndex++) {
  387. if (WebCamTexture.devices [cameraIndex].name == requestedDeviceName) {
  388. webCamDevice = WebCamTexture.devices [cameraIndex];
  389. if (avoidAndroidFrontCameraLowLightIssue && webCamDevice.isFrontFacing == true)
  390. requestedFPS = 15f;
  391. if (requestedFPS < 0) {
  392. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight);
  393. } else {
  394. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight, (int)requestedFPS);
  395. }
  396. break;
  397. }
  398. }
  399. }
  400. if (webCamTexture == null)
  401. Debug.Log ("Cannot find camera device " + requestedDeviceName + ".");
  402. }
  403. if (webCamTexture == null) {
  404. // Checks how many and which cameras are available on the device
  405. for (int cameraIndex = 0; cameraIndex < WebCamTexture.devices.Length; cameraIndex++) {
  406. if (WebCamTexture.devices [cameraIndex].isFrontFacing == requestedIsFrontFacing) {
  407. webCamDevice = WebCamTexture.devices [cameraIndex];
  408. if (avoidAndroidFrontCameraLowLightIssue && webCamDevice.isFrontFacing == true)
  409. requestedFPS = 15f;
  410. if (requestedFPS < 0) {
  411. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight);
  412. } else {
  413. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight, (int)requestedFPS);
  414. }
  415. break;
  416. }
  417. }
  418. }
  419. if (webCamTexture == null) {
  420. if (WebCamTexture.devices.Length > 0) {
  421. webCamDevice = WebCamTexture.devices [0];
  422. if (avoidAndroidFrontCameraLowLightIssue && webCamDevice.isFrontFacing == true)
  423. requestedFPS = 15f;
  424. if (requestedFPS < 0) {
  425. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight);
  426. } else {
  427. webCamTexture = new WebCamTexture (webCamDevice.name, requestedWidth, requestedHeight, (int)requestedFPS);
  428. }
  429. } else {
  430. isInitWaiting = false;
  431. if (onErrorOccurred != null)
  432. onErrorOccurred.Invoke (ErrorCode.CAMERA_DEVICE_NOT_EXIST);
  433. yield break;
  434. }
  435. }
  436. // Starts the camera
  437. webCamTexture.Play ();
  438. int initFrameCount = 0;
  439. bool isTimeout = false;
  440. while (true) {
  441. if (initFrameCount > timeoutFrameCount) {
  442. isTimeout = true;
  443. break;
  444. }
  445. // If you want to use webcamTexture.width and webcamTexture.height on iOS, you have to wait until webcamTexture.didUpdateThisFrame == 1, otherwise these two values will be equal to 16. (http://forum.unity3d.com/threads/webcamtexture-and-error-0x0502.123922/)
  446. #if UNITY_IOS && !UNITY_EDITOR && (UNITY_4_6_3 || UNITY_4_6_4 || UNITY_5_0_0 || UNITY_5_0_1)
  447. else if (webCamTexture.width > 16 && webCamTexture.height > 16) {
  448. #else
  449. else if (webCamTexture.didUpdateThisFrame) {
  450. #if UNITY_IOS && !UNITY_EDITOR && UNITY_5_2
  451. while (webCamTexture.width <= 16) {
  452. if (initFrameCount > timeoutFrameCount) {
  453. isTimeout = true;
  454. break;
  455. }else {
  456. initFrameCount++;
  457. }
  458. webCamTexture.GetPixels32 ();
  459. yield return new WaitForEndOfFrame ();
  460. }
  461. if (isTimeout) break;
  462. #endif
  463. #endif
  464. Debug.Log ("WebCamTextureToMatHelper:: " + "devicename:" + webCamTexture.deviceName + " name:" + webCamTexture.name + " width:" + webCamTexture.width + " height:" + webCamTexture.height + " fps:" + webCamTexture.requestedFPS
  465. + " videoRotationAngle:" + webCamTexture.videoRotationAngle + " videoVerticallyMirrored:" + webCamTexture.videoVerticallyMirrored + " isFrongFacing:" + webCamDevice.isFrontFacing);
  466. if (colors == null || colors.Length != webCamTexture.width * webCamTexture.height)
  467. colors = new Color32[webCamTexture.width * webCamTexture.height];
  468. frameMat = new Mat (webCamTexture.height, webCamTexture.width, CvType.CV_8UC4);
  469. screenOrientation = Screen.orientation;
  470. screenWidth = Screen.width;
  471. screenHeight = Screen.height;
  472. bool isRotatedFrame = false;
  473. #if !UNITY_EDITOR && !(UNITY_STANDALONE || UNITY_WEBGL)
  474. if (screenOrientation == ScreenOrientation.Portrait || screenOrientation == ScreenOrientation.PortraitUpsideDown)
  475. {
  476. if (!rotate90Degree)
  477. isRotatedFrame = true;
  478. }
  479. else if (rotate90Degree)
  480. {
  481. isRotatedFrame = true;
  482. }
  483. #else
  484. if (rotate90Degree)
  485. isRotatedFrame = true;
  486. #endif
  487. if (isRotatedFrame)
  488. rotatedFrameMat = new Mat (webCamTexture.width, webCamTexture.height, CvType.CV_8UC4);
  489. isInitWaiting = false;
  490. hasInitDone = true;
  491. initCoroutine = null;
  492. if (onInitialized != null)
  493. onInitialized.Invoke ();
  494. break;
  495. } else {
  496. initFrameCount++;
  497. yield return null;
  498. }
  499. }
  500. if (isTimeout) {
  501. webCamTexture.Stop ();
  502. webCamTexture = null;
  503. isInitWaiting = false;
  504. initCoroutine = null;
  505. if (onErrorOccurred != null)
  506. onErrorOccurred.Invoke (ErrorCode.TIMEOUT);
  507. }
  508. }
  509. /// <summary>
  510. /// Indicates whether this instance has been initialized.
  511. /// </summary>
  512. /// <returns><c>true</c>, if this instance has been initialized, <c>false</c> otherwise.</returns>
  513. public virtual bool IsInitialized ()
  514. {
  515. return hasInitDone;
  516. }
  517. /// <summary>
  518. /// Starts the camera.
  519. /// </summary>
  520. public virtual void Play ()
  521. {
  522. if (hasInitDone)
  523. webCamTexture.Play ();
  524. }
  525. /// <summary>
  526. /// Pauses the active camera.
  527. /// </summary>
  528. public virtual void Pause ()
  529. {
  530. if (hasInitDone)
  531. webCamTexture.Pause ();
  532. }
  533. /// <summary>
  534. /// Stops the active camera.
  535. /// </summary>
  536. public virtual void Stop ()
  537. {
  538. if (hasInitDone)
  539. webCamTexture.Stop ();
  540. }
  541. /// <summary>
  542. /// Indicates whether the active camera is currently playing.
  543. /// </summary>
  544. /// <returns><c>true</c>, if the active camera is playing, <c>false</c> otherwise.</returns>
  545. public virtual bool IsPlaying ()
  546. {
  547. return hasInitDone ? webCamTexture.isPlaying : false;
  548. }
  549. /// <summary>
  550. /// Indicates whether the active camera device is currently front facng.
  551. /// </summary>
  552. /// <returns><c>true</c>, if the active camera device is front facng, <c>false</c> otherwise.</returns>
  553. public virtual bool IsFrontFacing ()
  554. {
  555. return hasInitDone ? webCamDevice.isFrontFacing : false;
  556. }
  557. /// <summary>
  558. /// Returns the active camera device name.
  559. /// </summary>
  560. /// <returns>The active camera device name.</returns>
  561. public virtual string GetDeviceName ()
  562. {
  563. return hasInitDone ? webCamTexture.deviceName : "";
  564. }
  565. /// <summary>
  566. /// Returns the active camera width.
  567. /// </summary>
  568. /// <returns>The active camera width.</returns>
  569. public virtual int GetWidth ()
  570. {
  571. if (!hasInitDone)
  572. return -1;
  573. return (rotatedFrameMat != null) ? frameMat.height () : frameMat.width ();
  574. }
  575. /// <summary>
  576. /// Returns the active camera height.
  577. /// </summary>
  578. /// <returns>The active camera height.</returns>
  579. public virtual int GetHeight ()
  580. {
  581. if (!hasInitDone)
  582. return -1;
  583. return (rotatedFrameMat != null) ? frameMat.width () : frameMat.height ();
  584. }
  585. /// <summary>
  586. /// Returns the active camera framerate.
  587. /// </summary>
  588. /// <returns>The active camera framerate.</returns>
  589. public virtual float GetFPS ()
  590. {
  591. return hasInitDone ? webCamTexture.requestedFPS : -1f;
  592. }
  593. /// <summary>
  594. /// Returns the active WebcamTexture.
  595. /// </summary>
  596. /// <returns>The active WebcamTexture.</returns>
  597. public virtual WebCamTexture GetWebCamTexture ()
  598. {
  599. return hasInitDone ? webCamTexture : null;
  600. }
  601. /// <summary>
  602. /// Returns the active WebcamDevice.
  603. /// </summary>
  604. /// <returns>The active WebcamDevice.</returns>
  605. public virtual WebCamDevice GetWebCamDevice ()
  606. {
  607. return webCamDevice;
  608. }
  609. /// <summary>
  610. /// Returns the camera to world matrix.
  611. /// </summary>
  612. /// <returns>The camera to world matrix.</returns>
  613. public virtual Matrix4x4 GetCameraToWorldMatrix ()
  614. {
  615. return Camera.main.cameraToWorldMatrix;
  616. }
  617. /// <summary>
  618. /// Returns the projection matrix matrix.
  619. /// </summary>
  620. /// <returns>The projection matrix.</returns>
  621. public virtual Matrix4x4 GetProjectionMatrix ()
  622. {
  623. return Camera.main.projectionMatrix;
  624. }
  625. /// <summary>
  626. /// Indicates whether the video buffer of the frame has been updated.
  627. /// </summary>
  628. /// <returns><c>true</c>, if the video buffer has been updated <c>false</c> otherwise.</returns>
  629. public virtual bool DidUpdateThisFrame ()
  630. {
  631. if (!hasInitDone)
  632. return false;
  633. #if UNITY_IOS && !UNITY_EDITOR && (UNITY_4_6_3 || UNITY_4_6_4 || UNITY_5_0_0 || UNITY_5_0_1)
  634. if (webCamTexture.width > 16 && webCamTexture.height > 16) {
  635. return true;
  636. } else {
  637. return false;
  638. }
  639. #else
  640. return webCamTexture.didUpdateThisFrame;
  641. #endif
  642. }
  643. /// <summary>
  644. /// Gets the mat of the current frame.
  645. /// The Mat object's type is 'CV_8UC4' (RGBA).
  646. /// </summary>
  647. /// <returns>The mat of the current frame.</returns>
  648. public virtual Mat GetMat ()
  649. {
  650. if (!hasInitDone || !webCamTexture.isPlaying) {
  651. return (rotatedFrameMat != null) ? rotatedFrameMat : frameMat;
  652. }
  653. Utils.webCamTextureToMat (webCamTexture, frameMat, colors, false);
  654. #if !UNITY_EDITOR && !(UNITY_STANDALONE || UNITY_WEBGL)
  655. if (rotatedFrameMat != null)
  656. {
  657. if (screenOrientation == ScreenOrientation.Portrait || screenOrientation == ScreenOrientation.PortraitUpsideDown)
  658. {
  659. // (Orientation is Portrait, rotate90Degree is false)
  660. if (webCamDevice.isFrontFacing)
  661. {
  662. FlipMat (frameMat, !flipHorizontal, !flipVertical);
  663. }
  664. else
  665. {
  666. FlipMat (frameMat, flipHorizontal, flipVertical);
  667. }
  668. }
  669. else
  670. {
  671. // (Orientation is Landscape, rotate90Degrees=true)
  672. FlipMat (frameMat, flipVertical, flipHorizontal);
  673. }
  674. Core.rotate (frameMat, rotatedFrameMat, Core.ROTATE_90_CLOCKWISE);
  675. return rotatedFrameMat;
  676. }
  677. else
  678. {
  679. if (screenOrientation == ScreenOrientation.Portrait || screenOrientation == ScreenOrientation.PortraitUpsideDown)
  680. {
  681. // (Orientation is Portrait, rotate90Degree is ture)
  682. if (webCamDevice.isFrontFacing)
  683. {
  684. FlipMat (frameMat, flipHorizontal, flipVertical);
  685. }
  686. else
  687. {
  688. FlipMat (frameMat, !flipHorizontal, !flipVertical);
  689. }
  690. }
  691. else
  692. {
  693. // (Orientation is Landscape, rotate90Degree is false)
  694. FlipMat (frameMat, flipVertical, flipHorizontal);
  695. }
  696. return frameMat;
  697. }
  698. #else
  699. FlipMat (frameMat, flipVertical, flipHorizontal);
  700. if (rotatedFrameMat != null) {
  701. Core.rotate (frameMat, rotatedFrameMat, Core.ROTATE_90_CLOCKWISE);
  702. return rotatedFrameMat;
  703. } else {
  704. return frameMat;
  705. }
  706. #endif
  707. }
  708. /// <summary>
  709. /// Flips the mat.
  710. /// </summary>
  711. /// <param name="mat">Mat.</param>
  712. protected virtual void FlipMat (Mat mat, bool flipVertical, bool flipHorizontal)
  713. {
  714. //Since the order of pixels of WebCamTexture and Mat is opposite, the initial value of flipCode is set to 0 (flipVertical).
  715. int flipCode = 0;
  716. if (webCamDevice.isFrontFacing) {
  717. if (webCamTexture.videoRotationAngle == 0) {
  718. flipCode = -1;
  719. } else if (webCamTexture.videoRotationAngle == 90) {
  720. flipCode = -1;
  721. }
  722. if (webCamTexture.videoRotationAngle == 180) {
  723. flipCode = int.MinValue;
  724. } else if (webCamTexture.videoRotationAngle == 270) {
  725. flipCode = int.MinValue;
  726. }
  727. } else {
  728. if (webCamTexture.videoRotationAngle == 180) {
  729. flipCode = 1;
  730. } else if (webCamTexture.videoRotationAngle == 270) {
  731. flipCode = 1;
  732. }
  733. }
  734. if (flipVertical) {
  735. if (flipCode == int.MinValue) {
  736. flipCode = 0;
  737. } else if (flipCode == 0) {
  738. flipCode = int.MinValue;
  739. } else if (flipCode == 1) {
  740. flipCode = -1;
  741. } else if (flipCode == -1) {
  742. flipCode = 1;
  743. }
  744. }
  745. if (flipHorizontal) {
  746. if (flipCode == int.MinValue) {
  747. flipCode = 1;
  748. } else if (flipCode == 0) {
  749. flipCode = -1;
  750. } else if (flipCode == 1) {
  751. flipCode = int.MinValue;
  752. } else if (flipCode == -1) {
  753. flipCode = 0;
  754. }
  755. }
  756. if (flipCode > int.MinValue) {
  757. Core.flip (mat, mat, flipCode);
  758. }
  759. }
  760. /// <summary>
  761. /// Gets the buffer colors.
  762. /// </summary>
  763. /// <returns>The buffer colors.</returns>
  764. public virtual Color32[] GetBufferColors ()
  765. {
  766. return colors;
  767. }
  768. /// <summary>
  769. /// Cancel Init Coroutine.
  770. /// </summary>
  771. protected virtual void CancelInitCoroutine ()
  772. {
  773. if (initCoroutine != null) {
  774. StopCoroutine (initCoroutine);
  775. ((IDisposable)initCoroutine).Dispose ();
  776. initCoroutine = null;
  777. }
  778. }
  779. /// <summary>
  780. /// To release the resources.
  781. /// </summary>
  782. protected virtual void ReleaseResources ()
  783. {
  784. isInitWaiting = false;
  785. hasInitDone = false;
  786. if (webCamTexture != null) {
  787. webCamTexture.Stop ();
  788. WebCamTexture.Destroy (webCamTexture);
  789. webCamTexture = null;
  790. }
  791. if (frameMat != null) {
  792. frameMat.Dispose ();
  793. frameMat = null;
  794. }
  795. if (rotatedFrameMat != null) {
  796. rotatedFrameMat.Dispose ();
  797. rotatedFrameMat = null;
  798. }
  799. }
  800. /// <summary>
  801. /// Releases all resource used by the <see cref="WebCamTextureToMatHelper"/> object.
  802. /// </summary>
  803. /// <remarks>Call <see cref="Dispose"/> when you are finished using the <see cref="WebCamTextureToMatHelper"/>. The
  804. /// <see cref="Dispose"/> method leaves the <see cref="WebCamTextureToMatHelper"/> in an unusable state. After
  805. /// calling <see cref="Dispose"/>, you must release all references to the <see cref="WebCamTextureToMatHelper"/> so
  806. /// the garbage collector can reclaim the memory that the <see cref="WebCamTextureToMatHelper"/> was occupying.</remarks>
  807. public virtual void Dispose ()
  808. {
  809. if (colors != null)
  810. colors = null;
  811. if (isInitWaiting) {
  812. CancelInitCoroutine ();
  813. ReleaseResources ();
  814. } else if (hasInitDone) {
  815. ReleaseResources ();
  816. if (onDisposed != null)
  817. onDisposed.Invoke ();
  818. }
  819. }
  820. }
  821. }