detect_objects.py 10 KB

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