detect_objects.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import os
  2. import cv2
  3. import time
  4. import datetime
  5. import ctypes
  6. import logging
  7. import multiprocessing as mp
  8. from contextlib import closing
  9. import numpy as np
  10. import tensorflow as tf
  11. from object_detection.utils import label_map_util
  12. from object_detection.utils import visualization_utils as vis_util
  13. from flask import Flask, Response, make_response
  14. RTSP_URL = os.getenv('RTSP_URL')
  15. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  16. PATH_TO_CKPT = '/frozen_inference_graph.pb'
  17. # List of the strings that is used to add correct label for each box.
  18. PATH_TO_LABELS = '/label_map.pbtext'
  19. # TODO: make dynamic?
  20. NUM_CLASSES = 90
  21. # Loading label map
  22. label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
  23. categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,
  24. use_display_name=True)
  25. category_index = label_map_util.create_category_index(categories)
  26. def detect_objects(image_np, sess, detection_graph):
  27. # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  28. image_np_expanded = np.expand_dims(image_np, axis=0)
  29. image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
  30. # Each box represents a part of the image where a particular object was detected.
  31. boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
  32. # Each score represent how level of confidence for each of the objects.
  33. # Score is shown on the result image, together with the class label.
  34. scores = detection_graph.get_tensor_by_name('detection_scores:0')
  35. classes = detection_graph.get_tensor_by_name('detection_classes:0')
  36. num_detections = detection_graph.get_tensor_by_name('num_detections:0')
  37. # Actual detection.
  38. (boxes, scores, classes, num_detections) = sess.run(
  39. [boxes, scores, classes, num_detections],
  40. feed_dict={image_tensor: image_np_expanded})
  41. # build an array of detected objects
  42. objects = []
  43. for index, value in enumerate(classes[0]):
  44. object_dict = {}
  45. if scores[0, index] > 0.5:
  46. object_dict[(category_index.get(value)).get('name').encode('utf8')] = \
  47. scores[0, index]
  48. objects.append(object_dict)
  49. # draw boxes for detected objects on image
  50. vis_util.visualize_boxes_and_labels_on_image_array(
  51. image_np,
  52. np.squeeze(boxes),
  53. np.squeeze(classes).astype(np.int32),
  54. np.squeeze(scores),
  55. category_index,
  56. use_normalized_coordinates=True,
  57. line_thickness=4)
  58. return objects, image_np
  59. def main():
  60. # capture a single frame and check the frame shape so the correct array
  61. # size can be allocated in memory
  62. video = cv2.VideoCapture(RTSP_URL)
  63. ret, frame = video.read()
  64. if ret:
  65. frame_shape = frame.shape
  66. else:
  67. print("Unable to capture video stream")
  68. exit(1)
  69. video.release()
  70. # create shared value for storing the time the frame was captured
  71. # note: this must be a double even though the value you are storing
  72. # is a float. otherwise it stops updating the value in shared
  73. # memory. probably something to do with the size of the memory block
  74. shared_frame_time = mp.Value('d', 0.0)
  75. # compute the flattened array length from the array shape
  76. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  77. # create shared array for passing the image data from capture to detect_objects
  78. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  79. # create shared array for passing the image data from detect_objects to flask
  80. shared_output_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  81. # create a numpy array with the image shape from the shared memory array
  82. # this is used by flask to output an mjpeg stream
  83. frame_output_arr = tonumpyarray(shared_output_arr).reshape(frame_shape)
  84. capture_process = mp.Process(target=fetch_frames, args=(shared_arr, shared_frame_time, frame_shape))
  85. capture_process.daemon = True
  86. detection_process = mp.Process(target=process_frames, args=(shared_arr, shared_output_arr, shared_frame_time, frame_shape))
  87. detection_process.daemon = True
  88. capture_process.start()
  89. print("capture_process pid ", capture_process.pid)
  90. detection_process.start()
  91. print("detection_process pid ", detection_process.pid)
  92. app = Flask(__name__)
  93. @app.route('/')
  94. def index():
  95. # return a multipart response
  96. return Response(imagestream(),
  97. mimetype='multipart/x-mixed-replace; boundary=frame')
  98. def imagestream():
  99. while True:
  100. # max out at 5 FPS
  101. time.sleep(0.2)
  102. # convert back to BGR
  103. frame_bgr = cv2.cvtColor(frame_output_arr, cv2.COLOR_RGB2BGR)
  104. # encode the image into a jpg
  105. ret, jpg = cv2.imencode('.jpg', frame_bgr)
  106. yield (b'--frame\r\n'
  107. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  108. app.run(host='0.0.0.0', debug=False)
  109. capture_process.join()
  110. detection_process.join()
  111. # convert shared memory array into numpy array
  112. def tonumpyarray(mp_arr):
  113. return np.frombuffer(mp_arr.get_obj(), dtype=np.uint16)
  114. # fetch the frames as fast a possible, only decoding the frames when the
  115. # detection_process has consumed the current frame
  116. def fetch_frames(shared_arr, shared_frame_time, frame_shape):
  117. # convert shared memory array into numpy and shape into image array
  118. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  119. # start the video capture
  120. video = cv2.VideoCapture(RTSP_URL)
  121. # keep the buffer small so we minimize old data
  122. video.set(cv2.CAP_PROP_BUFFERSIZE,1)
  123. while True:
  124. # grab the frame, but dont decode it yet
  125. ret = video.grab()
  126. # snapshot the time the frame was grabbed
  127. frame_time = datetime.datetime.now()
  128. if ret:
  129. # if the detection_process is ready for the next frame decode it
  130. # otherwise skip this frame and move onto the next one
  131. if shared_frame_time.value == 0.0:
  132. # go ahead and decode the current frame
  133. ret, frame = video.retrieve()
  134. if ret:
  135. # copy the frame into the numpy array
  136. arr[:] = frame
  137. # signal to the detection_process by setting the shared_frame_time
  138. shared_frame_time.value = frame_time.timestamp()
  139. video.release()
  140. # do the actual object detection
  141. def process_frames(shared_arr, shared_output_arr, shared_frame_time, frame_shape):
  142. # shape shared input array into frame for processing
  143. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  144. # shape shared output array into frame so it can be copied into
  145. output_arr = tonumpyarray(shared_output_arr).reshape(frame_shape)
  146. # Load a (frozen) Tensorflow model into memory before the processing loop
  147. detection_graph = tf.Graph()
  148. with detection_graph.as_default():
  149. od_graph_def = tf.GraphDef()
  150. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  151. serialized_graph = fid.read()
  152. od_graph_def.ParseFromString(serialized_graph)
  153. tf.import_graph_def(od_graph_def, name='')
  154. sess = tf.Session(graph=detection_graph)
  155. no_frames_available = -1
  156. while True:
  157. # if there isnt a frame ready for processing
  158. if shared_frame_time.value == 0.0:
  159. # save the first time there were no frames available
  160. if no_frames_available == -1:
  161. no_frames_available = datetime.datetime.now().timestamp()
  162. # if there havent been any frames available in 30 seconds,
  163. # sleep to avoid using so much cpu if the camera feed is down
  164. if no_frames_available > 0 and (datetime.datetime.now().timestamp() - no_frames_available) > 30:
  165. time.sleep(1)
  166. print("sleeping because no frames have been available in a while")
  167. continue
  168. # we got a valid frame, so reset the timer
  169. no_frames_available = -1
  170. # if the frame is more than 0.5 second old, discard it
  171. if (datetime.datetime.now().timestamp() - shared_frame_time.value) > 0.5:
  172. # signal that we need a new frame
  173. shared_frame_time.value = 0.0
  174. continue
  175. # make a copy of the frame
  176. frame = arr.copy()
  177. frame_time = shared_frame_time.value
  178. # signal that the frame has been used so a new one will be ready
  179. shared_frame_time.value = 0.0
  180. # convert to RGB
  181. frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  182. # do the object detection
  183. objects, frame_overlay = detect_objects(frame_rgb, sess, detection_graph)
  184. # copy the output frame with the bounding boxes to the output array
  185. output_arr[:] = frame_overlay
  186. if(len(objects) > 0):
  187. print(objects)
  188. if __name__ == '__main__':
  189. mp.freeze_support()
  190. main()