如何在单类别目标检测结果图像上显示目标数量?
问题描述
我是编程新手,正在Google Colab中学习目标检测算法教程,使用TensorFlow Object Detection API的示例代码,该代码采用Single Shot Detector输出检测图像。我已添加全局变量count和循环,统计置信度大于0.5的目标数量,在单类别检测场景下可正常工作,且已验证统计结果正确。现在希望将该数量显示在检测图像上,例如添加一行文字Number of people: {count value},请指导修改下方代码实现该功能:
def show_inference(model, image_path): global count count=0 # 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) display(Image.fromarray(image_np)) for o in output_dict['detection_scores']: if o > 0.5: count=count+1 print(count) for image_path in TEST_IMAGE_PATHS: show_inference(detection_model, image_path)
解决方案
要在图像上绘制统计数量,我们可以借助PIL的ImageDraw模块实现,同时调整代码执行顺序(先统计数量再绘制并显示图像),具体修改如下:
步骤1:导入必要模块
在代码开头添加PIL绘图相关模块:
from PIL import ImageDraw, ImageFont
步骤2:修改show_inference函数
调整统计逻辑位置,并添加文字绘制代码:
def show_inference(model, image_path): global count count = 0 # 读取图像并转为数组 image_np = np.array(Image.open(image_path)) # 执行检测 output_dict = run_inference_for_single_image(model, image_np) # 统计置信度>0.5的目标数量 for score in output_dict['detection_scores']: if score > 0.5: count += 1 # 可视化检测框与标签 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) # 将数组转回PIL图像,准备绘制文字 img = Image.fromarray(image_np) draw = ImageDraw.Draw(img) # 设置字体(Colab中兼容默认字体,异常时 fallback 到默认) try: font = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 40) except: font = ImageFont.load_default(size=40) # 绘制文字,位置为左上角,可根据需求调整坐标 text = f"Number of people: {count}" draw.text((20, 20), text, fill=(255, 0, 0), font=font) # 显示最终图像 display(img) print(count) for image_path in TEST_IMAGE_PATHS: show_inference(detection_model, image_path)
修改说明
- 顺序调整:把统计
count的循环移到可视化之后、图像显示之前,确保绘制文字时已得到正确统计值 - 绘图逻辑:将
image_np转回PIL图像对象,用ImageDraw绘制文字,指定字体大小、颜色和位置 - 字体兼容:加入异常处理,避免Colab中找不到指定字体时出错,自动使用默认字体
- 位置可调:文字默认绘制在左上角(20,20),可根据图像大小修改坐标值,优化显示位置
内容的提问来源于stack exchange,提问作者CKT
相关产品推荐
相关产品推荐

