使用TF Object Detection API时打印检测到的类别和分数

问题描述 投票:0回答:1

您好,我正在寻找一种方法来打印出检测到的类别和分数,同时使用object_detection_tutorial执行对象检测。这里的大多数解决方案适用于Tensorflow 1,并且不再起作用。

我在StackOverflow上找到一个Solution,但可惜它只打印出一个检测到的对象。我无法找出如何修改代码以获取图像中所有检测到的对象的分数。

这是我在这里找到的解决方案中给出的代码

def get_classes_name_and_scores(
    boxes,
    classes,
    scores,
    category_index,
    max_boxes_to_draw=20,
    min_score_thresh=.9): # returns bigger than 90% precision
display_str = {}
if not max_boxes_to_draw:
    max_boxes_to_draw = boxes.shape[0]
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
    if scores is None or scores[i] > min_score_thresh:
        if classes[i] in six.viewkeys(category_index):
            display_str['name'] = category_index[classes[i]]['name']
            display_str['score'] = '{}%'.format(int(100 * scores[i]))

return display_str

我使用此代码将其打印出来

def show_inference(model, 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 = np.array(Image.open(image_path))
  # Actual detection.
  output_dict = run_inference_for_single_image(model, image_np)
  # 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)

  # Print the Name and Score of each detected Object
  print(get_classes_name_and_scores(
    output_dict['detection_boxes'],
    output_dict['detection_classes'],
    output_dict['detection_scores'],
    category_index))

  display(Image.fromarray(image_np))
python object-detection tensorflow2.0 object-detection-api tensorflow2.x
1个回答
0
投票

每次循环时,这两行都被覆盖,因此先前的内容消失了:

display_str['name'] = category_index[classes[i]]['name']
display_str['score'] = '{}%'.format(int(100 * scores[i]))

我假设您要记录循环触发这些行的每个实例。就个人而言,为此,我将结果添加到列表中并返回:

display_str_list = []
    ### your loop code
    display_str_dict = {
        'name': category_index[classes[i]]['name'],
        'score': '{}%'.format(int(100 * scores[i])),
    }
    display_str_list.append(display_str_dict)
return display_str_list
© www.soinside.com 2019 - 2024. All rights reserved.