cache the computed jpg bytes to reduce cpu usage

This commit is contained in:
Blake Blackshear 2019-12-15 07:25:40 -06:00
parent b7b4e38f62
commit 6c87ce0879
2 changed files with 21 additions and 4 deletions

View File

@ -123,10 +123,8 @@ def main():
# max out at 1 FPS # max out at 1 FPS
time.sleep(1) time.sleep(1)
frame = cameras[camera_name].get_current_frame_with_objects() 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' 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) app.run(host='0.0.0.0', port=WEB_PORT, debug=False)

View File

@ -145,6 +145,12 @@ class Camera:
# Condition for notifying that objects were parsed # Condition for notifying that objects were parsed
self.objects_parsed = mp.Condition() self.objects_parsed = mp.Condition()
# initialize the frame cache
self.cached_frame_with_objects = {
'frame_bytes': [],
'frame_time': 0
}
self.ffmpeg_process = None self.ffmpeg_process = None
self.capture_thread = None self.capture_thread = None
@ -316,6 +322,9 @@ class Camera:
frame = self.current_frame.copy() frame = self.current_frame.copy()
frame_time = self.frame_time.value 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 # draw the bounding boxes on the screen
for obj in detected_objects: for obj in detected_objects:
draw_box_with_label(frame, obj['xmin'], obj['ymin'], obj['xmax'], obj['ymax'], obj['name'], obj['score'], obj['area']) draw_box_with_label(frame, obj['xmin'], obj['ymin'], obj['xmax'], obj['ymax'], obj['name'], obj['score'], obj['area'])
@ -333,7 +342,17 @@ class Camera:
# convert to BGR # convert to BGR
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) 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