Как получить процент предсказания объектов по классу обнаружения объектов Tensorflow - PullRequest
0 голосов
/ 04 марта 2020

Я начинаю изучать TensorFlow. Я ссылаюсь на исследовательские модели обнаружения объектов TensorFlow и выполняю их. он работает и отображает изображение с обнаружением возражений в области angular. Мне нужен процент предсказания класса в изображениях. Значит, человек - несколько%, птицы - несколько%, воздушный змей - несколько% и т.д. Как я могу получить прогноз в процентах

def run_inference_for_single_image(model, image):
  image = np.asarray(image)
  # The input needs to be a tensor, convert it using `tf.convert_to_tensor`.
  input_tensor = tf.convert_to_tensor(image)
  # The model expects a batch of images, so add an axis with `tf.newaxis`.
  input_tensor = input_tensor[tf.newaxis,...]

  # Run inference
  output_dict = model(input_tensor)


  num_detections = int(output_dict.pop('num_detections'))

  output_dict = {key:value[0, :num_detections].numpy() 
                 for key,value in output_dict.items()}
  output_dict['num_detections'] = num_detections

  # detection_classes should be ints.
  output_dict['detection_classes'] = output_dict['detection_classes'].astype(np.int64)


  # Handle models with masks:
  if 'detection_masks' in output_dict:
    # Reframe the the bbox mask to the image size.
    detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
              output_dict['detection_masks'], output_dict['detection_boxes'],
               image.shape[0], image.shape[1])      
    detection_masks_reframed = tf.cast(detection_masks_reframed > 0.5,
                                       tf.uint8)
    output_dict['detection_masks_reframed'] = detection_masks_reframed.numpy()

  return output_dict


def show_inference(model, image_path):
  image_np = np.array(Image.open(image_path))
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  print("---------------------------------------------------------------------------------------")

  print("---------------------------------------------------------------------------------------")

  # Visualization of the results of a detection.
  vis_util.visualize_boxes_and_labels_on_image_array(
      image_np,
      output_dict['detection_boxes'],
      output_dict['detection_classes'],
      output_dict['detection_scores'],
      category_index,
      instance_masks=output_dict.get('detection_masks_reframed', None),
      use_normalized_coordinates=True,
      line_thickness=8)

  display(Image.fromarray(image_np))

for image_path in TEST_IMAGE_PATHS:
  show_inference(detection_model, image_path

1 Ответ

1 голос
/ 04 марта 2020

Вы пытались посмотреть на output_dict['detection_scores']?

Так что это только процент от обнаруженного класса, а не все, поэтому то, что вы хотите, не выходит из коробки. Я вижу два варианта: либо вы пытаетесь найти имя tf.Operation на графике тензорного потока, который делает то, что вам нужно, и пытаетесь вывести его вместе с другими выходными данными (сложным, но быстрым способом), либо просто запускаете свои ящики через снова магистраль классификатора (например, если магистралью CNN является VGG16, пропустите его через VGG 16) (простой, но медленный путь).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...