timelapser.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import os
  2. import cv2 as cv
  3. import numpy as np
  4. class Timelapser:
  5. TIMELAPSE_CHOICES = ('no', 'as_is', 'crop',)
  6. DEFAULT_TIMELAPSE = 'no'
  7. def __init__(self, timelapse=DEFAULT_TIMELAPSE):
  8. self.do_timelapse = True
  9. self.timelapse_type = None
  10. self.timelapser = None
  11. if timelapse == "as_is":
  12. self.timelapse_type = cv.detail.Timelapser_AS_IS
  13. elif timelapse == "crop":
  14. self.timelapse_type = cv.detail.Timelapser_CROP
  15. else:
  16. self.do_timelapse = False
  17. if self.do_timelapse:
  18. self.timelapser = cv.detail.Timelapser_createDefault(
  19. self.timelapse_type
  20. )
  21. def initialize(self, *args):
  22. """https://docs.opencv.org/4.x/dd/dac/classcv_1_1detail_1_1Timelapser.html#aaf0f7c4128009f02473332a0c41f6345""" # noqa
  23. self.timelapser.initialize(*args)
  24. def process_and_save_frame(self, img_name, img, corner):
  25. self.process_frame(img, corner)
  26. cv.imwrite(self.get_fixed_filename(img_name), self.get_frame())
  27. def process_frame(self, img, corner):
  28. mask = np.ones((img.shape[0], img.shape[1]), np.uint8)
  29. img = img.astype(np.int16)
  30. self.timelapser.process(img, mask, corner)
  31. def get_frame(self):
  32. frame = self.timelapser.getDst()
  33. frame = np.float32(cv.UMat.get(frame))
  34. frame = cv.convertScaleAbs(frame)
  35. return frame
  36. @staticmethod
  37. def get_fixed_filename(img_name):
  38. dirname, filename = os.path.split(img_name)
  39. return os.path.join(dirname, "fixed_" + filename)