From 6c87ce0879ddc15fffc9493aea32bdd937b55bb6 Mon Sep 17 00:00:00 2001 From: Blake Blackshear Date: Sun, 15 Dec 2019 07:25:40 -0600 Subject: [PATCH] cache the computed jpg bytes to reduce cpu usage --- detect_objects.py | 4 +--- frigate/video.py | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/detect_objects.py b/detect_objects.py index 0ec6bf5bb..565f36f30 100644 --- a/detect_objects.py +++ b/detect_objects.py @@ -123,10 +123,8 @@ def main(): # max out at 1 FPS time.sleep(1) frame = cameras[camera_name].get_current_frame_with_objects() - # encode the image into a jpg - ret, jpg = cv2.imencode('.jpg', frame) yield (b'--frame\r\n' - b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n') + b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') app.run(host='0.0.0.0', port=WEB_PORT, debug=False) diff --git a/frigate/video.py b/frigate/video.py index d60d047c8..e8532f6d3 100644 --- a/frigate/video.py +++ b/frigate/video.py @@ -144,6 +144,12 @@ class Camera: self.frame_ready = mp.Condition() # Condition for notifying that objects were parsed self.objects_parsed = mp.Condition() + + # initialize the frame cache + self.cached_frame_with_objects = { + 'frame_bytes': [], + 'frame_time': 0 + } self.ffmpeg_process = None self.capture_thread = None @@ -315,6 +321,9 @@ class Camera: with self.frame_lock: frame = self.current_frame.copy() frame_time = self.frame_time.value + + if frame_time == self.cached_frame_with_objects['frame_time']: + return self.cached_frame_with_objects['frame_bytes'] # draw the bounding boxes on the screen for obj in detected_objects: @@ -333,7 +342,17 @@ class Camera: # convert to BGR frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) - return frame + # encode the image into a jpg + ret, jpg = cv2.imencode('.jpg', frame) + + frame_bytes = jpg.tobytes() + + self.cached_frame_with_objects = { + 'frame_bytes': frame_bytes, + 'frame_time': frame_time + } + + return frame_bytes