终极解决方案:在Mac上轻松制作Windows启动盘,免费且专业
2026/7/16 19:19:49
博主提供docker开发镜像(主要面向深度学习、计算机视觉和机器人开发等需要 GPU 支持的场景)用于测试所有博客用例代码,下载地址(ubuntu24_cux_dev)[https://wilson.blog.csdn.net/article/details/156309082]
以下是一个基于pycocotools开发的 Python 函数,支持对bbox(边界框)、segment(分割掩码)、pose(关键点)分别提供激活参数的可视化方案。该函数通过动态过滤标注类型实现灵活控制:
importmatplotlib.pyplotaspltfrompycocotools.cocoimportCOCOimportnumpyasnpdefvisualize_coco_annotations(ann_file,img_dir,img_id=None,show_bbox=True,show_segment=True,show_pose=True,figsize=(12,8)):""" 可视化 COCO 格式标注,支持按需激活 bbox/segment/pose 参数: ann_file (str): COCO 标注文件路径 (.json) img_dir (str): 对应图像目录路径 img_id (int, optional): 指定图像ID,None 表示随机选择 show_bbox/show_segment/show_pose (bool): 是否显示对应元素 figsize (tuple): 图像显示尺寸 """# 初始化 COCO APIcoco=COCO(ann_file)# 获取图像列表img_ids=coco.getImgIds()target_id=img_idifimg_idisnotNoneelsenp.random.choice(img_ids)img_info=coco.loadImgs(target_id)[0]# 加载对应图像img_path=f"{img_dir}/{img_info['file_name']}"img=plt.imread(img_path)# 获取当前图像所有标注ann_ids=coco.getAnnIds(imgIds=target_id)anns=coco.loadAnns(ann_ids)# 创建可视化画布plt.figure(figsize=figsize)ax=plt.gca()ax.imshow(img)ax.axis("off")# 按类型过滤并绘制标注filtered_anns=[]# 处理 bboxifshow_bbox:bbox_anns=[annforanninannsif'bbox'inann]filtered_anns.extend(bbox_anns)# 处理 segmentifshow_segment:seg_anns=[annforanninannsif'segmentation'inann]filtered_anns.extend(seg_anns)# 处理 poseifshow_pose:pose_anns=[annforanninannsif'keypoints'inann]filtered_anns.extend(pose_anns)# 绘制过滤后的标注coco.showAnns(filtered_anns)plt.title(f"Image ID:{target_id}")plt.show()# 使用示例visualize_coco_annotations(ann_file="path/to/annotations.json",img_dir="path/to/images",show_bbox=True,show_segment=True,show_pose=False# 仅关闭关键点显示)动态参数控制:
show_bbox/show_segment/show_pose布尔参数精确控制三类标注的显示智能标注过滤:
bbox字段segmentation字段(支持 RLE/多边形格式)keypoints字段图像加载优化:
img_id时)可视化增强:
自定义样式控制:
# 在 showAnns 前添加样式参数coco.showAnns(filtered_anns,box_color=(255,0,0),# bbox 颜色segment_color=(0,255,0),# segment 颜色keypoint_color=(0,0,255))# pose 颜色批量处理模式:
# 遍历指定图像ID列表forimg_idintarget_ids:visualize_coco_annotations(...,img_id=img_id)结果保存:
plt.savefig(f"visualize_{target_id}.jpg",bbox_inches='tight')show_segment无效)plt.close()及时释放资源该函数完整实现了参数化控制三类标注的可视化需求,可直接集成到数据验证、模型调试等流程中,通过灵活参数配置适应不同场景的可视化需求。