video.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """ Common function for camera based method """
  2. import json
  3. import logging
  4. import os
  5. import time
  6. from datetime import datetime
  7. import threading
  8. import cv2
  9. import numpy as np
  10. from settings.config import settings
  11. logger = logging.getLogger(__name__)
  12. class VideoCaptureThread:
  13. def __init__(self, output_dir, video_source=0, sync_device=None):
  14. super(VideoCaptureThread, self).__init__()
  15. self.video_source = video_source
  16. self.cap = cv2.VideoCapture(self.video_source, cv2.CAP_DSHOW)
  17. while not self.cap.isOpened():
  18. pass # Wait for the capture to be initialized
  19. self.cap.set(cv2.CAP_PROP_FPS, 30.0)
  20. self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280),
  21. self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
  22. self.sync_device = sync_device
  23. now = datetime.now()
  24. date_time_str = now.strftime("%m-%d-%Y-%H-%M-%S")
  25. try:
  26. os.makedirs(output_dir)
  27. except FileExistsError:
  28. pass
  29. self.output_path = os.path.join(output_dir, f'video_recording_{date_time_str}.mp4')
  30. self.out = cv2.VideoWriter(self.output_path, cv2.VideoWriter_fourcc(*'mp4v'), 30.0, (1280, 720))
  31. self.videothread = threading.Thread(target=self.run)
  32. self.videothread.start()
  33. def run(self):
  34. logger.info("Camera starting")
  35. self.capture_video()
  36. def capture_video(self):
  37. ret, frame = self.cap.read()
  38. if not ret:
  39. logger.error("Error: Couldn't read frame. Exit.")
  40. return
  41. # synchronize after getting the first frame
  42. if self.sync_device is not None:
  43. self.sync_device.send_trigger(0xff) # 255 for video ready
  44. while self.cap.isOpened():
  45. ret, frame = self.cap.read()
  46. # TODO: online analysis (500ms step, asychronize)
  47. self.out.write(frame)
  48. def close(self):
  49. logger.info("Camera ended")
  50. self.cap.release()
  51. self.out.release()
  52. self.videothread.join()