Advertisement
Guest User

Untitled

a guest
Nov 22nd, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.44 KB | None | 0 0
  1. def run_inference_for_single_image(image, graph):
  2.   with graph.as_default():
  3.     with tf.Session() as sess:
  4.       ops = tf.get_default_graph().get_operations()
  5.       all_tensor_names = {output.name for op in ops for output in op.outputs}
  6.       tensor_dict = {}
  7.       for key in [
  8.           'num_detections', 'detection_boxes', 'detection_scores',
  9.           'detection_classes', 'detection_masks'
  10.       ]:
  11.         tensor_name = key + ':0'
  12.         if tensor_name in all_tensor_names:
  13.           tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
  14.               tensor_name)
  15.       if 'detection_masks' in tensor_dict:
  16.         detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])
  17.         detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])
  18.         real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)
  19.         detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])
  20.         detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])
  21.         detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
  22.             detection_masks, detection_boxes, image.shape[0], image.shape[1])
  23.         detection_masks_reframed = tf.cast(
  24.             tf.greater(detection_masks_reframed, 0.5), tf.uint8)
  25.         tensor_dict['detection_masks'] = tf.expand_dims(
  26.             detection_masks_reframed, 0)
  27.       image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
  28.  
  29.       # Запуск поиска объектов
  30.       output_dict = sess.run(tensor_dict,
  31.                              feed_dict={image_tensor: np.expand_dims(image, 0)})
  32.  
  33.       # Преобразование выходных данных из массивов float32 в нужный формат
  34.       output_dict['num_detections'] = int(output_dict['num_detections'][0])
  35.       output_dict['detection_classes'] = output_dict[
  36.           'detection_classes'][0].astype(np.uint8)
  37.       output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
  38.       output_dict['detection_scores'] = output_dict['detection_scores'][0]
  39.       if 'detection_masks' in output_dict:
  40.         output_dict['detection_masks'] = output_dict['detection_masks'][0]
  41.  
  42.       test = output_dict.copy()
  43.       for i, v in enumerate(output_dict['detection_classes']):
  44.         if v != 1:
  45.           test['detection_boxes'][i] = np.zeros((4))
  46.           test['detection_scores'][i] = 0
  47.  
  48.  
  49.   return test
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement