detect_objects.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. from contextlib import closing
  13. import numpy as np
  14. from object_detection.utils import visualization_utils as vis_util
  15. from flask import Flask, Response, make_response, send_file
  16. import paho.mqtt.client as mqtt
  17. from frigate.util import tonumpyarray
  18. from frigate.mqtt import MqttMotionPublisher, MqttObjectPublisher
  19. from frigate.objects import ObjectParser, ObjectCleaner, BestPersonFrame
  20. from frigate.motion import detect_motion
  21. from frigate.video import fetch_frames, FrameTracker
  22. from frigate.object_detection import FramePrepper, PreppedQueueProcessor, detect_objects
  23. RTSP_URL = os.getenv('RTSP_URL')
  24. MQTT_HOST = os.getenv('MQTT_HOST')
  25. MQTT_USER = os.getenv('MQTT_USER')
  26. MQTT_PASS = os.getenv('MQTT_PASS')
  27. MQTT_TOPIC_PREFIX = os.getenv('MQTT_TOPIC_PREFIX')
  28. # REGIONS = "300,0,0,2000,200,no-mask-300.bmp:300,300,0,2000,200,no-mask-300.bmp:300,600,0,2000,200,no-mask-300.bmp:300,900,0,2000,200,no-mask-300.bmp:300,0,300,2000,200,no-mask-300.bmp:300,300,300,2000,200,no-mask-300.bmp:300,600,300,2000,200,no-mask-300.bmp:300,900,300,2000,200,no-mask-300.bmp"
  29. # REGIONS = "400,350,250,50"
  30. REGIONS = os.getenv('REGIONS')
  31. DEBUG = (os.getenv('DEBUG') == '1')
  32. def main():
  33. DETECTED_OBJECTS = []
  34. recent_frames = {}
  35. # Parse selected regions
  36. regions = []
  37. for region_string in REGIONS.split(':'):
  38. region_parts = region_string.split(',')
  39. regions.append({
  40. 'size': int(region_parts[0]),
  41. 'x_offset': int(region_parts[1]),
  42. 'y_offset': int(region_parts[2]),
  43. 'min_person_area': int(region_parts[3]),
  44. # array for prepped frame with shape (1, 300, 300, 3)
  45. 'prepped_frame_array': mp.Array(ctypes.c_uint8, 300*300*3),
  46. # shared value for storing the prepped_frame_time
  47. 'prepped_frame_time': mp.Value('d', 0.0),
  48. # Lock to control access to the prepped frame
  49. 'prepped_frame_lock': mp.Lock()
  50. })
  51. # capture a single frame and check the frame shape so the correct array
  52. # size can be allocated in memory
  53. video = cv2.VideoCapture(RTSP_URL)
  54. ret, frame = video.read()
  55. if ret:
  56. frame_shape = frame.shape
  57. else:
  58. print("Unable to capture video stream")
  59. exit(1)
  60. video.release()
  61. # compute the flattened array length from the array shape
  62. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  63. # create shared array for storing the full frame image data
  64. shared_arr = mp.Array(ctypes.c_uint8, flat_array_length)
  65. # create shared value for storing the frame_time
  66. shared_frame_time = mp.Value('d', 0.0)
  67. # Lock to control access to the frame
  68. frame_lock = mp.Lock()
  69. # Condition for notifying that a new frame is ready
  70. frame_ready = mp.Condition()
  71. # Condition for notifying that objects were parsed
  72. objects_parsed = mp.Condition()
  73. # Queue for detected objects
  74. object_queue = queue.Queue()
  75. # Queue for prepped frames
  76. prepped_frame_queue = queue.Queue(len(regions)*2)
  77. # shape current frame so it can be treated as an image
  78. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  79. # start the process to capture frames from the RTSP stream and store in a shared array
  80. capture_process = mp.Process(target=fetch_frames, args=(shared_arr,
  81. shared_frame_time, frame_lock, frame_ready, frame_shape, RTSP_URL))
  82. capture_process.daemon = True
  83. # for each region, start a separate thread to resize the region and prep for detection
  84. detection_prep_threads = []
  85. for region in regions:
  86. detection_prep_threads.append(FramePrepper(
  87. frame_arr,
  88. shared_frame_time,
  89. frame_ready,
  90. frame_lock,
  91. region['size'], region['x_offset'], region['y_offset'],
  92. prepped_frame_queue
  93. ))
  94. prepped_queue_processor = PreppedQueueProcessor(
  95. prepped_frame_queue,
  96. object_queue
  97. )
  98. prepped_queue_processor.start()
  99. # start a thread to store recent motion frames for processing
  100. frame_tracker = FrameTracker(frame_arr, shared_frame_time, frame_ready, frame_lock,
  101. recent_frames)
  102. frame_tracker.start()
  103. # start a thread to store the highest scoring recent person frame
  104. best_person_frame = BestPersonFrame(objects_parsed, recent_frames, DETECTED_OBJECTS)
  105. best_person_frame.start()
  106. # start a thread to parse objects from the queue
  107. object_parser = ObjectParser(object_queue, objects_parsed, DETECTED_OBJECTS, regions)
  108. object_parser.start()
  109. # start a thread to expire objects from the detected objects list
  110. object_cleaner = ObjectCleaner(objects_parsed, DETECTED_OBJECTS)
  111. object_cleaner.start()
  112. # connect to mqtt and setup last will
  113. def on_connect(client, userdata, flags, rc):
  114. print("On connect called")
  115. # publish a message to signal that the service is running
  116. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  117. client = mqtt.Client()
  118. client.on_connect = on_connect
  119. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  120. if not MQTT_USER is None:
  121. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  122. client.connect(MQTT_HOST, 1883, 60)
  123. client.loop_start()
  124. # start a thread to publish object scores (currently only person)
  125. mqtt_publisher = MqttObjectPublisher(client, MQTT_TOPIC_PREFIX, objects_parsed, DETECTED_OBJECTS)
  126. mqtt_publisher.start()
  127. # start the process of capturing frames
  128. capture_process.start()
  129. print("capture_process pid ", capture_process.pid)
  130. # start the object detection prep threads
  131. for detection_prep_thread in detection_prep_threads:
  132. detection_prep_thread.start()
  133. # create a flask app that encodes frames a mjpeg on demand
  134. app = Flask(__name__)
  135. @app.route('/best_person.jpg')
  136. def best_person():
  137. frame = np.zeros(frame_shape, np.uint8) if best_person_frame.best_frame is None else best_person_frame.best_frame
  138. ret, jpg = cv2.imencode('.jpg', frame)
  139. response = make_response(jpg.tobytes())
  140. response.headers['Content-Type'] = 'image/jpg'
  141. return response
  142. @app.route('/')
  143. def index():
  144. # return a multipart response
  145. return Response(imagestream(),
  146. mimetype='multipart/x-mixed-replace; boundary=frame')
  147. def imagestream():
  148. while True:
  149. # max out at 5 FPS
  150. time.sleep(0.2)
  151. # make a copy of the current detected objects
  152. detected_objects = DETECTED_OBJECTS.copy()
  153. # lock and make a copy of the current frame
  154. with frame_lock:
  155. frame = frame_arr.copy()
  156. # convert to RGB for drawing
  157. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  158. # draw the bounding boxes on the screen
  159. for obj in detected_objects:
  160. vis_util.draw_bounding_box_on_image_array(frame,
  161. obj['ymin'],
  162. obj['xmin'],
  163. obj['ymax'],
  164. obj['xmax'],
  165. color='red',
  166. thickness=2,
  167. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  168. use_normalized_coordinates=False)
  169. for region in regions:
  170. color = (255,255,255)
  171. cv2.rectangle(frame, (region['x_offset'], region['y_offset']),
  172. (region['x_offset']+region['size'], region['y_offset']+region['size']),
  173. color, 2)
  174. # convert back to BGR
  175. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  176. # encode the image into a jpg
  177. ret, jpg = cv2.imencode('.jpg', frame)
  178. yield (b'--frame\r\n'
  179. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  180. app.run(host='0.0.0.0', debug=False)
  181. capture_process.join()
  182. for detection_prep_thread in detection_prep_threads:
  183. detection_prep_thread.join()
  184. frame_tracker.join()
  185. best_person_frame.join()
  186. object_parser.join()
  187. object_cleaner.join()
  188. mqtt_publisher.join()
  189. if __name__ == '__main__':
  190. main()