detect_objects.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  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. WEB_PORT = CONFIG.get('web_port', 5000)
  41. DEBUG = (CONFIG.get('debug', '0') == '1')
  42. def main():
  43. # connect to mqtt and setup last will
  44. def on_connect(client, userdata, flags, rc):
  45. print("On connect called")
  46. if rc != 0:
  47. if rc == 3:
  48. print ("MQTT Server unavailable")
  49. elif rc == 4:
  50. print ("MQTT Bad username or password")
  51. elif rc == 5:
  52. print ("MQTT Not authorized")
  53. else:
  54. print ("Unable to connect to MQTT: Connection refused. Error code: " + str(rc))
  55. # publish a message to signal that the service is running
  56. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  57. client = mqtt.Client(client_id=MQTT_CLIENT_ID)
  58. client.on_connect = on_connect
  59. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  60. if not MQTT_USER is None:
  61. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  62. client.connect(MQTT_HOST, MQTT_PORT, 60)
  63. client.loop_start()
  64. # Queue for prepped frames, max size set to (number of cameras * 5)
  65. max_queue_size = len(CONFIG['cameras'].items())*5
  66. prepped_frame_queue = queue.Queue(max_queue_size)
  67. cameras = {}
  68. for name, config in CONFIG['cameras'].items():
  69. cameras[name] = Camera(name, FFMPEG_DEFAULT_CONFIG, config, prepped_frame_queue, client, MQTT_TOPIC_PREFIX)
  70. prepped_queue_processor = PreppedQueueProcessor(
  71. cameras,
  72. prepped_frame_queue
  73. )
  74. prepped_queue_processor.start()
  75. for name, camera in cameras.items():
  76. camera.start()
  77. print("Capture process for {}: {}".format(name, camera.get_capture_pid()))
  78. # create a flask app that encodes frames a mjpeg on demand
  79. app = Flask(__name__)
  80. @app.route('/')
  81. def ishealthy():
  82. # return a healh
  83. return "Frigate is running. Alive and healthy!"
  84. @app.route('/<camera_name>/best_person.jpg')
  85. def best_person(camera_name):
  86. if camera_name in cameras:
  87. best_person_frame = cameras[camera_name].get_best_person()
  88. if best_person_frame is None:
  89. best_person_frame = np.zeros((720,1280,3), np.uint8)
  90. ret, jpg = cv2.imencode('.jpg', best_person_frame)
  91. response = make_response(jpg.tobytes())
  92. response.headers['Content-Type'] = 'image/jpg'
  93. return response
  94. else:
  95. return f'Camera named {camera_name} not found', 404
  96. @app.route('/<camera_name>')
  97. def mjpeg_feed(camera_name):
  98. if camera_name in cameras:
  99. # return a multipart response
  100. return Response(imagestream(camera_name),
  101. mimetype='multipart/x-mixed-replace; boundary=frame')
  102. else:
  103. return f'Camera named {camera_name} not found', 404
  104. def imagestream(camera_name):
  105. while True:
  106. # max out at 5 FPS
  107. time.sleep(0.2)
  108. frame = cameras[camera_name].get_current_frame_with_objects()
  109. # encode the image into a jpg
  110. ret, jpg = cv2.imencode('.jpg', frame)
  111. yield (b'--frame\r\n'
  112. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + 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()