detect_objects.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. import cv2
  2. import time
  3. import queue
  4. import yaml
  5. import threading
  6. import multiprocessing as mp
  7. import subprocess as sp
  8. import numpy as np
  9. import logging
  10. from flask import Flask, Response, make_response, jsonify
  11. import paho.mqtt.client as mqtt
  12. from frigate.video import track_camera
  13. from frigate.object_processing import TrackedObjectProcessor
  14. from frigate.util import EventsPerSecond
  15. from frigate.edgetpu import EdgeTPUProcess
  16. with open('/config/config.yml') as f:
  17. CONFIG = yaml.safe_load(f)
  18. MQTT_HOST = CONFIG['mqtt']['host']
  19. MQTT_PORT = CONFIG.get('mqtt', {}).get('port', 1883)
  20. MQTT_TOPIC_PREFIX = CONFIG.get('mqtt', {}).get('topic_prefix', 'frigate')
  21. MQTT_USER = CONFIG.get('mqtt', {}).get('user')
  22. MQTT_PASS = CONFIG.get('mqtt', {}).get('password')
  23. MQTT_CLIENT_ID = CONFIG.get('mqtt', {}).get('client_id', 'frigate')
  24. # Set the default FFmpeg config
  25. FFMPEG_CONFIG = CONFIG.get('ffmpeg', {})
  26. FFMPEG_DEFAULT_CONFIG = {
  27. 'global_args': FFMPEG_CONFIG.get('global_args',
  28. ['-hide_banner','-loglevel','panic']),
  29. 'hwaccel_args': FFMPEG_CONFIG.get('hwaccel_args',
  30. []),
  31. 'input_args': FFMPEG_CONFIG.get('input_args',
  32. ['-avoid_negative_ts', 'make_zero',
  33. '-fflags', 'nobuffer',
  34. '-flags', 'low_delay',
  35. '-strict', 'experimental',
  36. '-fflags', '+genpts+discardcorrupt',
  37. '-vsync', 'drop',
  38. '-rtsp_transport', 'tcp',
  39. '-stimeout', '5000000',
  40. '-use_wallclock_as_timestamps', '1']),
  41. 'output_args': FFMPEG_CONFIG.get('output_args',
  42. ['-f', 'rawvideo',
  43. '-pix_fmt', 'rgb24'])
  44. }
  45. GLOBAL_OBJECT_CONFIG = CONFIG.get('objects', {})
  46. WEB_PORT = CONFIG.get('web_port', 5000)
  47. DEBUG = (CONFIG.get('debug', '0') == '1')
  48. class CameraWatchdog(threading.Thread):
  49. def __init__(self, camera_processes, config, tflite_process, tracked_objects_queue):
  50. threading.Thread.__init__(self)
  51. self.camera_processes = camera_processes
  52. self.config = config
  53. self.tflite_process = tflite_process
  54. self.tracked_objects_queue = tracked_objects_queue
  55. def run(self):
  56. time.sleep(10)
  57. while True:
  58. # wait a bit before checking
  59. time.sleep(10)
  60. for name, camera_process in self.camera_processes.items():
  61. process = camera_process['process']
  62. if not process.is_alive():
  63. print(f"Process for {name} is not alive. Starting again...")
  64. camera_process['fps'].value = float(self.config[name]['fps'])
  65. camera_process['skipped_fps'].value = 0.0
  66. process = mp.Process(target=track_camera, args=(name, self.config[name], FFMPEG_DEFAULT_CONFIG, GLOBAL_OBJECT_CONFIG,
  67. self.tflite_process.detect_lock, self.tflite_process.detect_ready, self.tflite_process.frame_ready, self.tracked_objects_queue,
  68. camera_process['fps'], camera_process['skipped_fps']))
  69. process.daemon = True
  70. camera_process['process'] = process
  71. process.start()
  72. print(f"Camera_process started for {name}: {process.pid}")
  73. def main():
  74. # connect to mqtt and setup last will
  75. def on_connect(client, userdata, flags, rc):
  76. print("On connect called")
  77. if rc != 0:
  78. if rc == 3:
  79. print ("MQTT Server unavailable")
  80. elif rc == 4:
  81. print ("MQTT Bad username or password")
  82. elif rc == 5:
  83. print ("MQTT Not authorized")
  84. else:
  85. print ("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
  86. # publish a message to signal that the service is running
  87. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  88. client = mqtt.Client(client_id=MQTT_CLIENT_ID)
  89. client.on_connect = on_connect
  90. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  91. if not MQTT_USER is None:
  92. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  93. client.connect(MQTT_HOST, MQTT_PORT, 60)
  94. client.loop_start()
  95. # start plasma store
  96. plasma_cmd = ['plasma_store', '-m', '400000000', '-s', '/tmp/plasma']
  97. plasma_process = sp.Popen(plasma_cmd, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
  98. time.sleep(1)
  99. rc = plasma_process.poll()
  100. if rc is not None:
  101. raise RuntimeError("plasma_store exited unexpectedly with "
  102. "code %d" % (rc,))
  103. ##
  104. # Setup config defaults for cameras
  105. ##
  106. for name, config in CONFIG['cameras'].items():
  107. config['snapshots'] = {
  108. 'show_timestamp': config.get('snapshots', {}).get('show_timestamp', True)
  109. }
  110. # Queue for cameras to push tracked objects to
  111. tracked_objects_queue = mp.Queue()
  112. # Start the shared tflite process
  113. tflite_process = EdgeTPUProcess()
  114. # start the camera processes
  115. camera_processes = {}
  116. for name, config in CONFIG['cameras'].items():
  117. camera_processes[name] = {
  118. 'fps': mp.Value('d', float(config['fps'])),
  119. 'skipped_fps': mp.Value('d', 0.0)
  120. }
  121. camera_process = mp.Process(target=track_camera, args=(name, config, FFMPEG_DEFAULT_CONFIG, GLOBAL_OBJECT_CONFIG,
  122. tflite_process.detect_lock, tflite_process.detect_ready, tflite_process.frame_ready, tracked_objects_queue,
  123. camera_processes[name]['fps'], camera_processes[name]['skipped_fps']))
  124. camera_process.daemon = True
  125. camera_processes[name]['process'] = camera_process
  126. for name, camera_process in camera_processes.items():
  127. camera_process['process'].start()
  128. print(f"Camera_process started for {name}: {camera_process['process'].pid}")
  129. camera_watchdog = CameraWatchdog(camera_processes, CONFIG['cameras'], tflite_process, tracked_objects_queue)
  130. camera_watchdog.start()
  131. object_processor = TrackedObjectProcessor(CONFIG['cameras'], client, MQTT_TOPIC_PREFIX, tracked_objects_queue)
  132. object_processor.start()
  133. # create a flask app that encodes frames a mjpeg on demand
  134. app = Flask(__name__)
  135. log = logging.getLogger('werkzeug')
  136. log.setLevel(logging.ERROR)
  137. @app.route('/')
  138. def ishealthy():
  139. # return a healh
  140. return "Frigate is running. Alive and healthy!"
  141. @app.route('/debug/stats')
  142. def stats():
  143. stats = {
  144. 'coral': {
  145. 'fps': tflite_process.fps.value,
  146. 'inference_speed': round(tflite_process.avg_inference_speed.value*1000, 2)
  147. }
  148. }
  149. for name, camera_stats in camera_processes.items():
  150. stats[name] = {
  151. 'fps': camera_stats['fps'].value,
  152. 'skipped_fps': camera_stats['skipped_fps'].value
  153. }
  154. return jsonify(stats)
  155. @app.route('/<camera_name>/<label>/best.jpg')
  156. def best(camera_name, label):
  157. if camera_name in CONFIG['cameras']:
  158. best_frame = object_processor.get_best(camera_name, label)
  159. if best_frame is None:
  160. best_frame = np.zeros((720,1280,3), np.uint8)
  161. best_frame = cv2.cvtColor(best_frame, cv2.COLOR_RGB2BGR)
  162. ret, jpg = cv2.imencode('.jpg', best_frame)
  163. response = make_response(jpg.tobytes())
  164. response.headers['Content-Type'] = 'image/jpg'
  165. return response
  166. else:
  167. return "Camera named {} not found".format(camera_name), 404
  168. @app.route('/<camera_name>')
  169. def mjpeg_feed(camera_name):
  170. if camera_name in CONFIG['cameras']:
  171. # return a multipart response
  172. return Response(imagestream(camera_name),
  173. mimetype='multipart/x-mixed-replace; boundary=frame')
  174. else:
  175. return "Camera named {} not found".format(camera_name), 404
  176. def imagestream(camera_name):
  177. while True:
  178. # max out at 1 FPS
  179. time.sleep(1)
  180. frame = object_processor.get_current_frame(camera_name)
  181. if frame is None:
  182. frame = np.zeros((720,1280,3), np.uint8)
  183. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  184. ret, jpg = cv2.imencode('.jpg', frame)
  185. yield (b'--frame\r\n'
  186. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  187. app.run(host='0.0.0.0', port=WEB_PORT, debug=False)
  188. camera_watchdog.join()
  189. plasma_process.terminate()
  190. if __name__ == '__main__':
  191. main()