detect_objects.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. import os
  2. import cv2
  3. import imutils
  4. import time
  5. import datetime
  6. import ctypes
  7. import logging
  8. import multiprocessing as mp
  9. import queue
  10. import threading
  11. import json
  12. import yaml
  13. from contextlib import closing
  14. import numpy as np
  15. from object_detection.utils import visualization_utils as vis_util
  16. from flask import Flask, Response, make_response, send_file
  17. import paho.mqtt.client as mqtt
  18. from frigate.util import tonumpyarray
  19. from frigate.mqtt import MqttMotionPublisher, MqttObjectPublisher
  20. from frigate.objects import ObjectParser, ObjectCleaner, BestPersonFrame
  21. from frigate.motion import detect_motion
  22. from frigate.video import fetch_frames, FrameTracker, Camera
  23. from frigate.object_detection import FramePrepper, PreppedQueueProcessor
  24. with open('/config/config.yml') as f:
  25. # use safe_load instead load
  26. CONFIG = yaml.safe_load(f)
  27. MQTT_HOST = CONFIG['mqtt']['host']
  28. MQTT_PORT = CONFIG.get('mqtt', {}).get('port', 1883)
  29. MQTT_TOPIC_PREFIX = CONFIG.get('mqtt', {}).get('topic_prefix', 'frigate')
  30. MQTT_USER = CONFIG.get('mqtt', {}).get('user')
  31. MQTT_PASS = CONFIG.get('mqtt', {}).get('password')
  32. WEB_PORT = CONFIG.get('web_port', 5000)
  33. DEBUG = (CONFIG.get('debug', '0') == '1')
  34. def main():
  35. # connect to mqtt and setup last will
  36. def on_connect(client, userdata, flags, rc):
  37. print("On connect called")
  38. # publish a message to signal that the service is running
  39. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  40. client = mqtt.Client()
  41. client.on_connect = on_connect
  42. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  43. if not MQTT_USER is None:
  44. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  45. client.connect(MQTT_HOST, MQTT_PORT, 60)
  46. client.loop_start()
  47. # Queue for prepped frames
  48. # TODO: set length to 1.5x the number of total regions
  49. prepped_frame_queue = queue.Queue(6)
  50. cameras = {}
  51. for name, config in CONFIG['cameras'].items():
  52. cameras[name] = Camera(name, config, prepped_frame_queue, client, MQTT_TOPIC_PREFIX)
  53. prepped_queue_processor = PreppedQueueProcessor(
  54. cameras,
  55. prepped_frame_queue
  56. )
  57. prepped_queue_processor.start()
  58. for name, camera in cameras.items():
  59. camera.start()
  60. print("Capture process for {}: {}".format(name, camera.get_capture_pid()))
  61. # create a flask app that encodes frames a mjpeg on demand
  62. app = Flask(__name__)
  63. @app.route('/<camera_name>/best_person.jpg')
  64. def best_person(camera_name):
  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. @app.route('/<camera_name>')
  73. def mjpeg_feed(camera_name):
  74. # return a multipart response
  75. return Response(imagestream(camera_name),
  76. mimetype='multipart/x-mixed-replace; boundary=frame')
  77. def imagestream(camera_name):
  78. while True:
  79. # max out at 5 FPS
  80. time.sleep(0.2)
  81. frame = cameras[camera_name].get_current_frame_with_objects()
  82. # encode the image into a jpg
  83. ret, jpg = cv2.imencode('.jpg', frame)
  84. yield (b'--frame\r\n'
  85. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  86. app.run(host='0.0.0.0', port=WEB_PORT, debug=False)
  87. camera.join()
  88. if __name__ == '__main__':
  89. main()