在Tensorflow对象检测API中获取类和概率

时间:2018-11-18 18:17:20

标签: python tensorflow machine-learning object-detection

在Tensorflow对象检测API中获取类和检测到对象的概率时遇到问题。我想在每张图像上打印这两个值。

这是代码:

for image_path in TEST_IMAGE_PATHS:
  image = Image.open(image_path)
  # the array based representation of the image will be used later in order to prepare the
  # result image with boxes and labels on it.
  image_np = load_image_into_numpy_array(image)
  # Expand dimensions since the model expects images to have shape: [1, None, None, 3]
  image_np_expanded = np.expand_dims(image_np, axis=0)
  # Actual detection.
  output_dict = run_inference_for_single_image(image_np, detection_graph)
  # 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'),
      use_normalized_coordinates=True,
      line_thickness=2)
  plt.figure(figsize=IMAGE_SIZE)
  plt.imshow(image_np)

1 个答案:

答案 0 :(得分:0)

以下代码为所有得分高于50%的实体提取类ID和得分提供了可能性。

#Create indexes list of element with a score > 0.5
indexes = [k for k,v in enumerate(output_dict['detection_scores']) if (v > 0.5)]

#Number of entities
num_entities = len(indexes)

#Extract the class id
class_id = itemgetter(*indexes)(output_dict['detection_classes'])
scores = itemgetter(*indexes)(output_dict['detection_scores'])

#Convert the class id in their name
class_names = []
if num_entities == 1:
  class_names.append(category_index[class_id]['name'])
  class_name = str(class_names)
else:
  for i in range(0, len(indexes)):
  class_names.append(category_index[class_id[i]]['name'])

如果仅检测到一个元素,则为if。

然后您可以打印class_names[i]str(scores[i])