You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在目标检测推理代码中添加已检测图像总数统计功能?

实现已检测图像总数统计的方法

要在保留原有可视化输出的基础上添加图像总数统计,只需在循环外初始化计数器,每次处理完单张图像后递增计数,最后在循环结束后输出统计结果即可。以下是修改后的完整代码:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')

def load_image_into_numpy_array(path):
    return np.array(Image.open(path))

# 初始化图像检测计数器
total_images = 0

for image_path in img:
    print('Running inference for {}... '.format(image_path), end='')
    image_np=load_image_into_numpy_array(image_path)
    input_tensor=tf.convert_to_tensor(image_np)
    input_tensor=input_tensor[tf.newaxis, ...]
    detections=detect_fn(input_tensor)
    num_detections=int(detections.pop('num_detections'))
    detections={key:value[0,:num_detections].numpy()
               for key,value in detections.items()}
    detections['num_detections']=num_detections

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

    image_np_with_detections=image_np.copy()

    viz_utils.visualize_boxes_and_labels_on_image_array(
          image_np_with_detections,
          detections['detection_boxes'],
          detections['detection_classes'],
          detections['detection_scores'],
          category_index,
          use_normalized_coordinates=True,
          max_boxes_to_draw=100,     
          min_score_thresh=.3,     
          agnostic_mode=False)
    %matplotlib inline
    plt.figure(figsize=(16,16))
    plt.imshow(image_np_with_detections)
    print('Done')
    plt.show()
    
    # 每完成一张图像检测,计数器加1
    total_images += 1

# 输出最终检测图像总数
print(f"已完成检测的图像总数:{total_images}")

关键修改说明

  • 在循环启动前定义total_images = 0作为计数初始值
  • 每次循环末尾执行total_images += 1,完成单张图像的计数累加
  • 循环结束后打印最终统计结果

该修改完全保留原有可视化和输出逻辑,新增功能简洁高效。

内容的提问来源于stack exchange,提问作者MAdams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 20:40:55