LegacyTrackingExample.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using OpenCVForUnity.CoreModule;
  2. using OpenCVForUnity.ImgprocModule;
  3. using OpenCVForUnity.TrackingModule;
  4. using OpenCVForUnity.UnityUtils;
  5. using OpenCVForUnity.UnityUtils.Helper;
  6. using System.Collections.Generic;
  7. using UnityEngine;
  8. using UnityEngine.EventSystems;
  9. using UnityEngine.SceneManagement;
  10. using UnityEngine.UI;
  11. using Rect = OpenCVForUnity.CoreModule.Rect;
  12. namespace OpenCVForUnityExample
  13. {
  14. /// <summary>
  15. /// Legacy Tracking Example
  16. /// An example of object tracking using the TrackingModule.legacy_Tracker Class.
  17. /// http://docs.opencv.org/trunk/d5/d07/tutorial_multitracker.html
  18. /// </summary>
  19. [RequireComponent(typeof(VideoCaptureToMatHelper))]
  20. public class LegacyTrackingExample : MonoBehaviour
  21. {
  22. /// <summary>
  23. /// The trackerBoosting Toggle.
  24. /// </summary>
  25. public Toggle trackerBoostingToggle;
  26. /// <summary>
  27. /// The trackerCSRT Toggle.
  28. /// </summary>
  29. public Toggle trackerCSRTToggle;
  30. /// <summary>
  31. /// The trackerKCF Toggle.
  32. /// </summary>
  33. public Toggle trackerKCFToggle;
  34. /// <summary>
  35. /// The trackerMedianFlow Toggle.
  36. /// </summary>
  37. public Toggle trackerMedianFlowToggle;
  38. /// <summary>
  39. /// The trackerMIL Toggle.
  40. /// </summary>
  41. public Toggle trackerMILToggle;
  42. /// <summary>
  43. /// The trackerMOSSE Toggle.
  44. /// </summary>
  45. public Toggle trackerMOSSEToggle;
  46. /// <summary>
  47. /// The trackerTLD Toggle.
  48. /// </summary>
  49. public Toggle trackerTLDToggle;
  50. /// <summary>
  51. /// The texture.
  52. /// </summary>
  53. Texture2D texture;
  54. /// <summary>
  55. /// The trackers.
  56. /// </summary>
  57. List<TrackerSetting> trackers;
  58. /// <summary>
  59. /// The selected point list.
  60. /// </summary>
  61. List<Point> selectedPointList;
  62. /// <summary>
  63. /// The stored touch point.
  64. /// </summary>
  65. Point storedTouchPoint;
  66. /// <summary>
  67. /// The video capture to mat helper.
  68. /// </summary>
  69. VideoCaptureToMatHelper sourceToMatHelper;
  70. /// <summary>
  71. /// The FPS monitor.
  72. /// </summary>
  73. FpsMonitor fpsMonitor;
  74. /// <summary>
  75. /// VIDEO_FILENAME
  76. /// </summary>
  77. protected static readonly string VIDEO_FILENAME = "OpenCVForUnity/768x576_mjpeg.mjpeg";
  78. // Use this for initialization
  79. void Start()
  80. {
  81. fpsMonitor = GetComponent<FpsMonitor>();
  82. sourceToMatHelper = gameObject.GetComponent<VideoCaptureToMatHelper>();
  83. if (string.IsNullOrEmpty(sourceToMatHelper.requestedVideoFilePath))
  84. sourceToMatHelper.requestedVideoFilePath = VIDEO_FILENAME;
  85. sourceToMatHelper.outputColorFormat = VideoCaptureToMatHelper.ColorFormat.RGB; // Tracking API must handle 3 channels Mat image.
  86. sourceToMatHelper.Initialize();
  87. }
  88. /// <summary>
  89. /// Raises the video capture to mat helper initialized event.
  90. /// </summary>
  91. public void OnVideoCaptureToMatHelperInitialized()
  92. {
  93. Debug.Log("OnVideoCaptureToMatHelperInitialized");
  94. Mat rgbMat = sourceToMatHelper.GetMat();
  95. texture = new Texture2D(rgbMat.cols(), rgbMat.rows(), TextureFormat.RGB24, false);
  96. Utils.matToTexture2D(rgbMat, texture);
  97. gameObject.GetComponent<Renderer>().material.mainTexture = texture;
  98. gameObject.transform.localScale = new Vector3(rgbMat.cols(), rgbMat.rows(), 1);
  99. Debug.Log("Screen.width " + Screen.width + " Screen.height " + Screen.height + " Screen.orientation " + Screen.orientation);
  100. float width = rgbMat.width();
  101. float height = rgbMat.height();
  102. float widthScale = (float)Screen.width / width;
  103. float heightScale = (float)Screen.height / height;
  104. if (widthScale < heightScale)
  105. {
  106. Camera.main.orthographicSize = (width * (float)Screen.height / (float)Screen.width) / 2;
  107. }
  108. else
  109. {
  110. Camera.main.orthographicSize = height / 2;
  111. }
  112. trackers = new List<TrackerSetting>();
  113. selectedPointList = new List<Point>();
  114. }
  115. /// <summary>
  116. /// Raises the video capture to mat helper disposed event.
  117. /// </summary>
  118. public void OnVideoCaptureToMatHelperDisposed()
  119. {
  120. Debug.Log("OnVideoCaptureToMatHelperDisposed");
  121. if (texture != null)
  122. {
  123. Texture2D.Destroy(texture);
  124. texture = null;
  125. }
  126. ResetTrackers();
  127. }
  128. /// <summary>
  129. /// Raises the video capture to mat helper error occurred event.
  130. /// </summary>
  131. /// <param name="errorCode">Error code.</param>
  132. public void OnVideoCaptureToMatHelperErrorOccurred(VideoCaptureToMatHelper.ErrorCode errorCode)
  133. {
  134. Debug.Log("OnVideoCaptureToMatHelperErrorOccurred " + errorCode);
  135. if (fpsMonitor != null)
  136. {
  137. fpsMonitor.consoleText = "ErrorCode: " + errorCode;
  138. }
  139. }
  140. // Update is called once per frame
  141. void Update()
  142. {
  143. if (!sourceToMatHelper.IsInitialized())
  144. return;
  145. #if ((UNITY_ANDROID || UNITY_IOS) && !UNITY_EDITOR)
  146. //Touch
  147. int touchCount = Input.touchCount;
  148. if (touchCount == 1)
  149. {
  150. Touch t = Input.GetTouch(0);
  151. if(t.phase == TouchPhase.Ended && !EventSystem.current.IsPointerOverGameObject (t.fingerId)) {
  152. storedTouchPoint = new Point (t.position.x, t.position.y);
  153. //Debug.Log ("touch X " + t.position.x);
  154. //Debug.Log ("touch Y " + t.position.y);
  155. }
  156. }
  157. #else
  158. //Mouse
  159. if (Input.GetMouseButtonUp(0) && !EventSystem.current.IsPointerOverGameObject())
  160. {
  161. storedTouchPoint = new Point(Input.mousePosition.x, Input.mousePosition.y);
  162. //Debug.Log ("mouse X " + Input.mousePosition.x);
  163. //Debug.Log ("mouse Y " + Input.mousePosition.y);
  164. }
  165. #endif
  166. if (selectedPointList.Count != 1)
  167. {
  168. if (!sourceToMatHelper.IsPlaying())
  169. sourceToMatHelper.Play();
  170. if (sourceToMatHelper.IsPlaying() && sourceToMatHelper.DidUpdateThisFrame())
  171. {
  172. Mat rgbMat = sourceToMatHelper.GetMat();
  173. if (storedTouchPoint != null)
  174. {
  175. ConvertScreenPointToTexturePoint(storedTouchPoint, storedTouchPoint, gameObject, texture.width, texture.height);
  176. OnTouch(storedTouchPoint, texture.width, texture.height);
  177. storedTouchPoint = null;
  178. }
  179. if (selectedPointList.Count == 1)
  180. {
  181. foreach (var point in selectedPointList)
  182. {
  183. Imgproc.circle(rgbMat, point, 6, new Scalar(0, 0, 255), 2);
  184. }
  185. }
  186. else if (selectedPointList.Count == 2)
  187. {
  188. ResetTrackers();
  189. using (MatOfPoint selectedPointMat = new MatOfPoint(selectedPointList.ToArray()))
  190. {
  191. Rect _region = Imgproc.boundingRect(selectedPointMat);
  192. Rect2d region = new Rect2d(_region.tl(), _region.size());
  193. // init trackers.
  194. if (trackerBoostingToggle.isOn)
  195. {
  196. legacy_TrackerBoosting trackerBoosting = legacy_TrackerBoosting.create();
  197. trackerBoosting.init(rgbMat, region);
  198. trackers.Add(new TrackerSetting(trackerBoosting, trackerBoosting.GetType().Name.ToString(), new Scalar(255, 0, 0)));
  199. }
  200. if (trackerCSRTToggle.isOn)
  201. {
  202. legacy_TrackerCSRT trackerCSRT = legacy_TrackerCSRT.create();
  203. trackerCSRT.init(rgbMat, region);
  204. trackers.Add(new TrackerSetting(trackerCSRT, trackerCSRT.GetType().Name.ToString(), new Scalar(0, 255, 0)));
  205. }
  206. if (trackerKCFToggle.isOn)
  207. {
  208. legacy_TrackerKCF trackerKCF = legacy_TrackerKCF.create();
  209. trackerKCF.init(rgbMat, region);
  210. trackers.Add(new TrackerSetting(trackerKCF, trackerKCF.GetType().Name.ToString(), new Scalar(0, 0, 255)));
  211. }
  212. if (trackerMedianFlowToggle.isOn)
  213. {
  214. legacy_TrackerMedianFlow trackerMedianFlow = legacy_TrackerMedianFlow.create();
  215. trackerMedianFlow.init(rgbMat, region);
  216. trackers.Add(new TrackerSetting(trackerMedianFlow, trackerMedianFlow.GetType().Name.ToString(), new Scalar(255, 255, 0)));
  217. }
  218. if (trackerMILToggle.isOn)
  219. {
  220. legacy_TrackerMIL trackerMIL = legacy_TrackerMIL.create();
  221. trackerMIL.init(rgbMat, region);
  222. trackers.Add(new TrackerSetting(trackerMIL, trackerMIL.GetType().Name.ToString(), new Scalar(255, 0, 255)));
  223. }
  224. if (trackerMOSSEToggle.isOn)
  225. {
  226. legacy_TrackerMOSSE trackerMOSSE = legacy_TrackerMOSSE.create();
  227. trackerMOSSE.init(rgbMat, region);
  228. trackers.Add(new TrackerSetting(trackerMOSSE, trackerMOSSE.GetType().Name.ToString(), new Scalar(0, 255, 255)));
  229. }
  230. if (trackerTLDToggle.isOn)
  231. {
  232. legacy_TrackerTLD trackerTLD = legacy_TrackerTLD.create();
  233. trackerTLD.init(rgbMat, region);
  234. trackers.Add(new TrackerSetting(trackerTLD, trackerTLD.GetType().Name.ToString(), new Scalar(255, 255, 255)));
  235. }
  236. }
  237. selectedPointList.Clear();
  238. if (trackers.Count > 0)
  239. {
  240. if (fpsMonitor != null)
  241. {
  242. fpsMonitor.consoleText = "";
  243. }
  244. trackerBoostingToggle.interactable = trackerCSRTToggle.interactable = trackerKCFToggle.interactable = trackerMedianFlowToggle.interactable =
  245. trackerMILToggle.interactable = trackerMOSSEToggle.interactable = trackerTLDToggle.interactable = false;
  246. }
  247. }
  248. // update trackers.
  249. for (int i = 0; i < trackers.Count; i++)
  250. {
  251. legacy_Tracker tracker = trackers[i].tracker;
  252. string label = trackers[i].label;
  253. Scalar lineColor = trackers[i].lineColor;
  254. Rect2d boundingBox = trackers[i].boundingBox;
  255. tracker.update(rgbMat, boundingBox);
  256. Imgproc.rectangle(rgbMat, boundingBox.tl(), boundingBox.br(), lineColor, 2, 1, 0);
  257. Imgproc.putText(rgbMat, label, new Point(boundingBox.x, boundingBox.y - 5), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, lineColor, 1, Imgproc.LINE_AA, false);
  258. }
  259. if (trackers.Count == 0)
  260. {
  261. if (selectedPointList.Count != 1)
  262. {
  263. //Imgproc.putText (rgbMat, "Please touch the screen, and select tracking regions.", new Point (5, rgbMat.rows () - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 0.8, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
  264. if (fpsMonitor != null)
  265. {
  266. fpsMonitor.consoleText = "Please touch the screen, and select tracking regions.";
  267. }
  268. }
  269. else
  270. {
  271. //Imgproc.putText (rgbMat, "Please select the end point of the new tracking region.", new Point (5, rgbMat.rows () - 10), Imgproc.FONT_HERSHEY_SIMPLEX, 0.8, new Scalar (255, 255, 255, 255), 2, Imgproc.LINE_AA, false);
  272. if (fpsMonitor != null)
  273. {
  274. fpsMonitor.consoleText = "Please select the end point of the new tracking region.";
  275. }
  276. }
  277. }
  278. Utils.matToTexture2D(rgbMat, texture);
  279. }
  280. }
  281. else
  282. {
  283. if (sourceToMatHelper.IsPlaying())
  284. sourceToMatHelper.Pause();
  285. if (storedTouchPoint != null)
  286. {
  287. ConvertScreenPointToTexturePoint(storedTouchPoint, storedTouchPoint, gameObject, texture.width, texture.height);
  288. OnTouch(storedTouchPoint, texture.width, texture.height);
  289. storedTouchPoint = null;
  290. }
  291. }
  292. }
  293. private void ResetTrackers()
  294. {
  295. if (trackers != null)
  296. {
  297. foreach (var t in trackers)
  298. {
  299. t.Dispose();
  300. }
  301. trackers.Clear();
  302. }
  303. trackerBoostingToggle.interactable = trackerCSRTToggle.interactable = trackerKCFToggle.interactable= trackerMedianFlowToggle.interactable =
  304. trackerMILToggle.interactable = trackerMOSSEToggle.interactable = trackerTLDToggle.interactable = true;
  305. }
  306. private void OnTouch(Point touchPoint, int textureWidth = -1, int textureHeight = -1)
  307. {
  308. if (selectedPointList.Count < 2)
  309. {
  310. selectedPointList.Add(touchPoint);
  311. if (!(new OpenCVForUnity.CoreModule.Rect(0, 0, textureWidth, textureHeight).contains(selectedPointList[selectedPointList.Count - 1])))
  312. {
  313. selectedPointList.RemoveAt(selectedPointList.Count - 1);
  314. }
  315. }
  316. }
  317. /// <summary>
  318. /// Converts the screen point to texture point.
  319. /// </summary>
  320. /// <param name="screenPoint">Screen point.</param>
  321. /// <param name="dstPoint">Dst point.</param>
  322. /// <param name="texturQuad">Texture quad.</param>
  323. /// <param name="textureWidth">Texture width.</param>
  324. /// <param name="textureHeight">Texture height.</param>
  325. /// <param name="camera">Camera.</param>
  326. private void ConvertScreenPointToTexturePoint(Point screenPoint, Point dstPoint, GameObject textureQuad, int textureWidth = -1, int textureHeight = -1, Camera camera = null)
  327. {
  328. if (textureWidth < 0 || textureHeight < 0)
  329. {
  330. Renderer r = textureQuad.GetComponent<Renderer>();
  331. if (r != null && r.material != null && r.material.mainTexture != null)
  332. {
  333. textureWidth = r.material.mainTexture.width;
  334. textureHeight = r.material.mainTexture.height;
  335. }
  336. else
  337. {
  338. textureWidth = (int)textureQuad.transform.localScale.x;
  339. textureHeight = (int)textureQuad.transform.localScale.y;
  340. }
  341. }
  342. if (camera == null)
  343. camera = Camera.main;
  344. Vector3 quadPosition = textureQuad.transform.localPosition;
  345. Vector3 quadScale = textureQuad.transform.localScale;
  346. Vector2 tl = camera.WorldToScreenPoint(new Vector3(quadPosition.x - quadScale.x / 2, quadPosition.y + quadScale.y / 2, quadPosition.z));
  347. Vector2 tr = camera.WorldToScreenPoint(new Vector3(quadPosition.x + quadScale.x / 2, quadPosition.y + quadScale.y / 2, quadPosition.z));
  348. Vector2 br = camera.WorldToScreenPoint(new Vector3(quadPosition.x + quadScale.x / 2, quadPosition.y - quadScale.y / 2, quadPosition.z));
  349. Vector2 bl = camera.WorldToScreenPoint(new Vector3(quadPosition.x - quadScale.x / 2, quadPosition.y - quadScale.y / 2, quadPosition.z));
  350. using (Mat srcRectMat = new Mat(4, 1, CvType.CV_32FC2))
  351. using (Mat dstRectMat = new Mat(4, 1, CvType.CV_32FC2))
  352. {
  353. srcRectMat.put(0, 0, tl.x, tl.y, tr.x, tr.y, br.x, br.y, bl.x, bl.y);
  354. dstRectMat.put(0, 0, 0, 0, quadScale.x, 0, quadScale.x, quadScale.y, 0, quadScale.y);
  355. using (Mat perspectiveTransform = Imgproc.getPerspectiveTransform(srcRectMat, dstRectMat))
  356. using (MatOfPoint2f srcPointMat = new MatOfPoint2f(screenPoint))
  357. using (MatOfPoint2f dstPointMat = new MatOfPoint2f())
  358. {
  359. Core.perspectiveTransform(srcPointMat, dstPointMat, perspectiveTransform);
  360. dstPoint.x = dstPointMat.get(0, 0)[0] * textureWidth / quadScale.x;
  361. dstPoint.y = dstPointMat.get(0, 0)[1] * textureHeight / quadScale.y;
  362. }
  363. }
  364. }
  365. /// <summary>
  366. /// Raises the destroy event.
  367. /// </summary>
  368. void OnDestroy()
  369. {
  370. if (sourceToMatHelper != null)
  371. sourceToMatHelper.Dispose();
  372. }
  373. /// <summary>
  374. /// Raises the back button click event.
  375. /// </summary>
  376. public void OnBackButtonClick()
  377. {
  378. SceneManager.LoadScene("OpenCVForUnityExample");
  379. }
  380. /// <summary>
  381. /// Raises the reset trackers button click event.
  382. /// </summary>
  383. public void OnResetTrackersButtonClick()
  384. {
  385. ResetTrackers();
  386. selectedPointList.Clear();
  387. }
  388. class TrackerSetting
  389. {
  390. public legacy_Tracker tracker;
  391. public string label;
  392. public Scalar lineColor;
  393. public Rect2d boundingBox;
  394. public TrackerSetting(legacy_Tracker tracker, string label, Scalar lineColor)
  395. {
  396. this.tracker = tracker;
  397. this.label = label;
  398. this.lineColor = lineColor;
  399. this.boundingBox = new Rect2d();
  400. }
  401. public void Dispose()
  402. {
  403. if (tracker != null)
  404. {
  405. tracker.Dispose();
  406. tracker = null;
  407. }
  408. }
  409. }
  410. }
  411. }