detect_objects.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. # compute the flattened array length from the array shape
  101. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  102. # create shared array for storing the full frame image data
  103. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  104. # shape current frame so it can be treated as an image
  105. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  106. # create shared array for storing 10 detected objects
  107. shared_output_arr = mp.Array(ctypes.c_double, 6*10)
  108. capture_process = mp.Process(target=fetch_frames, args=(shared_arr, shared_frame_time, frame_shape))
  109. capture_process.daemon = True
  110. detection_process = mp.Process(target=process_frames, args=(shared_arr, shared_output_arr, shared_frame_time, frame_shape, REGION_SIZE, REGION_X_OFFSET, REGION_Y_OFFSET))
  111. detection_process.daemon = True
  112. object_parser = ObjectParser([shared_output_arr])
  113. object_parser.start()
  114. capture_process.start()
  115. print("capture_process pid ", capture_process.pid)
  116. detection_process.start()
  117. print("detection_process pid ", detection_process.pid)
  118. app = Flask(__name__)
  119. @app.route('/')
  120. def index():
  121. # return a multipart response
  122. return Response(imagestream(),
  123. mimetype='multipart/x-mixed-replace; boundary=frame')
  124. def imagestream():
  125. global DETECTED_OBJECTS
  126. while True:
  127. # max out at 5 FPS
  128. time.sleep(0.2)
  129. # make a copy of the current detected objects
  130. detected_objects = DETECTED_OBJECTS.copy()
  131. # make a copy of the current frame
  132. frame = frame_arr.copy()
  133. # convert to RGB for drawing
  134. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  135. # draw the bounding boxes on the screen
  136. for obj in DETECTED_OBJECTS:
  137. vis_util.draw_bounding_box_on_image_array(frame,
  138. obj['ymin'],
  139. obj['xmin'],
  140. obj['ymax'],
  141. obj['xmax'],
  142. color='red',
  143. thickness=2,
  144. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  145. use_normalized_coordinates=False)
  146. cv2.rectangle(frame, (REGION_X_OFFSET, REGION_Y_OFFSET), (REGION_X_OFFSET+REGION_SIZE, REGION_Y_OFFSET+REGION_SIZE), (255,255,255), 2)
  147. # convert back to BGR
  148. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  149. # encode the image into a jpg
  150. ret, jpg = cv2.imencode('.jpg', frame)
  151. yield (b'--frame\r\n'
  152. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  153. app.run(host='0.0.0.0', debug=False)
  154. capture_process.join()
  155. detection_process.join()
  156. object_parser.join()
  157. # convert shared memory array into numpy array
  158. def tonumpyarray(mp_arr):
  159. return np.frombuffer(mp_arr.get_obj(), dtype=np.uint16)
  160. # fetch the frames as fast a possible, only decoding the frames when the
  161. # detection_process has consumed the current frame
  162. def fetch_frames(shared_arr, shared_frame_time, frame_shape):
  163. # convert shared memory array into numpy and shape into image array
  164. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  165. # start the video capture
  166. video = cv2.VideoCapture(RTSP_URL)
  167. # keep the buffer small so we minimize old data
  168. video.set(cv2.CAP_PROP_BUFFERSIZE,1)
  169. while True:
  170. # grab the frame, but dont decode it yet
  171. ret = video.grab()
  172. # snapshot the time the frame was grabbed
  173. frame_time = datetime.datetime.now()
  174. if ret:
  175. # if the detection_process is ready for the next frame decode it
  176. # otherwise skip this frame and move onto the next one
  177. if shared_frame_time.value == 0.0:
  178. # go ahead and decode the current frame
  179. ret, frame = video.retrieve()
  180. if ret:
  181. arr[:] = frame
  182. # signal to the detection_process by setting the shared_frame_time
  183. shared_frame_time.value = frame_time.timestamp()
  184. else:
  185. # sleep a little to reduce CPU usage
  186. time.sleep(0.01)
  187. video.release()
  188. # do the actual object detection
  189. def process_frames(shared_arr, shared_output_arr, shared_frame_time, frame_shape, region_size, region_x_offset, region_y_offset):
  190. # shape shared input array into frame for processing
  191. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  192. # Load a (frozen) Tensorflow model into memory before the processing loop
  193. detection_graph = tf.Graph()
  194. with detection_graph.as_default():
  195. od_graph_def = tf.GraphDef()
  196. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  197. serialized_graph = fid.read()
  198. od_graph_def.ParseFromString(serialized_graph)
  199. tf.import_graph_def(od_graph_def, name='')
  200. sess = tf.Session(graph=detection_graph)
  201. no_frames_available = -1
  202. while True:
  203. # if there isnt a frame ready for processing
  204. if shared_frame_time.value == 0.0:
  205. # save the first time there were no frames available
  206. if no_frames_available == -1:
  207. no_frames_available = datetime.datetime.now().timestamp()
  208. # if there havent been any frames available in 30 seconds,
  209. # sleep to avoid using so much cpu if the camera feed is down
  210. if no_frames_available > 0 and (datetime.datetime.now().timestamp() - no_frames_available) > 30:
  211. time.sleep(1)
  212. print("sleeping because no frames have been available in a while")
  213. else:
  214. # rest a little bit to avoid maxing out the CPU
  215. time.sleep(0.01)
  216. continue
  217. # we got a valid frame, so reset the timer
  218. no_frames_available = -1
  219. # if the frame is more than 0.5 second old, discard it
  220. if (datetime.datetime.now().timestamp() - shared_frame_time.value) > 0.5:
  221. # signal that we need a new frame
  222. shared_frame_time.value = 0.0
  223. # rest a little bit to avoid maxing out the CPU
  224. time.sleep(0.01)
  225. continue
  226. # make a copy of the cropped frame
  227. cropped_frame = arr[region_y_offset:region_y_offset+region_size, region_x_offset:region_x_offset+region_size].copy()
  228. frame_time = shared_frame_time.value
  229. # signal that the frame has been used so a new one will be ready
  230. shared_frame_time.value = 0.0
  231. # convert to RGB
  232. cropped_frame_rgb = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2RGB)
  233. # do the object detection
  234. objects = detect_objects(cropped_frame_rgb, sess, detection_graph, region_size, region_x_offset, region_y_offset)
  235. # copy the detected objects to the output array, filling the array when needed
  236. shared_output_arr[:] = objects + [0.0] * (60-len(objects))
  237. if __name__ == '__main__':
  238. mp.freeze_support()
  239. main()