detect_objects.py 3.9 KB

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