detect_objects.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. import tensorflow as tf
  14. from object_detection.utils import label_map_util
  15. from object_detection.utils import visualization_utils as vis_util
  16. from flask import Flask, Response, make_response
  17. import paho.mqtt.client as mqtt
  18. RTSP_URL = os.getenv('RTSP_URL')
  19. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  20. PATH_TO_CKPT = '/frozen_inference_graph.pb'
  21. # List of the strings that is used to add correct label for each box.
  22. PATH_TO_LABELS = '/label_map.pbtext'
  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. # TODO: make dynamic?
  27. NUM_CLASSES = 90
  28. # REGIONS = "350,0,300,50:400,350,250,50:400,750,250,50"
  29. # REGIONS = "400,350,250,50"
  30. REGIONS = os.getenv('REGIONS')
  31. DETECTED_OBJECTS = []
  32. # Loading label map
  33. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  34. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
  35. use_display_name=True)
  36. category_index = label_map_util.create_category_index(categories)
  37. def detect_objects(cropped_frame, sess, detection_graph, region_size, region_x_offset, region_y_offset):
  38. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  39. image_np_expanded = np.expand_dims(cropped_frame, axis=0)
  40. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  41. # Each box represents a part of the image where a particular object was detected.
  42. boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  43. # Each score represent how level of confidence for each of the objects.
  44. # Score is shown on the result image, together with the class label.
  45. scores = detection_graph.get_tensor_by_name('detection_scores:0')
  46. classes = detection_graph.get_tensor_by_name('detection_classes:0')
  47. num_detections = detection_graph.get_tensor_by_name('num_detections:0')
  48. # Actual detection.
  49. (boxes, scores, classes, num_detections) = sess.run(
  50. [boxes, scores, classes, num_detections],
  51. feed_dict={image_tensor: image_np_expanded})
  52. # build an array of detected objects
  53. objects = []
  54. for index, value in enumerate(classes[0]):
  55. score = scores[0, index]
  56. if score > 0.1:
  57. box = boxes[0, index].tolist()
  58. box[0] = (box[0] * region_size) + region_y_offset
  59. box[1] = (box[1] * region_size) + region_x_offset
  60. box[2] = (box[2] * region_size) + region_y_offset
  61. box[3] = (box[3] * region_size) + region_x_offset
  62. objects += [value, scores[0, index]] + box
  63. # only get the first 10 objects
  64. if len(objects) == 60:
  65. break
  66. return objects
  67. class ObjectParser(threading.Thread):
  68. def __init__(self, object_arrays):
  69. threading.Thread.__init__(self)
  70. self._object_arrays = object_arrays
  71. def run(self):
  72. global DETECTED_OBJECTS
  73. while True:
  74. detected_objects = []
  75. for object_array in self._object_arrays:
  76. object_index = 0
  77. while(object_index < 60 and object_array[object_index] > 0):
  78. object_class = object_array[object_index]
  79. detected_objects.append({
  80. 'name': str(category_index.get(object_class).get('name')),
  81. 'score': object_array[object_index+1],
  82. 'ymin': int(object_array[object_index+2]),
  83. 'xmin': int(object_array[object_index+3]),
  84. 'ymax': int(object_array[object_index+4]),
  85. 'xmax': int(object_array[object_index+5])
  86. })
  87. object_index += 6
  88. DETECTED_OBJECTS = detected_objects
  89. time.sleep(0.1)
  90. class MqttPublisher(threading.Thread):
  91. def __init__(self, host, topic_prefix, object_classes, motion_flags):
  92. threading.Thread.__init__(self)
  93. self.client = mqtt.Client()
  94. self.client.will_set(topic_prefix+'/available', payload='offline', qos=1, retain=True)
  95. self.client.connect(host, 1883, 60)
  96. self.client.loop_start()
  97. self.client.publish(topic_prefix+'/available', 'online', retain=True)
  98. self.topic_prefix = topic_prefix
  99. self.object_classes = object_classes
  100. self.motion_flags = motion_flags
  101. def run(self):
  102. global DETECTED_OBJECTS
  103. last_sent_payload = ""
  104. last_motion = ""
  105. while True:
  106. # initialize the payload
  107. payload = {}
  108. for obj in self.object_classes:
  109. payload[obj] = []
  110. # loop over detected objects and populate
  111. # the payload
  112. detected_objects = DETECTED_OBJECTS.copy()
  113. for obj in detected_objects:
  114. if obj['name'] in self.object_classes:
  115. payload[obj['name']].append(obj)
  116. new_payload = json.dumps(payload, sort_keys=True)
  117. if new_payload != last_sent_payload:
  118. last_sent_payload = new_payload
  119. self.client.publish(self.topic_prefix+'/objects', new_payload, retain=False)
  120. motion_status = 'OFF'
  121. if any(obj.value == 1 for obj in self.motion_flags):
  122. motion_status = 'ON'
  123. if motion_status != last_motion:
  124. last_motion = motion_status
  125. self.client.publish(self.topic_prefix+'/motion', motion_status, retain=False)
  126. time.sleep(0.1)
  127. def main():
  128. # Parse selected regions
  129. regions = []
  130. for region_string in REGIONS.split(':'):
  131. region_parts = region_string.split(',')
  132. regions.append({
  133. 'size': int(region_parts[0]),
  134. 'x_offset': int(region_parts[1]),
  135. 'y_offset': int(region_parts[2]),
  136. 'min_object_size': int(region_parts[3]),
  137. # shared value for signaling to the capture process that we are ready for the next frame
  138. # (1 for ready 0 for not ready)
  139. 'ready_for_frame': mp.Value('i', 1),
  140. # shared value for motion detection signal (1 for motion 0 for no motion)
  141. 'motion_detected': mp.Value('i', 0),
  142. # create shared array for storing 10 detected objects
  143. # note: this must be a double even though the value you are storing
  144. # is a float. otherwise it stops updating the value in shared
  145. # memory. probably something to do with the size of the memory block
  146. 'output_array': mp.Array(ctypes.c_double, 6*10)
  147. })
  148. # capture a single frame and check the frame shape so the correct array
  149. # size can be allocated in memory
  150. video = cv2.VideoCapture(RTSP_URL)
  151. ret, frame = video.read()
  152. if ret:
  153. frame_shape = frame.shape
  154. else:
  155. print("Unable to capture video stream")
  156. exit(1)
  157. video.release()
  158. # compute the flattened array length from the array shape
  159. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  160. # create shared array for storing the full frame image data
  161. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  162. # create shared value for storing the frame_time
  163. shared_frame_time = mp.Value('d', 0.0)
  164. # shape current frame so it can be treated as an image
  165. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  166. capture_process = mp.Process(target=fetch_frames, args=(shared_arr,
  167. shared_frame_time, [region['ready_for_frame'] for region in regions], frame_shape))
  168. capture_process.daemon = True
  169. detection_processes = []
  170. for index, region in enumerate(regions):
  171. detection_process = mp.Process(target=process_frames, args=(shared_arr,
  172. region['output_array'],
  173. shared_frame_time,
  174. region['motion_detected'],
  175. frame_shape,
  176. region['size'], region['x_offset'], region['y_offset']))
  177. detection_process.daemon = True
  178. detection_processes.append(detection_process)
  179. motion_processes = []
  180. for index, region in enumerate(regions):
  181. motion_process = mp.Process(target=detect_motion, args=(shared_arr,
  182. shared_frame_time,
  183. region['ready_for_frame'],
  184. region['motion_detected'],
  185. frame_shape,
  186. region['size'], region['x_offset'], region['y_offset'],
  187. region['min_object_size']))
  188. motion_process.daemon = True
  189. motion_processes.append(motion_process)
  190. object_parser = ObjectParser([region['output_array'] for region in regions])
  191. object_parser.start()
  192. mqtt_publisher = MqttPublisher(MQTT_HOST, MQTT_TOPIC_PREFIX,
  193. MQTT_OBJECT_CLASSES.split(','),
  194. [region['motion_detected'] for region in regions])
  195. mqtt_publisher.start()
  196. capture_process.start()
  197. print("capture_process pid ", capture_process.pid)
  198. for detection_process in detection_processes:
  199. detection_process.start()
  200. print("detection_process pid ", detection_process.pid)
  201. for motion_process in motion_processes:
  202. motion_process.start()
  203. print("motion_process pid ", motion_process.pid)
  204. app = Flask(__name__)
  205. @app.route('/')
  206. def index():
  207. # return a multipart response
  208. return Response(imagestream(),
  209. mimetype='multipart/x-mixed-replace; boundary=frame')
  210. def imagestream():
  211. global DETECTED_OBJECTS
  212. while True:
  213. # max out at 5 FPS
  214. time.sleep(0.2)
  215. # make a copy of the current detected objects
  216. detected_objects = DETECTED_OBJECTS.copy()
  217. # make a copy of the current frame
  218. frame = frame_arr.copy()
  219. # convert to RGB for drawing
  220. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  221. # draw the bounding boxes on the screen
  222. for obj in detected_objects:
  223. vis_util.draw_bounding_box_on_image_array(frame,
  224. obj['ymin'],
  225. obj['xmin'],
  226. obj['ymax'],
  227. obj['xmax'],
  228. color='red',
  229. thickness=2,
  230. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  231. use_normalized_coordinates=False)
  232. for region in regions:
  233. color = (255,255,255)
  234. if region['motion_detected'].value == 1:
  235. color = (0,255,0)
  236. cv2.rectangle(frame, (region['x_offset'], region['y_offset']),
  237. (region['x_offset']+region['size'], region['y_offset']+region['size']),
  238. color, 2)
  239. cv2.putText(frame, datetime.datetime.now().strftime("%H:%M:%S"), (1125, 20),
  240. cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
  241. # convert back to BGR
  242. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  243. # encode the image into a jpg
  244. ret, jpg = cv2.imencode('.jpg', frame)
  245. yield (b'--frame\r\n'
  246. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  247. app.run(host='0.0.0.0', debug=False)
  248. capture_process.join()
  249. for detection_process in detection_processes:
  250. detection_process.join()
  251. for motion_process in motion_processes:
  252. motion_process.join()
  253. object_parser.join()
  254. mqtt_publisher.join()
  255. # convert shared memory array into numpy array
  256. def tonumpyarray(mp_arr):
  257. return np.frombuffer(mp_arr.get_obj(), dtype=np.uint16)
  258. # fetch the frames as fast a possible, only decoding the frames when the
  259. # detection_process has consumed the current frame
  260. def fetch_frames(shared_arr, shared_frame_time, ready_for_frame_flags, frame_shape):
  261. # convert shared memory array into numpy and shape into image array
  262. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  263. # start the video capture
  264. video = cv2.VideoCapture(RTSP_URL)
  265. # keep the buffer small so we minimize old data
  266. video.set(cv2.CAP_PROP_BUFFERSIZE,1)
  267. while True:
  268. # grab the frame, but dont decode it yet
  269. ret = video.grab()
  270. # snapshot the time the frame was grabbed
  271. frame_time = datetime.datetime.now()
  272. if ret:
  273. # if the anyone is ready for the next frame decode it
  274. # otherwise skip this frame and move onto the next one
  275. if any(flag.value == 1 for flag in ready_for_frame_flags):
  276. # go ahead and decode the current frame
  277. ret, frame = video.retrieve()
  278. if ret:
  279. arr[:] = frame
  280. shared_frame_time.value = frame_time.timestamp()
  281. # signal to the detection_processes by setting the shared_frame_time
  282. for flag in ready_for_frame_flags:
  283. flag.value = 0
  284. else:
  285. # sleep a little to reduce CPU usage
  286. time.sleep(0.1)
  287. video.release()
  288. # do the actual object detection
  289. def process_frames(shared_arr, shared_output_arr, shared_frame_time, shared_motion, frame_shape, region_size, region_x_offset, region_y_offset):
  290. # shape shared input array into frame for processing
  291. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  292. # Load a (frozen) Tensorflow model into memory before the processing loop
  293. detection_graph = tf.Graph()
  294. with detection_graph.as_default():
  295. od_graph_def = tf.GraphDef()
  296. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  297. serialized_graph = fid.read()
  298. od_graph_def.ParseFromString(serialized_graph)
  299. tf.import_graph_def(od_graph_def, name='')
  300. sess = tf.Session(graph=detection_graph)
  301. no_frames_available = -1
  302. frame_time = 0.0
  303. while True:
  304. now = datetime.datetime.now().timestamp()
  305. # if there is no motion detected
  306. if shared_motion.value == 0:
  307. time.sleep(0.1)
  308. continue
  309. # if there isnt a new frame ready for processing
  310. if shared_frame_time.value == frame_time:
  311. # save the first time there were no frames available
  312. if no_frames_available == -1:
  313. no_frames_available = now
  314. # if there havent been any frames available in 30 seconds,
  315. # sleep to avoid using so much cpu if the camera feed is down
  316. if no_frames_available > 0 and (now - no_frames_available) > 30:
  317. time.sleep(1)
  318. print("sleeping because no frames have been available in a while")
  319. else:
  320. # rest a little bit to avoid maxing out the CPU
  321. time.sleep(0.1)
  322. continue
  323. # we got a valid frame, so reset the timer
  324. no_frames_available = -1
  325. # if the frame is more than 0.5 second old, ignore it
  326. if (now - shared_frame_time.value) > 0.5:
  327. # rest a little bit to avoid maxing out the CPU
  328. time.sleep(0.1)
  329. continue
  330. # make a copy of the cropped frame
  331. cropped_frame = arr[region_y_offset:region_y_offset+region_size, region_x_offset:region_x_offset+region_size].copy()
  332. frame_time = shared_frame_time.value
  333. # convert to RGB
  334. cropped_frame_rgb = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2RGB)
  335. # do the object detection
  336. objects = detect_objects(cropped_frame_rgb, sess, detection_graph, region_size, region_x_offset, region_y_offset)
  337. # copy the detected objects to the output array, filling the array when needed
  338. shared_output_arr[:] = objects + [0.0] * (60-len(objects))
  339. # do the actual object detection
  340. def detect_motion(shared_arr, shared_frame_time, ready_for_frame, shared_motion, frame_shape, region_size, region_x_offset, region_y_offset, min_motion_area):
  341. # shape shared input array into frame for processing
  342. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  343. no_frames_available = -1
  344. avg_frame = None
  345. last_motion = -1
  346. frame_time = 0.0
  347. while True:
  348. now = datetime.datetime.now().timestamp()
  349. # if it has been 30 seconds since the last motion, clear the flag
  350. if last_motion > 0 and (now - last_motion) > 30:
  351. last_motion = -1
  352. shared_motion.value = 0
  353. # if there isnt a frame ready for processing
  354. if shared_frame_time.value == frame_time:
  355. # save the first time there were no frames available
  356. if no_frames_available == -1:
  357. no_frames_available = now
  358. # if there havent been any frames available in 30 seconds,
  359. # sleep to avoid using so much cpu if the camera feed is down
  360. if no_frames_available > 0 and (now - no_frames_available) > 30:
  361. time.sleep(1)
  362. print("sleeping because no frames have been available in a while")
  363. else:
  364. # rest a little bit to avoid maxing out the CPU
  365. time.sleep(0.1)
  366. if ready_for_frame.value == 0:
  367. ready_for_frame.value = 1
  368. continue
  369. # we got a valid frame, so reset the timer
  370. no_frames_available = -1
  371. # if the frame is more than 0.5 second old, discard it
  372. if (now - shared_frame_time.value) > 0.5:
  373. # signal that we need a new frame
  374. ready_for_frame.value = 1
  375. # rest a little bit to avoid maxing out the CPU
  376. time.sleep(0.1)
  377. continue
  378. # make a copy of the cropped frame
  379. cropped_frame = arr[region_y_offset:region_y_offset+region_size, region_x_offset:region_x_offset+region_size].copy().astype('uint8')
  380. frame_time = shared_frame_time.value
  381. # signal that the frame has been used so a new one will be ready
  382. ready_for_frame.value = 1
  383. # convert to grayscale
  384. gray = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2GRAY)
  385. # apply gaussian blur
  386. gray = cv2.GaussianBlur(gray, (21, 21), 0)
  387. if avg_frame is None:
  388. avg_frame = gray.copy().astype("float")
  389. continue
  390. # look at the delta from the avg_frame
  391. cv2.accumulateWeighted(gray, avg_frame, 0.5)
  392. frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg_frame))
  393. thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
  394. # dilate the thresholded image to fill in holes, then find contours
  395. # on thresholded image
  396. thresh = cv2.dilate(thresh, None, iterations=2)
  397. cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
  398. cv2.CHAIN_APPROX_SIMPLE)
  399. cnts = imutils.grab_contours(cnts)
  400. # loop over the contours
  401. for c in cnts:
  402. # if the contour is big enough report motion
  403. if cv2.contourArea(c) > min_motion_area:
  404. last_motion = now
  405. shared_motion.value = 1
  406. break
  407. if __name__ == '__main__':
  408. mp.freeze_support()
  409. main()