video.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. """ Common function for camera based method """
  2. from fractions import Fraction
  3. import json
  4. import logging
  5. import os
  6. import time
  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_path, 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)
  17. self.sync_device = sync_device
  18. self.output_path = output_path
  19. frame_size = (int(self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
  20. int(self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
  21. self.out = cv2.VideoWriter(output_path, cv2.VideoWriter_fourcc(*'avc1'), 20.0, frame_size)
  22. self.videothread = threading.Thread(target=self.run)
  23. self.videothread.start()
  24. def run(self):
  25. logger.info("Camera starting")
  26. self.capture_video()
  27. def capture_video(self):
  28. while not self.cap.isOpened():
  29. pass # Wait for the capture to be initialized
  30. # synchronize
  31. if self.sync_device is not None:
  32. self.sync_device.send_trigger(0xff) # 255 for video ready
  33. while True:
  34. ret, frame = self.cap.read()
  35. # TODO: online analysis (500ms step, asychronize)
  36. if not ret:
  37. logger.error("Error: Couldn't read frame. Exit.")
  38. break
  39. self.out.write(frame)
  40. def close(self):
  41. logger.info("Camera ended")
  42. self.cap.release()
  43. self.out.release()
  44. self.videothread.join()