detect_objects.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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(cropped_frame, full_frame, 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(cropped_frame, 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.1:
  46. object_dict[(category_index.get(value)).get('name').encode('utf8')] = \
  47. scores[0, index]
  48. objects.append(object_dict)
  49. squeezed_boxes = np.squeeze(boxes)
  50. squeezed_scores = np.squeeze(scores)
  51. if(len(objects)>0):
  52. # reposition bounding box based on full frame
  53. for i, box in enumerate(squeezed_boxes):
  54. if squeezed_scores[i] > .1:
  55. ymin = ((box[0] * 300) + 200)/1080 # ymin
  56. xmin = ((box[1] * 300) + 1300)/1920 # xmin
  57. xmax = ((box[2] * 300) + 200)/1080 # ymax
  58. ymax = ((box[3] * 300) + 1300)/1920 # xmax
  59. print("ymin", box[0] * 300, ymin)
  60. print("xmin", box[1] * 300, xmin)
  61. print("ymax", box[2] * 300, ymax)
  62. print("xmax", box[3] * 300, xmax)
  63. # draw boxes for detected objects on image
  64. vis_util.visualize_boxes_and_labels_on_image_array(
  65. cropped_frame,
  66. squeezed_boxes,
  67. np.squeeze(classes).astype(np.int32),
  68. squeezed_scores,
  69. category_index,
  70. use_normalized_coordinates=True,
  71. line_thickness=4,
  72. min_score_thresh=.1)
  73. # cv2.rectangle(full_frame, (800, 100), (1250, 550), (255,0,0), 2)
  74. return objects, cropped_frame
  75. def main():
  76. # capture a single frame and check the frame shape so the correct array
  77. # size can be allocated in memory
  78. video = cv2.VideoCapture(RTSP_URL)
  79. ret, frame = video.read()
  80. if ret:
  81. frame_shape = frame.shape
  82. else:
  83. print("Unable to capture video stream")
  84. exit(1)
  85. video.release()
  86. # create shared value for storing the time the frame was captured
  87. # note: this must be a double even though the value you are storing
  88. # is a float. otherwise it stops updating the value in shared
  89. # memory. probably something to do with the size of the memory block
  90. shared_frame_time = mp.Value('d', 0.0)
  91. # compute the flattened array length from the array shape
  92. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  93. # create shared array for storing the full frame image data
  94. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  95. # create shared array for storing the cropped frame image data
  96. # TODO: make dynamic
  97. shared_cropped_arr = mp.Array(ctypes.c_uint16, 300*300*3)
  98. # create shared array for passing the image data from detect_objects to flask
  99. shared_output_arr = mp.Array(ctypes.c_uint16, 300*300*3)#flat_array_length)
  100. # create a numpy array with the image shape from the shared memory array
  101. # this is used by flask to output an mjpeg stream
  102. frame_output_arr = tonumpyarray(shared_output_arr).reshape(300,300,3)
  103. capture_process = mp.Process(target=fetch_frames, args=(shared_arr, shared_cropped_arr, shared_frame_time, frame_shape))
  104. capture_process.daemon = True
  105. detection_process = mp.Process(target=process_frames, args=(shared_arr, shared_cropped_arr, shared_output_arr, shared_frame_time, frame_shape))
  106. detection_process.daemon = True
  107. capture_process.start()
  108. print("capture_process pid ", capture_process.pid)
  109. detection_process.start()
  110. print("detection_process pid ", detection_process.pid)
  111. app = Flask(__name__)
  112. @app.route('/')
  113. def index():
  114. # return a multipart response
  115. return Response(imagestream(),
  116. mimetype='multipart/x-mixed-replace; boundary=frame')
  117. def imagestream():
  118. while True:
  119. # max out at 5 FPS
  120. time.sleep(0.2)
  121. # convert back to BGR
  122. # frame_bgr = cv2.cvtColor(frame_output_arr, cv2.COLOR_RGB2BGR)
  123. # encode the image into a jpg
  124. ret, jpg = cv2.imencode('.jpg', frame_output_arr)
  125. yield (b'--frame\r\n'
  126. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  127. app.run(host='0.0.0.0', debug=False)
  128. capture_process.join()
  129. detection_process.join()
  130. # convert shared memory array into numpy array
  131. def tonumpyarray(mp_arr):
  132. return np.frombuffer(mp_arr.get_obj(), dtype=np.uint16)
  133. # fetch the frames as fast a possible, only decoding the frames when the
  134. # detection_process has consumed the current frame
  135. def fetch_frames(shared_arr, shared_cropped_arr, shared_frame_time, frame_shape):
  136. # convert shared memory array into numpy and shape into image array
  137. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  138. cropped_frame = tonumpyarray(shared_cropped_arr).reshape(300,300,3)
  139. # start the video capture
  140. video = cv2.VideoCapture(RTSP_URL)
  141. # keep the buffer small so we minimize old data
  142. video.set(cv2.CAP_PROP_BUFFERSIZE,1)
  143. while True:
  144. # grab the frame, but dont decode it yet
  145. ret = video.grab()
  146. # snapshot the time the frame was grabbed
  147. frame_time = datetime.datetime.now()
  148. if ret:
  149. # if the detection_process is ready for the next frame decode it
  150. # otherwise skip this frame and move onto the next one
  151. if shared_frame_time.value == 0.0:
  152. # go ahead and decode the current frame
  153. ret, frame = video.retrieve()
  154. if ret:
  155. # copy the frame into the numpy array
  156. # Position 1
  157. # cropped_frame[:] = frame[270:720, 550:1000]
  158. # Position 2
  159. # frame_cropped = frame[270:720, 100:550]
  160. # Car
  161. cropped_frame[:] = frame[200:500, 1300:1600]
  162. arr[:] = frame
  163. # signal to the detection_process by setting the shared_frame_time
  164. shared_frame_time.value = frame_time.timestamp()
  165. video.release()
  166. # do the actual object detection
  167. def process_frames(shared_arr, shared_cropped_arr, shared_output_arr, shared_frame_time, frame_shape):
  168. # shape shared input array into frame for processing
  169. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  170. shared_cropped_frame = tonumpyarray(shared_cropped_arr).reshape(300,300,3)
  171. # shape shared output array into frame so it can be copied into
  172. output_arr = tonumpyarray(shared_output_arr).reshape(300,300,3)
  173. # Load a (frozen) Tensorflow model into memory before the processing loop
  174. detection_graph = tf.Graph()
  175. with detection_graph.as_default():
  176. od_graph_def = tf.GraphDef()
  177. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  178. serialized_graph = fid.read()
  179. od_graph_def.ParseFromString(serialized_graph)
  180. tf.import_graph_def(od_graph_def, name='')
  181. sess = tf.Session(graph=detection_graph)
  182. no_frames_available = -1
  183. while True:
  184. # if there isnt a frame ready for processing
  185. if shared_frame_time.value == 0.0:
  186. # save the first time there were no frames available
  187. if no_frames_available == -1:
  188. no_frames_available = datetime.datetime.now().timestamp()
  189. # if there havent been any frames available in 30 seconds,
  190. # sleep to avoid using so much cpu if the camera feed is down
  191. if no_frames_available > 0 and (datetime.datetime.now().timestamp() - no_frames_available) > 30:
  192. time.sleep(1)
  193. print("sleeping because no frames have been available in a while")
  194. else:
  195. # rest a little bit to avoid maxing out the CPU
  196. time.sleep(0.01)
  197. continue
  198. # we got a valid frame, so reset the timer
  199. no_frames_available = -1
  200. # if the frame is more than 0.5 second old, discard it
  201. if (datetime.datetime.now().timestamp() - shared_frame_time.value) > 0.5:
  202. # signal that we need a new frame
  203. shared_frame_time.value = 0.0
  204. # rest a little bit to avoid maxing out the CPU
  205. time.sleep(0.01)
  206. continue
  207. # make a copy of the frame
  208. frame = arr.copy()
  209. cropped_frame = shared_cropped_frame.copy()
  210. frame_time = shared_frame_time.value
  211. # signal that the frame has been used so a new one will be ready
  212. shared_frame_time.value = 0.0
  213. # convert to RGB
  214. cropped_frame_rgb = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2RGB)
  215. # do the object detection
  216. objects, frame_overlay = detect_objects(cropped_frame_rgb, frame, sess, detection_graph)
  217. # copy the output frame with the bounding boxes to the output array
  218. output_arr[:] = frame_overlay
  219. if(len(objects) > 0):
  220. print(objects)
  221. if __name__ == '__main__':
  222. mp.freeze_support()
  223. main()