detect_objects.py 11 KB

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