VideoWriterExample.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. using UnityEngine;
  2. using UnityEngine.SceneManagement;
  3. using UnityEngine.UI;
  4. using System.Collections;
  5. using System.Collections.Generic;
  6. using OpenCVForUnity.CoreModule;
  7. using OpenCVForUnity.VideoioModule;
  8. using OpenCVForUnity.ImgprocModule;
  9. using OpenCVForUnity.UnityUtils;
  10. namespace OpenCVForUnitySample
  11. {
  12. /// <summary>
  13. /// VideoWriter Example
  14. /// An example of saving a video file using the VideoWriter class.
  15. /// http://docs.opencv.org/3.2.0/dd/d43/tutorial_py_video_display.html
  16. /// </summary>
  17. public class VideoWriterExample : MonoBehaviour
  18. {
  19. /// <summary>
  20. /// The cube.
  21. /// </summary>
  22. public GameObject cube;
  23. /// <summary>
  24. /// The preview panel.
  25. /// </summary>
  26. public RawImage previewPanel;
  27. /// <summary>
  28. /// The rec button.
  29. /// </summary>
  30. public Button RecButton;
  31. /// <summary>
  32. /// The play button.
  33. /// </summary>
  34. public Button PlayButton;
  35. /// <summary>
  36. /// The save path input field.
  37. /// </summary>
  38. public InputField savePathInputField;
  39. /// <summary>
  40. /// The max frame count.
  41. /// </summary>
  42. const int maxframeCount = 300;
  43. /// <summary>
  44. /// The frame count.
  45. /// </summary>
  46. int frameCount;
  47. /// <summary>
  48. /// The videowriter.
  49. /// </summary>
  50. VideoWriter writer;
  51. /// <summary>
  52. /// The videocapture.
  53. /// </summary>
  54. VideoCapture capture;
  55. /// <summary>
  56. /// The screen capture.
  57. /// </summary>
  58. Texture2D screenCapture;
  59. /// <summary>
  60. /// The recording frame rgb mat.
  61. /// </summary>
  62. Mat recordingFrameRgbMat;
  63. /// <summary>
  64. /// The preview rgb mat.
  65. /// </summary>
  66. Mat previewRgbMat;
  67. /// <summary>
  68. /// The preview texture.
  69. /// </summary>
  70. Texture2D previrwTexture;
  71. /// <summary>
  72. /// Indicates whether videowriter is recording.
  73. /// </summary>
  74. bool isRecording;
  75. /// <summary>
  76. /// Indicates whether videocapture is playing.
  77. /// </summary>
  78. bool isPlaying;
  79. /// <summary>
  80. /// The save path.
  81. /// </summary>
  82. string savePath;
  83. // Use this for initialization
  84. void Start ()
  85. {
  86. PlayButton.interactable = false;
  87. previewPanel.gameObject.SetActive (false);
  88. Initialize ();
  89. }
  90. private void Initialize ()
  91. {
  92. Texture2D imgTexture = Resources.Load ("lena") as Texture2D;
  93. Mat imgMat = new Mat (imgTexture.height, imgTexture.width, CvType.CV_8UC4);
  94. Utils.texture2DToMat (imgTexture, imgMat);
  95. Texture2D texture = new Texture2D (imgMat.cols (), imgMat.rows (), TextureFormat.RGBA32, false);
  96. Utils.matToTexture2D (imgMat, texture);
  97. cube.GetComponent<Renderer> ().material.mainTexture = texture;
  98. }
  99. // Update is called once per frame
  100. void Update ()
  101. {
  102. if (!isPlaying) {
  103. cube.transform.Rotate (new Vector3 (90, 90, 0) * Time.deltaTime, Space.Self);
  104. }
  105. if (isPlaying) {
  106. //Loop play
  107. if (capture.get (Videoio.CAP_PROP_POS_FRAMES) >= capture.get (Videoio.CAP_PROP_FRAME_COUNT))
  108. capture.set (Videoio.CAP_PROP_POS_FRAMES, 0);
  109. if (capture.grab ()) {
  110. capture.retrieve (previewRgbMat, 0);
  111. Imgproc.rectangle (previewRgbMat, new Point (0, 0), new Point (previewRgbMat.cols (), previewRgbMat.rows ()), new Scalar (0, 0, 255), 3);
  112. Imgproc.cvtColor (previewRgbMat, previewRgbMat, Imgproc.COLOR_BGR2RGB);
  113. Utils.fastMatToTexture2D (previewRgbMat, previrwTexture);
  114. }
  115. }
  116. }
  117. void OnPostRender ()
  118. {
  119. if (isRecording) {
  120. if (frameCount >= maxframeCount ||
  121. recordingFrameRgbMat.width () != Screen.width || recordingFrameRgbMat.height () != Screen.height) {
  122. OnRecButtonClick ();
  123. return;
  124. }
  125. frameCount++;
  126. // Take screen shot.
  127. screenCapture.ReadPixels (new UnityEngine.Rect (0, 0, Screen.width, Screen.height), 0, 0);
  128. screenCapture.Apply ();
  129. Utils.texture2DToMat (screenCapture, recordingFrameRgbMat);
  130. Imgproc.cvtColor (recordingFrameRgbMat, recordingFrameRgbMat, Imgproc.COLOR_RGB2BGR);
  131. Imgproc.putText (recordingFrameRgbMat, frameCount.ToString (), new Point (recordingFrameRgbMat.cols () - 70, 30), Imgproc.FONT_HERSHEY_SIMPLEX, 1.0, new Scalar (255, 255, 255), 2, Imgproc.LINE_AA, false);
  132. Imgproc.putText (recordingFrameRgbMat, "SavePath:", new Point (5, recordingFrameRgbMat.rows () - 30), Imgproc.FONT_HERSHEY_SIMPLEX, 0.8, new Scalar (0, 0, 255), 2, Imgproc.LINE_AA, false);
  133. Imgproc.putText (recordingFrameRgbMat, savePath, new Point (5, recordingFrameRgbMat.rows () - 8), Imgproc.FONT_HERSHEY_SIMPLEX, 0.5, new Scalar (255, 255, 255), 0, Imgproc.LINE_AA, false);
  134. writer.write (recordingFrameRgbMat);
  135. }
  136. }
  137. private void StartRecording (string savePath)
  138. {
  139. if (isRecording || isPlaying)
  140. return;
  141. this.savePath = savePath;
  142. writer = new VideoWriter ();
  143. writer.open (savePath, VideoWriter.fourcc ('M', 'J', 'P', 'G'), 30, new Size (Screen.width, Screen.height));
  144. if (!writer.isOpened ()) {
  145. Debug.LogError ("writer.isOpened() false");
  146. writer.release ();
  147. return;
  148. }
  149. screenCapture = new Texture2D (Screen.width, Screen.height, TextureFormat.RGB24, false);
  150. recordingFrameRgbMat = new Mat (Screen.height, Screen.width, CvType.CV_8UC3);
  151. frameCount = 0;
  152. isRecording = true;
  153. }
  154. private void StopRecording ()
  155. {
  156. if (!isRecording || isPlaying)
  157. return;
  158. if (writer != null && !writer.IsDisposed)
  159. writer.release ();
  160. if (recordingFrameRgbMat != null && !recordingFrameRgbMat.IsDisposed)
  161. recordingFrameRgbMat.Dispose ();
  162. savePathInputField.text = savePath;
  163. isRecording = false;
  164. }
  165. private void PlayVideo (string filePath)
  166. {
  167. if (isPlaying || isRecording)
  168. return;
  169. capture = new VideoCapture ();
  170. capture.open (filePath);
  171. if (!capture.isOpened ()) {
  172. Debug.LogError ("capture.isOpened() is false. ");
  173. capture.release ();
  174. return;
  175. }
  176. Debug.Log ("CAP_PROP_FORMAT: " + capture.get (Videoio.CAP_PROP_FORMAT));
  177. Debug.Log ("CAP_PROP_POS_MSEC: " + capture.get (Videoio.CAP_PROP_POS_MSEC));
  178. Debug.Log ("CAP_PROP_POS_FRAMES: " + capture.get (Videoio.CAP_PROP_POS_FRAMES));
  179. Debug.Log ("CAP_PROP_POS_AVI_RATIO: " + capture.get (Videoio.CAP_PROP_POS_AVI_RATIO));
  180. Debug.Log ("CAP_PROP_FRAME_COUNT: " + capture.get (Videoio.CAP_PROP_FRAME_COUNT));
  181. Debug.Log ("CAP_PROP_FPS: " + capture.get (Videoio.CAP_PROP_FPS));
  182. Debug.Log ("CAP_PROP_FRAME_WIDTH: " + capture.get (Videoio.CAP_PROP_FRAME_WIDTH));
  183. Debug.Log ("CAP_PROP_FRAME_HEIGHT: " + capture.get (Videoio.CAP_PROP_FRAME_HEIGHT));
  184. double ext = capture.get (Videoio.CAP_PROP_FOURCC);
  185. Debug.Log ("CAP_PROP_FOURCC: " + (char)((int)ext & 0XFF) + (char)(((int)ext & 0XFF00) >> 8) + (char)(((int)ext & 0XFF0000) >> 16) + (char)(((int)ext & 0XFF000000) >> 24));
  186. previewRgbMat = new Mat ();
  187. capture.grab ();
  188. capture.retrieve (previewRgbMat, 0);
  189. int frameWidth = previewRgbMat.cols ();
  190. int frameHeight = previewRgbMat.rows ();
  191. previrwTexture = new Texture2D (frameWidth, frameHeight, TextureFormat.RGB24, false);
  192. capture.set (Videoio.CAP_PROP_POS_FRAMES, 0);
  193. previewPanel.texture = previrwTexture;
  194. isPlaying = true;
  195. }
  196. private void StopVideo ()
  197. {
  198. if (!isPlaying || isRecording)
  199. return;
  200. if (capture != null && !capture.IsDisposed)
  201. capture.release ();
  202. if (previewRgbMat != null && !previewRgbMat.IsDisposed)
  203. previewRgbMat.Dispose ();
  204. isPlaying = false;
  205. }
  206. /// <summary>
  207. /// Raises the destroy event.
  208. /// </summary>
  209. void OnDestroy ()
  210. {
  211. StopRecording ();
  212. StopVideo ();
  213. }
  214. /// <summary>
  215. /// Raises the back button click event.
  216. /// </summary>
  217. public void OnBackButtonClick ()
  218. {
  219. SceneManager.LoadScene ("OpenCVForUnityExample");
  220. }
  221. /// <summary>
  222. /// Raises the rec button click event.
  223. /// </summary>
  224. public void OnRecButtonClick ()
  225. {
  226. if (isRecording) {
  227. RecButton.GetComponentInChildren<UnityEngine.UI.Text> ().color = Color.black;
  228. StopRecording ();
  229. PlayButton.interactable = true;
  230. previewPanel.gameObject.SetActive (false);
  231. } else {
  232. RecButton.GetComponentInChildren<UnityEngine.UI.Text> ().color = Color.red;
  233. StartRecording (Application.persistentDataPath + "/VideoWriterExample_output.avi");
  234. PlayButton.interactable = false;
  235. }
  236. }
  237. /// <summary>
  238. /// Raises the play button click event.
  239. /// </summary>
  240. public void OnPlayButtonClick ()
  241. {
  242. if (isPlaying) {
  243. StopVideo ();
  244. PlayButton.GetComponentInChildren<UnityEngine.UI.Text> ().text = "Play";
  245. RecButton.interactable = true;
  246. previewPanel.gameObject.SetActive (false);
  247. } else {
  248. if (string.IsNullOrEmpty (savePath))
  249. return;
  250. PlayVideo (savePath);
  251. PlayButton.GetComponentInChildren<UnityEngine.UI.Text> ().text = "Stop";
  252. RecButton.interactable = false;
  253. previewPanel.gameObject.SetActive (true);
  254. }
  255. }
  256. }
  257. }