detect_objects.py 3.5 KB

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