detect_objects.py 8.3 KB

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