detect_objects.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import os
  2. import cv2
  3. import imutils
  4. import time
  5. import datetime
  6. import ctypes
  7. import logging
  8. import multiprocessing as mp
  9. import threading
  10. from contextlib import closing
  11. import numpy as np
  12. import tensorflow as tf
  13. from object_detection.utils import label_map_util
  14. from object_detection.utils import visualization_utils as vis_util
  15. from flask import Flask, Response, make_response
  16. RTSP_URL = os.getenv('RTSP_URL')
  17. # Path to frozen detection graph. This is the actual model that is used for the object detection.
  18. PATH_TO_CKPT = '/frozen_inference_graph.pb'
  19. # List of the strings that is used to add correct label for each box.
  20. PATH_TO_LABELS = '/label_map.pbtext'
  21. # TODO: make dynamic?
  22. NUM_CLASSES = 90
  23. REGIONS = "350,0,300:400,350,250:400,750,250"
  24. #REGIONS = os.getenv('REGIONS')
  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. # Parse selected regions
  86. regions = []
  87. for region_string in REGIONS.split(':'):
  88. region_parts = region_string.split(',')
  89. regions.append({
  90. 'size': int(region_parts[0]),
  91. 'x_offset': int(region_parts[1]),
  92. 'y_offset': int(region_parts[2])
  93. })
  94. # capture a single frame and check the frame shape so the correct array
  95. # size can be allocated in memory
  96. video = cv2.VideoCapture(RTSP_URL)
  97. ret, frame = video.read()
  98. if ret:
  99. frame_shape = frame.shape
  100. else:
  101. print("Unable to capture video stream")
  102. exit(1)
  103. video.release()
  104. shared_memory_objects = []
  105. for region in regions:
  106. shared_memory_objects.append({
  107. # create shared value for storing the time the frame was captured
  108. 'frame_time': mp.Value('d', 0.0),
  109. # shared value for signaling to the capture process that we are ready for the next frame
  110. # (1 for ready 0 for not ready)
  111. 'ready_for_frame': mp.Value('i', 1),
  112. # shared value for motion detection signal (1 for motion 0 for no motion)
  113. 'motion_detected': mp.Value('i', 0),
  114. # create shared array for storing 10 detected objects
  115. # note: this must be a double even though the value you are storing
  116. # is a float. otherwise it stops updating the value in shared
  117. # memory. probably something to do with the size of the memory block
  118. 'output_array': mp.Array(ctypes.c_double, 6*10)
  119. })
  120. # compute the flattened array length from the array shape
  121. flat_array_length = frame_shape[0] * frame_shape[1] * frame_shape[2]
  122. # create shared array for storing the full frame image data
  123. shared_arr = mp.Array(ctypes.c_uint16, flat_array_length)
  124. # shape current frame so it can be treated as an image
  125. frame_arr = tonumpyarray(shared_arr).reshape(frame_shape)
  126. capture_process = mp.Process(target=fetch_frames, args=(shared_arr, [obj['frame_time'] for obj in shared_memory_objects], frame_shape))
  127. capture_process.daemon = True
  128. detection_processes = []
  129. for index, region in enumerate(regions):
  130. detection_process = mp.Process(target=process_frames, args=(shared_arr,
  131. shared_memory_objects[index]['output_array'],
  132. shared_memory_objects[index]['frame_time'],
  133. shared_memory_objects[index]['motion_detected'],
  134. frame_shape,
  135. region['size'], region['x_offset'], region['y_offset']))
  136. detection_process.daemon = True
  137. detection_processes.append(detection_process)
  138. motion_processes = []
  139. for index, region in enumerate(regions):
  140. motion_process = mp.Process(target=detect_motion, args=(shared_arr,
  141. shared_memory_objects[index]['frame_time'],
  142. shared_memory_objects[index]['motion_detected'],
  143. frame_shape,
  144. region['size'], region['x_offset'], region['y_offset']))
  145. motion_process.daemon = True
  146. motion_processes.append(motion_process)
  147. object_parser = ObjectParser([obj['output_array'] for obj in shared_memory_objects])
  148. object_parser.start()
  149. capture_process.start()
  150. print("capture_process pid ", capture_process.pid)
  151. for detection_process in detection_processes:
  152. detection_process.start()
  153. print("detection_process pid ", detection_process.pid)
  154. for motion_process in motion_processes:
  155. motion_process.start()
  156. print("motion_process pid ", motion_process.pid)
  157. app = Flask(__name__)
  158. @app.route('/')
  159. def index():
  160. # return a multipart response
  161. return Response(imagestream(),
  162. mimetype='multipart/x-mixed-replace; boundary=frame')
  163. def imagestream():
  164. global DETECTED_OBJECTS
  165. while True:
  166. # max out at 5 FPS
  167. time.sleep(0.2)
  168. # make a copy of the current detected objects
  169. detected_objects = DETECTED_OBJECTS.copy()
  170. # make a copy of the current frame
  171. frame = frame_arr.copy()
  172. # convert to RGB for drawing
  173. frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
  174. # draw the bounding boxes on the screen
  175. for obj in DETECTED_OBJECTS:
  176. vis_util.draw_bounding_box_on_image_array(frame,
  177. obj['ymin'],
  178. obj['xmin'],
  179. obj['ymax'],
  180. obj['xmax'],
  181. color='red',
  182. thickness=2,
  183. display_str_list=["{}: {}%".format(obj['name'],int(obj['score']*100))],
  184. use_normalized_coordinates=False)
  185. for region in regions:
  186. cv2.rectangle(frame, (region['x_offset'], region['y_offset']),
  187. (region['x_offset']+region['size'], region['y_offset']+region['size']),
  188. (255,255,255), 2)
  189. # convert back to BGR
  190. frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
  191. # encode the image into a jpg
  192. ret, jpg = cv2.imencode('.jpg', frame)
  193. yield (b'--frame\r\n'
  194. b'Content-Type: image/jpeg\r\n\r\n' + jpg.tobytes() + b'\r\n\r\n')
  195. app.run(host='0.0.0.0', debug=False)
  196. capture_process.join()
  197. for detection_process in detection_processes:
  198. detection_process.join()
  199. for motion_process in motion_processes:
  200. motion_process.join()
  201. object_parser.join()
  202. # convert shared memory array into numpy array
  203. def tonumpyarray(mp_arr):
  204. return np.frombuffer(mp_arr.get_obj(), dtype=np.uint16)
  205. # fetch the frames as fast a possible, only decoding the frames when the
  206. # detection_process has consumed the current frame
  207. def fetch_frames(shared_arr, shared_frame_times, frame_shape):
  208. # convert shared memory array into numpy and shape into image array
  209. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  210. # start the video capture
  211. video = cv2.VideoCapture(RTSP_URL)
  212. # keep the buffer small so we minimize old data
  213. video.set(cv2.CAP_PROP_BUFFERSIZE,1)
  214. while True:
  215. # grab the frame, but dont decode it yet
  216. ret = video.grab()
  217. # snapshot the time the frame was grabbed
  218. frame_time = datetime.datetime.now()
  219. if ret:
  220. # if the detection_process is ready for the next frame decode it
  221. # otherwise skip this frame and move onto the next one
  222. if all(shared_frame_time.value == 0.0 for shared_frame_time in shared_frame_times):
  223. # go ahead and decode the current frame
  224. ret, frame = video.retrieve()
  225. if ret:
  226. arr[:] = frame
  227. # signal to the detection_processes by setting the shared_frame_time
  228. for shared_frame_time in shared_frame_times:
  229. shared_frame_time.value = frame_time.timestamp()
  230. else:
  231. # sleep a little to reduce CPU usage
  232. time.sleep(0.01)
  233. video.release()
  234. # do the actual object detection
  235. def process_frames(shared_arr, shared_output_arr, shared_frame_time, shared_motion, frame_shape, region_size, region_x_offset, region_y_offset):
  236. # shape shared input array into frame for processing
  237. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  238. # Load a (frozen) Tensorflow model into memory before the processing loop
  239. detection_graph = tf.Graph()
  240. with detection_graph.as_default():
  241. od_graph_def = tf.GraphDef()
  242. with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
  243. serialized_graph = fid.read()
  244. od_graph_def.ParseFromString(serialized_graph)
  245. tf.import_graph_def(od_graph_def, name='')
  246. sess = tf.Session(graph=detection_graph)
  247. no_frames_available = -1
  248. frame_time = 0.0
  249. while True:
  250. now = datetime.datetime.now().timestamp()
  251. # if there is no motion detected
  252. if shared_motion.value == 0:
  253. time.sleep(0.01)
  254. continue
  255. # if there isnt a new frame ready for processing
  256. if shared_frame_time.value == frame_time:
  257. # save the first time there were no frames available
  258. if no_frames_available == -1:
  259. no_frames_available = now
  260. # if there havent been any frames available in 30 seconds,
  261. # sleep to avoid using so much cpu if the camera feed is down
  262. if no_frames_available > 0 and (now - no_frames_available) > 30:
  263. time.sleep(1)
  264. print("sleeping because no frames have been available in a while")
  265. else:
  266. # rest a little bit to avoid maxing out the CPU
  267. time.sleep(0.01)
  268. continue
  269. # we got a valid frame, so reset the timer
  270. no_frames_available = -1
  271. # if the frame is more than 0.5 second old, ignore it
  272. if (now - shared_frame_time.value) > 0.5:
  273. # rest a little bit to avoid maxing out the CPU
  274. time.sleep(0.01)
  275. continue
  276. # make a copy of the cropped frame
  277. cropped_frame = arr[region_y_offset:region_y_offset+region_size, region_x_offset:region_x_offset+region_size].copy()
  278. frame_time = shared_frame_time.value
  279. # convert to RGB
  280. cropped_frame_rgb = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2RGB)
  281. # do the object detection
  282. objects = detect_objects(cropped_frame_rgb, sess, detection_graph, region_size, region_x_offset, region_y_offset)
  283. # copy the detected objects to the output array, filling the array when needed
  284. shared_output_arr[:] = objects + [0.0] * (60-len(objects))
  285. # do the actual object detection
  286. def detect_motion(shared_arr, shared_frame_time, shared_motion, frame_shape, region_size, region_x_offset, region_y_offset):
  287. # shape shared input array into frame for processing
  288. arr = tonumpyarray(shared_arr).reshape(frame_shape)
  289. no_frames_available = -1
  290. avg_frame = None
  291. last_motion = -1
  292. while True:
  293. now = datetime.datetime.now().timestamp()
  294. # if it has been 30 seconds since the last motion, clear the flag
  295. if last_motion > 0 and (now - last_motion) > 30:
  296. last_motion = -1
  297. shared_motion.value = 0
  298. print("motion cleared")
  299. # if there isnt a frame ready for processing
  300. if shared_frame_time.value == 0.0:
  301. # save the first time there were no frames available
  302. if no_frames_available == -1:
  303. no_frames_available = now
  304. # if there havent been any frames available in 30 seconds,
  305. # sleep to avoid using so much cpu if the camera feed is down
  306. if no_frames_available > 0 and (now - no_frames_available) > 30:
  307. time.sleep(1)
  308. print("sleeping because no frames have been available in a while")
  309. else:
  310. # rest a little bit to avoid maxing out the CPU
  311. time.sleep(0.01)
  312. continue
  313. # we got a valid frame, so reset the timer
  314. no_frames_available = -1
  315. # if the frame is more than 0.5 second old, discard it
  316. if (now - shared_frame_time.value) > 0.5:
  317. # signal that we need a new frame
  318. shared_frame_time.value = 0.0
  319. # rest a little bit to avoid maxing out the CPU
  320. time.sleep(0.01)
  321. continue
  322. # make a copy of the cropped frame
  323. cropped_frame = arr[region_y_offset:region_y_offset+region_size, region_x_offset:region_x_offset+region_size].copy()
  324. frame_time = shared_frame_time.value
  325. # signal that the frame has been used so a new one will be ready
  326. shared_frame_time.value = 0.0
  327. # convert to grayscale
  328. gray = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2GRAY)
  329. # convert to uint8
  330. gray = (gray/256).astype('uint8')
  331. # apply gaussian blur
  332. gray = cv2.GaussianBlur(gray, (21, 21), 0)
  333. if avg_frame is None:
  334. avg_frame = gray.copy().astype("float")
  335. continue
  336. # look at the delta from the avg_frame
  337. cv2.accumulateWeighted(gray, avg_frame, 0.5)
  338. frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg_frame))
  339. thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
  340. # dilate the thresholded image to fill in holes, then find contours
  341. # on thresholded image
  342. thresh = cv2.dilate(thresh, None, iterations=2)
  343. cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
  344. cv2.CHAIN_APPROX_SIMPLE)
  345. cnts = imutils.grab_contours(cnts)
  346. # loop over the contours
  347. for c in cnts:
  348. # if the contour is too small, ignore it
  349. if cv2.contourArea(c) < 50:
  350. continue
  351. print("motion_detected")
  352. last_motion = now
  353. shared_motion.value = 1
  354. # compute the bounding box for the contour, draw it on the frame,
  355. # and update the text
  356. (x, y, w, h) = cv2.boundingRect(c)
  357. cv2.rectangle(cropped_frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
  358. cv2.imwrite("motion%d.png" % frame_time, cropped_frame)
  359. if __name__ == '__main__':
  360. mp.freeze_support()
  361. main()