detect_objects.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. import os
  2. import cv2
  3. import time
  4. import datetime
  5. import ctypes
  6. import logging
  7. import multiprocessing as mp
  8. import threading
  9. from contextlib import closing
  10. import numpy as np
  11. import tensorflow as tf
  12. from object_detection.utils import label_map_util
  13. from object_detection.utils import visualization_utils as vis_util
  14. from flask import Flask, Response, make_response
  15. RTSP_URL = os.getenv('RTSP_URL')
  16. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  17. PATH_TO_CKPT = '/frozen_inference_graph.pb'
  18. # List of the strings that is used to add correct label for each box.
  19. PATH_TO_LABELS = '/label_map.pbtext'
  20. # TODO: make dynamic?
  21. NUM_CLASSES = 90
  22. REGION_SIZE = 300
  23. REGION_X_OFFSET = 1250
  24. REGION_Y_OFFSET = 180
  25. DETECTED_OBJECTS = []
  26. # Loading label map
  27. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  28. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
  29. use_display_name=True)
  30. category_index = label_map_util.create_category_index(categories)
  31. def detect_objects(cropped_frame, sess, detection_graph, region_size, region_x_offset, region_y_offset):
  32. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  33. image_np_expanded = np.expand_dims(cropped_frame, axis=0)
  34. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  35. # Each box represents a part of the image where a particular object was detected.
  36. boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  37. # Each score represent how level of confidence for each of the objects.
  38. # Score is shown on the result image, together with the class label.
  39. scores = detection_graph.get_tensor_by_name('detection_scores:0')
  40. classes = detection_graph.get_tensor_by_name('detection_classes:0')
  41. num_detections = detection_graph.get_tensor_by_name('num_detections:0')
  42. # Actual detection.
  43. (boxes, scores, classes, num_detections) = sess.run(
  44. [boxes, scores, classes, num_detections],
  45. feed_dict={image_tensor: image_np_expanded})
  46. # build an array of detected objects
  47. objects = []
  48. for index, value in enumerate(classes[0]):
  49. score = scores[0, index]
  50. if score > 0.1:
  51. box = boxes[0, index].tolist()
  52. box[0] = (box[0] * region_size) + region_y_offset
  53. box[1] = (box[1] * region_size) + region_x_offset
  54. box[2] = (box[2] * region_size) + region_y_offset
  55. box[3] = (box[3] * region_size) + region_x_offset
  56. objects += [value, scores[0, index]] + box
  57. # only get the first 10 objects
  58. if len(objects) == 60:
  59. break
  60. return objects
  61. class ObjectParser(threading.Thread):
  62. def __init__(self, object_arrays):
  63. threading.Thread.__init__(self)
  64. self._object_arrays = object_arrays
  65. def run(self):
  66. global DETECTED_OBJECTS
  67. while True:
  68. detected_objects = []
  69. for object_array in self._object_arrays:
  70. object_index = 0
  71. while(object_index < 60 and object_array[object_index] > 0):
  72. object_class = object_array[object_index]
  73. detected_objects.append({
  74. 'name': str(category_index.get(object_class).get('name')),
  75. 'score': object_array[object_index+1],
  76. 'ymin': int(object_array[object_index+2]),
  77. 'xmin': int(object_array[object_index+3]),
  78. 'ymax': int(object_array[object_index+4]),
  79. 'xmax': int(object_array[object_index+5])
  80. })
  81. object_index += 6
  82. DETECTED_OBJECTS = detected_objects
  83. time.sleep(0.01)
  84. def main():
  85. # capture a single frame and check the frame shape so the correct array
  86. # size can be allocated in memory
  87. video = cv2.VideoCapture(RTSP_URL)
  88. ret, frame = video.read()
  89. if ret:
  90. frame_shape = frame.shape
  91. else:
  92. print("Unable to capture video stream")
  93. exit(1)
  94. video.release()
  95. # create shared value for storing the time the frame was captured
  96. # note: this must be a double even though the value you are storing
  97. # is a float. otherwise it stops updating the value in shared
  98. # memory. probably something to do with the size of the memory block
  99. shared_frame_time = mp.Value('d', 0.0)
  100. shared_frame_time2 = mp.Value('d', 0.0)
  101. # compute the flattened array length from the array shape
  102. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  103. # create shared array for storing the full frame image data
  104. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  105. # shape current frame so it can be treated as an image
  106. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  107. # create shared array for storing 10 detected objects
  108. shared_output_arr = mp.Array(ctypes.c_double, 6*10)
  109. shared_output_arr2 = mp.Array(ctypes.c_double, 6*10)
  110. capture_process = mp.Process(target=fetch_frames, args=(shared_arr, [shared_frame_time, shared_frame_time2], frame_shape))
  111. capture_process.daemon = True
  112. detection_process = mp.Process(target=process_frames, args=(shared_arr, shared_output_arr,
  113. shared_frame_time, frame_shape, REGION_SIZE, REGION_X_OFFSET, REGION_Y_OFFSET))
  114. detection_process.daemon = True
  115. detection_process2 = mp.Process(target=process_frames, args=(shared_arr, shared_output_arr2,
  116. shared_frame_time2, frame_shape, 1080, 0, 0))
  117. detection_process.daemon = True
  118. object_parser = ObjectParser([shared_output_arr, shared_output_arr2])
  119. object_parser.start()
  120. capture_process.start()
  121. print("capture_process pid ", capture_process.pid)
  122. detection_process.start()
  123. print("detection_process pid ", detection_process.pid)
  124. detection_process2.start()
  125. print("detection_process pid ", detection_process2.pid)
  126. app = Flask(__name__)
  127. @app.route('/')
  128. def index():
  129. # return a multipart response
  130. return Response(imagestream(),
  131. mimetype='multipart/x-mixed-replace; boundary=frame')
  132. def imagestream():
  133. global DETECTED_OBJECTS
  134. while True:
  135. # max out at 5 FPS
  136. time.sleep(0.2)
  137. # make a copy of the current detected objects
  138. detected_objects = DETECTED_OBJECTS.copy()
  139. # make a copy of the current frame
  140. frame = frame_arr.copy()
  141. # convert to RGB for drawing
  142. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  143. # draw the bounding boxes on the screen
  144. for obj in DETECTED_OBJECTS:
  145. vis_util.draw_bounding_box_on_image_array(frame,
  146. obj['ymin'],
  147. obj['xmin'],
  148. obj['ymax'],
  149. obj['xmax'],
  150. color='red',
  151. thickness=2,
  152. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  153. use_normalized_coordinates=False)
  154. cv2.rectangle(frame, (REGION_X_OFFSET, REGION_Y_OFFSET), (REGION_X_OFFSET+REGION_SIZE, REGION_Y_OFFSET+REGION_SIZE), (255,255,255), 2)
  155. # convert back to BGR
  156. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  157. # encode the image into a jpg
  158. ret, jpg = cv2.imencode('.jpg', frame)
  159. yield (b'--frame\r\n'
  160. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  161. app.run(host='0.0.0.0', debug=False)
  162. capture_process.join()
  163. detection_process.join()
  164. detection_process2.join()
  165. object_parser.join()
  166. # convert shared memory array into numpy array
  167. def tonumpyarray(mp_arr):
  168. return np.frombuffer(mp_arr.get_obj(), dtype=np.uint16)
  169. # fetch the frames as fast a possible, only decoding the frames when the
  170. # detection_process has consumed the current frame
  171. def fetch_frames(shared_arr, shared_frame_times, frame_shape):
  172. # convert shared memory array into numpy and shape into image array
  173. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  174. # start the video capture
  175. video = cv2.VideoCapture(RTSP_URL)
  176. # keep the buffer small so we minimize old data
  177. video.set(cv2.CAP_PROP_BUFFERSIZE,1)
  178. while True:
  179. # grab the frame, but dont decode it yet
  180. ret = video.grab()
  181. # snapshot the time the frame was grabbed
  182. frame_time = datetime.datetime.now()
  183. if ret:
  184. # if the detection_process is ready for the next frame decode it
  185. # otherwise skip this frame and move onto the next one
  186. if all(shared_frame_time.value == 0.0 for shared_frame_time in shared_frame_times):
  187. # go ahead and decode the current frame
  188. ret, frame = video.retrieve()
  189. if ret:
  190. arr[:] = frame
  191. # signal to the detection_processes by setting the shared_frame_time
  192. for shared_frame_time in shared_frame_times:
  193. shared_frame_time.value = frame_time.timestamp()
  194. else:
  195. # sleep a little to reduce CPU usage
  196. time.sleep(0.01)
  197. video.release()
  198. # do the actual object detection
  199. def process_frames(shared_arr, shared_output_arr, shared_frame_time, frame_shape, region_size, region_x_offset, region_y_offset):
  200. # shape shared input array into frame for processing
  201. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  202. # Load a (frozen) Tensorflow model into memory before the processing loop
  203. detection_graph = tf.Graph()
  204. with detection_graph.as_default():
  205. od_graph_def = tf.GraphDef()
  206. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  207. serialized_graph = fid.read()
  208. od_graph_def.ParseFromString(serialized_graph)
  209. tf.import_graph_def(od_graph_def, name='')
  210. sess = tf.Session(graph=detection_graph)
  211. no_frames_available = -1
  212. while True:
  213. # if there isnt a frame ready for processing
  214. if shared_frame_time.value == 0.0:
  215. # save the first time there were no frames available
  216. if no_frames_available == -1:
  217. no_frames_available = datetime.datetime.now().timestamp()
  218. # if there havent been any frames available in 30 seconds,
  219. # sleep to avoid using so much cpu if the camera feed is down
  220. if no_frames_available > 0 and (datetime.datetime.now().timestamp() - no_frames_available) > 30:
  221. time.sleep(1)
  222. print("sleeping because no frames have been available in a while")
  223. else:
  224. # rest a little bit to avoid maxing out the CPU
  225. time.sleep(0.01)
  226. continue
  227. # we got a valid frame, so reset the timer
  228. no_frames_available = -1
  229. # if the frame is more than 0.5 second old, discard it
  230. if (datetime.datetime.now().timestamp() - shared_frame_time.value) > 0.5:
  231. # signal that we need a new frame
  232. shared_frame_time.value = 0.0
  233. # rest a little bit to avoid maxing out the CPU
  234. time.sleep(0.01)
  235. continue
  236. # make a copy of the cropped frame
  237. cropped_frame = arr[region_y_offset:region_y_offset+region_size, region_x_offset:region_x_offset+region_size].copy()
  238. frame_time = shared_frame_time.value
  239. # signal that the frame has been used so a new one will be ready
  240. shared_frame_time.value = 0.0
  241. # convert to RGB
  242. cropped_frame_rgb = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2RGB)
  243. # do the object detection
  244. objects = detect_objects(cropped_frame_rgb, sess, detection_graph, region_size, region_x_offset, region_y_offset)
  245. # copy the detected objects to the output array, filling the array when needed
  246. shared_output_arr[:] = objects + [0.0] * (60-len(objects))
  247. if __name__ == '__main__':
  248. mp.freeze_support()
  249. main()