rtsp.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import cv2
  2. import numpy as np
  3. from .lib import DETR_HOST
  4. from threading import Thread
  5. from requests import request
  6. from time import sleep, strftime, localtime
  7. __all__ = ["Rtsp"]
  8. class Rtsp:
  9. def __init__(self):
  10. self.__handler, self.__data = None, None
  11. self.__reading: "bool" = False
  12. @staticmethod
  13. def __current_time(fmt: "str" = "%Y-%m-%d_%H-%M-%S") -> "str":
  14. return strftime(fmt, localtime())
  15. @staticmethod
  16. def resize(img: "np.ndarray", ratio: "int" = -1) -> "np.ndarray":
  17. if ratio == -1:
  18. return img
  19. h, w = img.shape[:2]
  20. tar_shape = int(w / ratio), int(h / ratio)
  21. return cv2.resize(img, tar_shape, interpolation=cv2.INTER_AREA)
  22. @staticmethod
  23. def detr(img: "np.ndarray") -> "np.ndarray":
  24. _, img = cv2.imencode(".jpg", img) # noqa
  25. files = {"img": ("from-python.jpg", img.tobytes(), "image/jpg")}
  26. resp = request("POST", DETR_HOST, files=files)
  27. img = cv2.imdecode(np.frombuffer(resp.content, np.uint8), 1)
  28. return img
  29. def __write(self):
  30. width = int(self.__handler.get(3))
  31. height = int(self.__handler.get(4))
  32. fps = int(self.__handler.get(5))
  33. print(width, height, fps)
  34. fourcc = cv2.VideoWriter_fourcc(*'XVID')
  35. writer = cv2.VideoWriter("./live.mp4", fourcc, fps, (width, height))
  36. ret, frame = self.__handler.read()
  37. while ret:
  38. writer.write(frame)
  39. ret, frame = self.__handler.read()
  40. def __read(self) -> "None":
  41. while True:
  42. if not self.__reading:
  43. self.__handler.release()
  44. self.__handler = None
  45. break
  46. ret, self.__data = self.__handler.read()
  47. if not ret:
  48. raise RuntimeError("Fail To Read Data.")
  49. def connect(self, rtsp: "str") -> "None":
  50. self.__handler = cv2.VideoCapture(rtsp)
  51. if not self.__handler.isOpened():
  52. raise RuntimeError("Fail To Connect Camera.")
  53. self.__reading = True
  54. Thread(target=self.__read, name="RTSP reader").start()
  55. # Thread(target=self.__write, name="RTSP writer").start()
  56. while self.__data is None:
  57. sleep(0.5)
  58. def close(self) -> "None":
  59. self.__reading = False
  60. self.__data = None
  61. def read_current(self) -> "np.ndarray":
  62. return self.__data
  63. def save_current_to(self, path: "str", compress: "int" = -1) -> None:
  64. if compress == -1:
  65. cv2.imwrite(path, self.__data)
  66. else:
  67. cv2.imwrite(path, self.resize(self.__data, compress))
  68. def read_stream(self, time_gap: "float" = 1.0, total: "int" = -1):
  69. if total == -1:
  70. while True:
  71. yield self.__data
  72. if time_gap > 0:
  73. sleep(time_gap)
  74. else:
  75. while total > 0:
  76. yield self.__data
  77. total -= 1
  78. if total > 0 and time_gap > 0:
  79. sleep(time_gap)