detect_objects.py 9.5 KB

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