detect_objects.py 9.7 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 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 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. # create shared array for storing 10 detected objects
  50. # note: this must be a double even though the value you are storing
  51. # is a float. otherwise it stops updating the value in shared
  52. # memory. probably something to do with the size of the memory block
  53. 'output_array': mp.Array(ctypes.c_double, 6*10)
  54. })
  55. # capture a single frame and check the frame shape so the correct array
  56. # size can be allocated in memory
  57. video = cv2.VideoCapture(RTSP_URL)
  58. ret, frame = video.read()
  59. if ret:
  60. frame_shape = frame.shape
  61. else:
  62. print("Unable to capture video stream")
  63. exit(1)
  64. video.release()
  65. # compute the flattened array length from the array shape
  66. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  67. # create shared array for storing the full frame image data
  68. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  69. # create shared value for storing the frame_time
  70. shared_frame_time = mp.Value('d', 0.0)
  71. # Lock to control access to the frame
  72. frame_lock = mp.Lock()
  73. # Condition for notifying that a new frame is ready
  74. frame_ready = mp.Condition()
  75. # Condition for notifying that motion status changed globally
  76. motion_changed = mp.Condition()
  77. # Condition for notifying that objects were parsed
  78. objects_parsed = mp.Condition()
  79. # Queue for detected objects
  80. object_queue = mp.Queue()
  81. # shape current frame so it can be treated as an image
  82. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  83. # start the process to capture frames from the RTSP stream and store in a shared array
  84. capture_process = mp.Process(target=fetch_frames, args=(shared_arr,
  85. shared_frame_time, frame_lock, frame_ready, frame_shape, RTSP_URL))
  86. capture_process.daemon = True
  87. # for each region, start a separate process for motion detection and object detection
  88. detection_processes = []
  89. motion_processes = []
  90. for region in regions:
  91. detection_process = mp.Process(target=detect_objects, args=(shared_arr,
  92. object_queue,
  93. shared_frame_time,
  94. frame_lock, frame_ready,
  95. region['motion_detected'],
  96. frame_shape,
  97. region['size'], region['x_offset'], region['y_offset'],
  98. region['min_person_area'],
  99. DEBUG))
  100. detection_process.daemon = True
  101. detection_processes.append(detection_process)
  102. motion_process = mp.Process(target=detect_motion, args=(shared_arr,
  103. shared_frame_time,
  104. frame_lock, frame_ready,
  105. region['motion_detected'],
  106. motion_changed,
  107. frame_shape,
  108. region['size'], region['x_offset'], region['y_offset'],
  109. region['min_object_size'], region['mask'],
  110. DEBUG))
  111. motion_process.daemon = True
  112. motion_processes.append(motion_process)
  113. # start a thread to store recent motion frames for processing
  114. frame_tracker = FrameTracker(frame_arr, shared_frame_time, frame_ready, frame_lock,
  115. recent_motion_frames, motion_changed, [region['motion_detected'] for region in regions])
  116. frame_tracker.start()
  117. # start a thread to store the highest scoring recent person frame
  118. best_person_frame = BestPersonFrame(objects_parsed, recent_motion_frames, DETECTED_OBJECTS,
  119. motion_changed, [region['motion_detected'] for region in regions])
  120. best_person_frame.start()
  121. # start a thread to parse objects from the queue
  122. object_parser = ObjectParser(object_queue, objects_parsed, DETECTED_OBJECTS)
  123. object_parser.start()
  124. # start a thread to expire objects from the detected objects list
  125. object_cleaner = ObjectCleaner(objects_parsed, DETECTED_OBJECTS,
  126. motion_changed, [region['motion_detected'] for region in regions])
  127. object_cleaner.start()
  128. # connect to mqtt and setup last will
  129. def on_connect(client, userdata, flags, rc):
  130. print("On connect called")
  131. # publish a message to signal that the service is running
  132. client.publish(MQTT_TOPIC_PREFIX+'/available', 'online', retain=True)
  133. client = mqtt.Client()
  134. client.on_connect = on_connect
  135. client.will_set(MQTT_TOPIC_PREFIX+'/available', payload='offline', qos=1, retain=True)
  136. if not MQTT_USER is None:
  137. client.username_pw_set(MQTT_USER, password=MQTT_PASS)
  138. client.connect(MQTT_HOST, 1883, 60)
  139. client.loop_start()
  140. # start a thread to publish object scores (currently only person)
  141. mqtt_publisher = MqttObjectPublisher(client, MQTT_TOPIC_PREFIX, objects_parsed, DETECTED_OBJECTS)
  142. mqtt_publisher.start()
  143. # start thread to publish motion status
  144. mqtt_motion_publisher = MqttMotionPublisher(client, MQTT_TOPIC_PREFIX, motion_changed,
  145. [region['motion_detected'] for region in regions])
  146. mqtt_motion_publisher.start()
  147. # start the process of capturing frames
  148. capture_process.start()
  149. print("capture_process pid ", capture_process.pid)
  150. # start the object detection processes
  151. for detection_process in detection_processes:
  152. detection_process.start()
  153. print("detection_process pid ", detection_process.pid)
  154. # start the motion detection processes
  155. for motion_process in motion_processes:
  156. motion_process.start()
  157. print("motion_process pid ", motion_process.pid)
  158. # create a flask app that encodes frames a mjpeg on demand
  159. app = Flask(__name__)
  160. @app.route('/best_person.jpg')
  161. def best_person():
  162. frame = np.zeros(frame_shape, np.uint8) if best_person_frame.best_frame is None else best_person_frame.best_frame
  163. ret, jpg = cv2.imencode('.jpg', frame)
  164. response = make_response(jpg.tobytes())
  165. response.headers['Content-Type'] = 'image/jpg'
  166. return response
  167. @app.route('/')
  168. def index():
  169. # return a multipart response
  170. return Response(imagestream(),
  171. mimetype='multipart/x-mixed-replace; boundary=frame')
  172. def imagestream():
  173. while True:
  174. # max out at 5 FPS
  175. time.sleep(0.2)
  176. # make a copy of the current detected objects
  177. detected_objects = DETECTED_OBJECTS.copy()
  178. # lock and make a copy of the current frame
  179. with frame_lock:
  180. frame = frame_arr.copy()
  181. # convert to RGB for drawing
  182. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  183. # draw the bounding boxes on the screen
  184. for obj in detected_objects:
  185. vis_util.draw_bounding_box_on_image_array(frame,
  186. obj['ymin'],
  187. obj['xmin'],
  188. obj['ymax'],
  189. obj['xmax'],
  190. color='red',
  191. thickness=2,
  192. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  193. use_normalized_coordinates=False)
  194. for region in regions:
  195. color = (255,255,255)
  196. if region['motion_detected'].is_set():
  197. color = (0,255,0)
  198. cv2.rectangle(frame, (region['x_offset'], region['y_offset']),
  199. (region['x_offset']+region['size'], region['y_offset']+region['size']),
  200. color, 2)
  201. # convert back to BGR
  202. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  203. # encode the image into a jpg
  204. ret, jpg = cv2.imencode('.jpg', frame)
  205. yield (b'--frame\r\n'
  206. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  207. app.run(host='0.0.0.0', debug=False)
  208. capture_process.join()
  209. for detection_process in detection_processes:
  210. detection_process.join()
  211. for motion_process in motion_processes:
  212. motion_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()