detect_objects.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. # Shared memory array for passing prepped frame to tensorflow
  72. prepped_frame_array = mp.Array(ctypes.c_uint8, 300*300*3)
  73. # create shared value for storing the frame_time
  74. prepped_frame_time = mp.Value('d', 0.0)
  75. # Event for notifying that object detection needs a new frame
  76. prepped_frame_grabbed = mp.Event()
  77. # Event for notifying that new frame is ready for detection
  78. prepped_frame_ready = mp.Event()
  79. # Condition for notifying that objects were parsed
  80. objects_parsed = mp.Condition()
  81. # Queue for detected objects
  82. object_queue = mp.Queue()
  83. # Queue for prepped frames
  84. prepped_frame_queue = queue.Queue(len(regions)*2)
  85. # Array for passing original region box to compute object bounding box
  86. prepped_frame_box = mp.Array(ctypes.c_uint16, 3)
  87. # shape current frame so it can be treated as an image
  88. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  89. # start the process to capture frames from the RTSP stream and store in a shared array
  90. capture_process = mp.Process(target=fetch_frames, args=(shared_arr,
  91. shared_frame_time, frame_lock, frame_ready, frame_shape, RTSP_URL))
  92. capture_process.daemon = True
  93. # for each region, start a separate thread to resize the region and prep for detection
  94. detection_prep_threads = []
  95. for region in regions:
  96. detection_prep_threads.append(FramePrepper(
  97. frame_arr,
  98. shared_frame_time,
  99. frame_ready,
  100. frame_lock,
  101. region['size'], region['x_offset'], region['y_offset'],
  102. prepped_frame_queue
  103. ))
  104. prepped_queue_processor = PreppedQueueProcessor(
  105. prepped_frame_array,
  106. prepped_frame_time,
  107. prepped_frame_ready,
  108. prepped_frame_grabbed,
  109. prepped_frame_box,
  110. prepped_frame_queue
  111. )
  112. prepped_queue_processor.start()
  113. # create a process for object detection
  114. # if the coprocessor is doing the work, can this run as a thread
  115. # since it is waiting for IO?
  116. detection_process = mp.Process(target=detect_objects, args=(
  117. prepped_frame_array,
  118. prepped_frame_time,
  119. prepped_frame_ready,
  120. prepped_frame_grabbed,
  121. prepped_frame_box,
  122. object_queue, DEBUG
  123. ))
  124. detection_process.daemon = True
  125. # start a thread to store recent motion frames for processing
  126. frame_tracker = FrameTracker(frame_arr, shared_frame_time, frame_ready, frame_lock,
  127. recent_frames)
  128. frame_tracker.start()
  129. # start a thread to store the highest scoring recent person frame
  130. best_person_frame = BestPersonFrame(objects_parsed, recent_frames, DETECTED_OBJECTS)
  131. best_person_frame.start()
  132. # start a thread to parse objects from the queue
  133. object_parser = ObjectParser(object_queue, objects_parsed, DETECTED_OBJECTS, regions)
  134. object_parser.start()
  135. # start a thread to expire objects from the detected objects list
  136. object_cleaner = ObjectCleaner(objects_parsed, DETECTED_OBJECTS)
  137. object_cleaner.start()
  138. # connect to mqtt and setup last will
  139. def on_connect(client, userdata, flags, rc):
  140. print("On connect called")
  141. # publish a message to signal that the service is running
  142. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  143. client = mqtt.Client()
  144. client.on_connect = on_connect
  145. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  146. if not MQTT_USER is None:
  147. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  148. client.connect(MQTT_HOST, 1883, 60)
  149. client.loop_start()
  150. # start a thread to publish object scores (currently only person)
  151. mqtt_publisher = MqttObjectPublisher(client, MQTT_TOPIC_PREFIX, objects_parsed, DETECTED_OBJECTS)
  152. mqtt_publisher.start()
  153. # start the process of capturing frames
  154. capture_process.start()
  155. print("capture_process pid ", capture_process.pid)
  156. # start the object detection prep threads
  157. for detection_prep_thread in detection_prep_threads:
  158. detection_prep_thread.start()
  159. detection_process.start()
  160. print("detection_process pid ", detection_process.pid)
  161. # create a flask app that encodes frames a mjpeg on demand
  162. app = Flask(__name__)
  163. @app.route('/best_person.jpg')
  164. def best_person():
  165. frame = np.zeros(frame_shape, np.uint8) if best_person_frame.best_frame is None else best_person_frame.best_frame
  166. ret, jpg = cv2.imencode('.jpg', frame)
  167. response = make_response(jpg.tobytes())
  168. response.headers['Content-Type'] = 'image/jpg'
  169. return response
  170. @app.route('/')
  171. def index():
  172. # return a multipart response
  173. return Response(imagestream(),
  174. mimetype='multipart/x-mixed-replace; boundary=frame')
  175. def imagestream():
  176. while True:
  177. # max out at 5 FPS
  178. time.sleep(0.2)
  179. # make a copy of the current detected objects
  180. detected_objects = DETECTED_OBJECTS.copy()
  181. # lock and make a copy of the current frame
  182. with frame_lock:
  183. frame = frame_arr.copy()
  184. # convert to RGB for drawing
  185. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  186. # draw the bounding boxes on the screen
  187. for obj in detected_objects:
  188. vis_util.draw_bounding_box_on_image_array(frame,
  189. obj['ymin'],
  190. obj['xmin'],
  191. obj['ymax'],
  192. obj['xmax'],
  193. color='red',
  194. thickness=2,
  195. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  196. use_normalized_coordinates=False)
  197. for region in regions:
  198. color = (255,255,255)
  199. cv2.rectangle(frame, (region['x_offset'], region['y_offset']),
  200. (region['x_offset']+region['size'], region['y_offset']+region['size']),
  201. color, 2)
  202. # convert back to BGR
  203. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  204. # encode the image into a jpg
  205. ret, jpg = cv2.imencode('.jpg', frame)
  206. yield (b'--frame\r\n'
  207. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  208. app.run(host='0.0.0.0', debug=False)
  209. capture_process.join()
  210. for detection_prep_thread in detection_prep_threads:
  211. detection_prep_thread.join()
  212. detection_process.join()
  213. frame_tracker.join()
  214. best_person_frame.join()
  215. object_parser.join()
  216. object_cleaner.join()
  217. mqtt_publisher.join()
  218. if __name__ == '__main__':
  219. main()