detect_objects.py 17 KB

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