detect_objects.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135
  1. import cv2
  2. import time
  3. import queue
  4. import yaml
  5. import numpy as np
  6. from flask import Flask, Response, make_response
  7. import paho.mqtt.client as mqtt
  8. from frigate.video import Camera
  9. from frigate.object_detection import PreppedQueueProcessor
  10. with open('/config/config.yml') as f:
  11. CONFIG = yaml.safe_load(f)
  12. MQTT_HOST = CONFIG['mqtt']['host']
  13. MQTT_PORT = CONFIG.get('mqtt', {}).get('port', 1883)
  14. MQTT_TOPIC_PREFIX = CONFIG.get('mqtt', {}).get('topic_prefix', 'frigate')
  15. MQTT_USER = CONFIG.get('mqtt', {}).get('user')
  16. MQTT_PASS = CONFIG.get('mqtt', {}).get('password')
  17. MQTT_CLIENT_ID = CONFIG.get('mqtt', {}).get('client_id', 'frigate')
  18. # Set the default FFmpeg config
  19. FFMPEG_CONFIG = CONFIG.get('ffmpeg', {})
  20. FFMPEG_DEFAULT_CONFIG = {
  21. 'global_args': FFMPEG_CONFIG.get('global_args',
  22. ['-hide_banner','-loglevel','panic']),
  23. 'hwaccel_args': FFMPEG_CONFIG.get('hwaccel_args',
  24. []),
  25. 'input_args': FFMPEG_CONFIG.get('input_args',
  26. ['-avoid_negative_ts', 'make_zero',
  27. '-fflags', 'nobuffer',
  28. '-flags', 'low_delay',
  29. '-strict', 'experimental',
  30. '-fflags', '+genpts+discardcorrupt',
  31. '-vsync', 'drop',
  32. '-rtsp_transport', 'tcp',
  33. '-stimeout', '5000000',
  34. '-use_wallclock_as_timestamps', '1']),
  35. 'output_args': FFMPEG_CONFIG.get('output_args',
  36. ['-vf', 'mpdecimate',
  37. '-f', 'rawvideo',
  38. '-pix_fmt', 'rgb24'])
  39. }
  40. GLOBAL_OBJECT_CONFIG = CONFIG.get('objects', {})
  41. WEB_PORT = CONFIG.get('web_port', 5000)
  42. DEBUG = (CONFIG.get('debug', '0') == '1')
  43. def main():
  44. # connect to mqtt and setup last will
  45. def on_connect(client, userdata, flags, rc):
  46. print("On connect called")
  47. if rc != 0:
  48. if rc == 3:
  49. print ("MQTT Server unavailable")
  50. elif rc == 4:
  51. print ("MQTT Bad username or password")
  52. elif rc == 5:
  53. print ("MQTT Not authorized")
  54. else:
  55. print ("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
  56. # publish a message to signal that the service is running
  57. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  58. client = mqtt.Client(client_id=MQTT_CLIENT_ID)
  59. client.on_connect = on_connect
  60. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  61. if not MQTT_USER is None:
  62. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  63. client.connect(MQTT_HOST, MQTT_PORT, 60)
  64. client.loop_start()
  65. # Queue for prepped frames, max size set to (number of cameras * 5)
  66. max_queue_size = len(CONFIG['cameras'].items())*5
  67. prepped_frame_queue = queue.PriorityQueue(max_queue_size)
  68. cameras = {}
  69. for name, config in CONFIG['cameras'].items():
  70. cameras[name] = Camera(name, FFMPEG_DEFAULT_CONFIG, GLOBAL_OBJECT_CONFIG, config,
  71. prepped_frame_queue, client, MQTT_TOPIC_PREFIX)
  72. prepped_queue_processor = PreppedQueueProcessor(
  73. cameras,
  74. prepped_frame_queue
  75. )
  76. prepped_queue_processor.start()
  77. for name, camera in cameras.items():
  78. camera.start()
  79. print("Capture process for {}: {}".format(name, camera.get_capture_pid()))
  80. # create a flask app that encodes frames a mjpeg on demand
  81. app = Flask(__name__)
  82. @app.route('/')
  83. def ishealthy():
  84. # return a healh
  85. return "Frigate is running. Alive and healthy!"
  86. @app.route('/<camera_name>/<label>/best.jpg')
  87. def best(camera_name, label):
  88. if camera_name in cameras:
  89. best_frame = cameras[camera_name].get_best(label)
  90. if best_frame is None:
  91. best_frame = np.zeros((720,1280,3), np.uint8)
  92. ret, jpg = cv2.imencode('.jpg', best_frame)
  93. response = make_response(jpg.tobytes())
  94. response.headers['Content-Type'] = 'image/jpg'
  95. return response
  96. else:
  97. return f'Camera named {camera_name} not found', 404
  98. @app.route('/<camera_name>')
  99. def mjpeg_feed(camera_name):
  100. if camera_name in cameras:
  101. # return a multipart response
  102. return Response(imagestream(camera_name),
  103. mimetype='multipart/x-mixed-replace; boundary=frame')
  104. else:
  105. return f'Camera named {camera_name} not found', 404
  106. def imagestream(camera_name):
  107. while True:
  108. # max out at 1 FPS
  109. time.sleep(1)
  110. frame = cameras[camera_name].get_current_frame_with_objects()
  111. yield (b'--frame\r\n'
  112. b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
  113. app.run(host='0.0.0.0', port=WEB_PORT, debug=False)
  114. camera.join()
  115. if __name__ == '__main__':
  116. main()