Python将COCO格式分割标签绘制到对应的图片上

  • 前言
  • 前提条件
  • 相关介绍
      • COCO 格式简介(实例分割)
      • 📁 主要目录结构:
      • 📄 JSON 标注文件结构示例:
      • ✅ 特点:
  • 实验环境
  • Python将COCO格式分割标签绘制到对应的图片上
    • 代码实现
    • 输出结果

在这里插入图片描述

前言

  • 由于本人水平有限,难免出现错漏,敬请批评改正。
  • 更多精彩内容,可点击进入Python日常小操作专栏、OpenCV-Python小应用专栏、YOLO系列专栏、自然语言处理专栏或我的个人主页查看
  • YOLOv8 Ultralytics:使用Ultralytics框架训练RT-DETR实时目标检测模型
  • 基于DETR的人脸伪装检测
  • YOLOv7训练自己的数据集(口罩检测)
  • YOLOv8训练自己的数据集(足球检测)
  • YOLOv5:TensorRT加速YOLOv5模型推理
  • YOLOv5:IoU、GIoU、DIoU、CIoU、EIoU
  • 玩转Jetson Nano(五):TensorRT加速YOLOv5目标检测
  • YOLOv5:添加SE、CBAM、CoordAtt、ECA注意力机制
  • YOLOv5:yolov5s.yaml配置文件解读、增加小目标检测层
  • Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集
  • YOLOv5:使用7.0版本训练自己的实例分割模型(车辆、行人、路标、车道线等实例分割)
  • 使用Kaggle GPU资源免费体验Stable Diffusion开源项目

前提条件

  • 熟悉Python

相关介绍

  • Python是一种跨平台的计算机程序设计语言。是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。最初被设计用于编写自动化脚本(shell),随着版本的不断更新和语言新功能的添加,越多被用于独立的、大型项目的开发。
  • PyTorch 是一个深度学习框架,封装好了很多网络和深度学习相关的工具方便我们调用,而不用我们一个个去单独写了。它分为 CPU 和 GPU 版本,其他框架还有 TensorFlow、Caffe 等。PyTorch 是由 Facebook 人工智能研究院(FAIR)基于 Torch 推出的,它是一个基于 Python 的可续计算包,提供两个高级功能:1、具有强大的 GPU 加速的张量计算(如 NumPy);2、构建深度神经网络时的自动微分机制。
  • YOLO是一种单阶段目标检测算法,它是一个在COCO数据集上预训练的物体检测架构和模型系列,代表了Ultralytics对未来视觉AI方法的开源研究,其中包含了经过数千小时的研究和开发而形成的经验教训和最佳实践。
  • Labelme是一款图像标注工具,由麻省理工(MIT)的计算机科学和人工智能实验室(CSAIL)研发。它是用Python和PyQT编写的,开源且免费。Labelme支持Windows、Linux和Mac等操作系统。

COCO 格式简介(实例分割)

COCO 是一种常用的目标检测与实例分割数据集格式,支持图像、标注和类别信息。


📁 主要目录结构:

coco/
├── JPEGImages/        # 存放所有图像(JPG/PNG)
└── annotations.json   # COCO 格式的标注文件(JSON)

📄 JSON 标注文件结构示例:

{"images": [{"id": 1,"file_name": "001.jpg","width": 640,"height": 480}],"annotations": [{"id": 1,"image_id": 1,"category_id": 1,           # 类别 ID(对应 class_names)"segmentation": [[x1,y1,x2,y2,...]],  # 多边形坐标点"area": 1000,               # 区域面积"bbox": [x, y, w, h],       # 边界框"iscrowd": 0}],"categories": [{"id": 1,"name": "person"}]
}

✅ 特点:

  • 支持多个对象、多边形标注
  • 图像可为 JPG 或 PNG
  • 常用于 Mask R-CNN、YOLOv8-seg 等模型训练

如需生成或转换数据集,可用脚本自动处理 YOLO 标注转 COCO。

实验环境

  • Python 3.x (面向对象的高级语言)

Python将COCO格式分割标签绘制到对应的图片上

在这里插入图片描述
实例分割标签:

{"images": [{"id": 1,"file_name": "1.png","width": 579,"height": 484}],"annotations": [{"id": 1,"image_id": 1,"category_id": 3,"segmentation": [[329.30625,330.659604,329.30625,333.37339199999997,328.401273,334.277988,328.401273,335.18258399999996,327.49687500000005,336.087664,327.49687500000005,337.896856,326.592477,338.80145200000004,326.592477,339.706048,325.6875,340.611128,325.6875,342.42032,324.782523,343.32491600000003,324.782523,345.13459200000005,323.87812499999995,346.03918799999997,323.87812499999995,346.943784,322.06875,348.752976,322.06875,349.658056,321.16435199999995,350.562652,321.16435199999995,351.46724800000004,320.259375,352.371844,320.259375,353.27644,319.354398,354.181036,319.354398,355.086116,318.45000000000005,355.99071200000003,318.45000000000005,357.799904,317.545602,358.7045,317.545602,359.609096,315.735648,361.418772,315.735648,362.323368,313.926273,364.13256,313.926273,365.942236,312.11689800000005,367.751428,309.40312500000005,367.751428,309.40312500000005,428.365652,313.021875,428.365652,313.926273,429.270248,314.83124999999995,429.270248,315.735648,430.174844,316.640625,430.174844,317.545602,429.270248,318.45000000000005,429.270248,323.87812499999995,423.842188,379.96875,423.842188,380.873727,424.746784,394.44375,424.746784,395.348148,425.65138,403.490625,425.65138,404.395023,426.55645999999996,406.204398,426.55645999999996,407.109375,427.461056,408.014352,427.461056,408.91875000000005,428.365652,409.823148,428.365652,410.728125,429.270248,411.63310199999995,429.270248,412.5375,430.174844,418.870023,430.174844,419.775,429.270248,420.67939800000005,429.270248,422.488773,427.461056,422.488773,426.55645999999996,423.39374999999995,425.65138,423.39374999999995,424.746784,424.298148,423.842188,424.298148,422.937592,425.203125,422.032996,425.203125,421.12791599999997,426.108102,420.22332,426.108102,418.414128,427.01250000000005,417.50953200000004,427.01250000000005,414.79526,427.916898,413.89066399999996,427.916898,412.986068,428.821875,412.081472,428.821875,410.271796,429.72685199999995,409.3672,429.72685199999995,406.65292800000003,430.63125,405.748332,430.63125,393.08302,429.72685199999995,392.17794000000004,429.72685199999995,388.559556,428.821875,387.654476,428.821875,383.131012,427.916898,382.226416,427.916898,379.51262799999995,427.01250000000005,378.607548,427.01250000000005,376.798356,426.108102,375.89376,426.108102,374.084568,425.203125,373.17948800000005,425.203125,372.274892,424.298148,371.370296,424.298148,370.4657,423.39374999999995,369.561104,423.39374999999995,367.751428,421.584375,365.942236,421.584375,365.03764,419.775,363.227964,419.775,362.323368,418.870023,361.418772,418.870023,360.51417599999996,416.15625,357.799904,416.15625,356.895308,415.251273,355.99071200000003,415.251273,355.086116,413.441898,353.27644,413.441898,352.371844,410.728125,349.658056,410.728125,348.752976,408.91875000000005,346.943784,408.91875000000005,346.03918799999997,405.29999999999995,342.42032,405.29999999999995,341.515724,400.776273,336.99226,399.87187500000005,336.99226,398.0625,335.18258399999996,396.25312499999995,335.18258399999996,395.348148,334.277988,394.44375,334.277988,393.53935199999995,333.37339199999997,393.53935199999995,330.659604]],"area": 10106,"bbox": [309,330,121,99],"iscrowd": 0},{"id": 2,"image_id": 1,"category_id": 3,"segmentation": [[88.65937500000001,312.565748,88.65937500000001,316.184132,87.754398,317.08921200000003,86.85,317.08921200000003,84.135648,319.803,84.135648,320.70759599999997,83.23124999999999,321.612676,83.23124999999999,322.517272,82.326273,323.421868,82.326273,324.326464,81.421875,325.23106,81.421875,326.13613999999995,80.517477,327.040736,80.517477,328.849928,79.61250000000001,329.754524,79.61250000000001,330.659604,78.707523,331.5642,78.707523,333.37339199999997,77.803125,334.277988,77.803125,336.087664,76.898148,336.99226,76.898148,337.896856,75.99375,338.80145200000004,75.99375,340.611128,75.088773,341.515724,75.088773,344.229512,74.18437499999999,345.13459200000005,74.18437499999999,346.943784,73.279398,347.84837999999996,73.279398,348.752976,72.375,349.658056,72.375,351.46724800000004,71.470602,352.371844,71.470602,354.181036,69.660648,355.99071200000003,66.946875,355.99071200000003,66.946875,409.3672,69.660648,409.3672,72.375,412.081472,72.375,412.986068,80.517477,421.12791599999997,81.421875,421.12791599999997,87.754398,427.461056,88.65937500000001,427.461056,89.564352,428.365652,96.801273,428.365652,97.70625000000001,427.461056,98.611227,427.461056,101.32499999999999,424.746784,102.229398,424.746784,104.94375,422.032996,105.848148,422.032996,106.75312500000001,421.12791599999997,128.465625,421.12791599999997,129.370602,422.032996,138.417477,422.032996,139.321875,422.937592,149.273148,422.937592,150.17812500000002,423.842188,155.60625,423.842188,156.51122700000002,424.746784,163.74814800000001,424.746784,164.653125,425.65138,169.17627299999998,425.65138,170.08125,426.55645999999996,171.890625,426.55645999999996,172.79502300000001,427.461056,173.7,427.461056,174.60497700000002,428.365652,175.50937499999998,428.365652,176.414352,429.270248,177.31875000000002,429.270248,179.128125,431.079924,180.032523,431.079924,180.9375,431.98452000000003,181.84189800000001,431.98452000000003,182.746875,432.889116,183.65185200000002,432.889116,184.55624999999998,433.79371199999997,189.079398,433.79371199999997,190.88877300000001,431.98452000000003,190.88877300000001,431.079924,191.79375,430.174844,191.79375,429.270248,192.69872700000002,428.365652,192.69872700000002,427.461056,193.60312499999998,426.55645999999996,193.60312499999998,425.65138,194.508102,424.746784,194.508102,423.842188,195.41250000000002,422.937592,195.41250000000002,422.032996,196.31689799999998,421.12791599999997,196.31689799999998,420.22332,198.126273,418.414128,198.126273,417.50953200000004,201.74560200000002,413.89066399999996,202.64999999999998,413.89066399999996,204.45937500000002,412.081472,206.26875,412.081472,207.173148,411.176392,223.45752299999998,411.176392,224.3625,410.271796,225.266898,410.271796,227.07627300000001,408.462604,227.07627300000001,407.558008,227.98125,406.65292800000003,227.98125,401.22486799999996,228.88622700000002,400.320272,228.88622700000002,383.131012,227.98125,382.226416,227.98125,379.51262799999995,227.07627300000001,378.607548,227.07627300000001,376.798356,226.171875,375.89376,226.171875,374.989164,225.266898,374.084568,225.266898,373.17948800000005,224.3625,372.274892,224.3625,370.4657,223.45752299999998,369.561104,223.45752299999998,368.656024,222.55312500000002,367.751428,222.55312500000002,366.846832,221.648148,365.942236,221.648148,364.13256,220.74374999999998,363.227964,220.74374999999998,361.418772,219.83935200000002,360.51417599999996,219.83935200000002,358.7045,218.934375,357.799904,218.934375,355.99071200000003,218.02939800000001,355.086116,218.02939800000001,353.27644,216.220023,351.46724800000004,216.220023,350.562652,215.315625,349.658056,215.315625,348.752976,214.41064799999998,347.84837999999996,214.41064799999998,346.943784,213.50625000000002,346.03918799999997,213.50625000000002,345.13459200000005,211.69687499999998,343.32491600000003,211.69687499999998,342.42032,210.79247700000002,341.515724,210.79247700000002,339.706048,209.8875,338.80145200000004,209.8875,336.99226,208.98252300000001,336.087664,208.98252300000001,334.277988,208.078125,333.37339199999997,208.078125,331.5642,207.173148,330.659604,207.173148,329.754524,199.93564800000001,322.517272,199.03125,322.517272,198.126273,321.612676,196.31689799999998,321.612676,195.41250000000002,320.70759599999997,194.508102,320.70759599999997,193.60312499999998,319.803,191.79375,319.803,190.88877300000001,318.898404,188.175,318.898404,187.27002299999998,317.993808,184.55624999999998,317.993808,183.65185200000002,317.08921200000003,180.9375,317.08921200000003,180.032523,316.184132,179.128125,316.184132,178.22314799999998,315.279536,178.22314799999998,312.565748]],"area": 15941,"bbox": [66,312,161,121],"iscrowd": 0},{"id": 3,"image_id": 1,"category_id": 3,"segmentation": [[208.078125,330.659604,208.078125,340.611128,210.79247700000002,340.611128,213.50625000000002,343.32491600000003,213.50625000000002,344.229512,216.220023,346.943784,216.220023,347.84837999999996,218.02939800000001,349.658056,218.02939800000001,350.562652,218.934375,351.46724800000004,218.934375,352.371844,219.83935200000002,353.27644,219.83935200000002,355.086116,220.74374999999998,355.99071200000003,220.74374999999998,358.7045,221.648148,359.609096,221.648148,362.323368,222.55312500000002,363.227964,222.55312500000002,364.13256,223.45752299999998,365.03764,223.45752299999998,365.942236,224.3625,366.846832,224.3625,367.751428,225.266898,368.656024,225.266898,370.4657,226.171875,371.370296,226.171875,373.17948800000005,228.88622700000002,375.89376,228.88622700000002,376.798356,229.79062499999998,377.702952,230.695602,377.702952,231.60000000000002,378.607548,234.313773,378.607548,235.21875,379.51262799999995,239.741898,379.51262799999995,240.64687500000002,378.607548,242.45625,378.607548,243.360648,377.702952,244.265625,377.702952,247.88437499999998,374.084568,247.88437499999998,373.17948800000005,248.789352,372.274892,248.789352,371.370296,249.69375000000002,370.4657,249.69375000000002,367.751428,250.59814799999998,366.846832,250.59814799999998,365.03764,249.69375000000002,364.13256,249.69375000000002,357.799904,248.789352,356.895308,248.789352,351.46724800000004,247.88437499999998,350.562652,247.88437499999998,346.03918799999997,246.97997700000002,345.13459200000005,246.97997700000002,343.32491600000003,246.075,342.42032,246.075,340.611128,245.17002300000001,339.706048,245.17002300000001,338.80145200000004,244.265625,337.896856,244.265625,336.99226,243.360648,336.087664,242.45625,336.087664,240.64687500000002,334.277988,240.64687500000002,330.659604]],"area": 1377,"bbox": [208,330,42,48],"iscrowd": 0},{"id": 4,"image_id": 1,"category_id": 8,"segmentation": [[229.79062499999998,316.184132,229.79062499999998,331.5642,236.12314800000001,331.5642,237.028125,332.468796,237.93310200000002,332.468796,238.83749999999998,333.37339199999997,239.741898,333.37339199999997,241.55127299999998,335.18258399999996,242.45625,335.18258399999996,245.17002300000001,337.896856,245.17002300000001,338.80145200000004,246.075,339.706048,246.075,341.515724,246.97997700000002,342.42032,246.97997700000002,345.13459200000005,247.88437499999998,346.03918799999997,247.88437499999998,349.658056,248.789352,350.562652,248.789352,355.99071200000003,249.69375000000002,356.895308,249.69375000000002,360.51417599999996,250.59814799999998,361.418772,250.59814799999998,364.13256,254.21689800000001,367.751428,258.740625,367.751428,259.645602,366.846832,270.501273,366.846832,271.40625,367.751428,277.739352,367.751428,278.64375,368.656024,280.453125,368.656024,281.358102,369.561104,282.2625,369.561104,283.166898,370.4657,283.166898,373.17948800000005,283.166898,369.561104,284.071875,368.656024,284.071875,367.751428,284.976852,366.846832,284.976852,333.37339199999997,284.071875,332.468796,284.071875,329.754524,283.166898,328.849928,283.166898,327.040736,282.2625,326.13613999999995,282.2625,324.326464,281.358102,323.421868,281.358102,322.517272,280.453125,321.612676,280.453125,320.70759599999997,278.64375,318.898404,278.64375,316.184132]],"area": 2148,"bbox": [229,316,55,56],"iscrowd": 0},{"id": 5,"image_id": 1,"category_id": 3,"segmentation": [[310.307523,334.277988,310.307523,337.896856,308.498727,339.706048,308.498727,340.611128,306.688773,342.42032,306.688773,344.229512,304.879398,346.03918799999997,302.165625,346.03918799999997,302.165625,359.609096,305.78437499999995,359.609096,306.688773,360.51417599999996,310.307523,360.51417599999996,311.2125,361.418772,314.83124999999995,361.418772,315.735648,360.51417599999996,316.640625,360.51417599999996,317.545602,359.609096,317.545602,358.7045,318.45000000000005,357.799904,318.45000000000005,356.895308,319.354398,355.99071200000003,319.354398,355.086116,320.259375,354.181036,320.259375,352.371844,321.16435199999995,351.46724800000004,321.16435199999995,350.562652,322.06875,349.658056,322.06875,348.752976,322.973148,347.84837999999996,322.973148,346.943784,323.87812499999995,346.03918799999997,323.87812499999995,345.13459200000005,324.782523,344.229512,324.782523,343.32491600000003,325.6875,342.42032,325.6875,341.515724,327.49687500000005,339.706048,330.21064800000005,339.706048,330.21064800000005,334.277988]],"area": 488,"bbox": [302,334,28,27],"iscrowd": 0},{"id": 6,"image_id": 1,"category_id": 3,"segmentation": [[284.071875,330.659604,284.071875,351.46724800000004,293.11875,351.46724800000004,293.11875,348.752976,294.02314800000005,347.84837999999996,296.73749999999995,347.84837999999996,297.641898,346.943784,302.165625,346.943784,305.78437499999995,343.32491600000003,308.498727,343.32491600000003,308.498727,334.277988,305.78437499999995,334.277988,304.879398,333.37339199999997,304.879398,330.659604]],"area": 413,"bbox": [284,330,24,20],"iscrowd": 0}],"categories": [{"id": 1,"name": "person","supercategory": "none"},{"id": 2,"name": "bicycle","supercategory": "none"},{"id": 3,"name": "car","supercategory": "none"},{"id": 4,"name": "motorcycle","supercategory": "none"},{"id": 5,"name": "airplane","supercategory": "none"},{"id": 6,"name": "bus","supercategory": "none"},{"id": 7,"name": "train","supercategory": "none"},{"id": 8,"name": "truck","supercategory": "none"},{"id": 9,"name": "boat","supercategory": "none"},{"id": 10,"name": "traffic light","supercategory": "none"},{"id": 11,"name": "fire hydrant","supercategory": "none"},{"id": 12,"name": "stop sign","supercategory": "none"},{"id": 13,"name": "parking meter","supercategory": "none"},{"id": 14,"name": "bench","supercategory": "none"},{"id": 15,"name": "bird","supercategory": "none"},{"id": 16,"name": "cat","supercategory": "none"},{"id": 17,"name": "dog","supercategory": "none"},{"id": 18,"name": "horse","supercategory": "none"},{"id": 19,"name": "sheep","supercategory": "none"},{"id": 20,"name": "cow","supercategory": "none"},{"id": 21,"name": "elephant","supercategory": "none"},{"id": 22,"name": "bear","supercategory": "none"},{"id": 23,"name": "zebra","supercategory": "none"},{"id": 24,"name": "giraffe","supercategory": "none"},{"id": 25,"name": "backpack","supercategory": "none"},{"id": 26,"name": "umbrella","supercategory": "none"},{"id": 27,"name": "handbag","supercategory": "none"},{"id": 28,"name": "tie","supercategory": "none"},{"id": 29,"name": "suitcase","supercategory": "none"},{"id": 30,"name": "frisbee","supercategory": "none"},{"id": 31,"name": "skis","supercategory": "none"},{"id": 32,"name": "snowboard","supercategory": "none"},{"id": 33,"name": "sports ball","supercategory": "none"},{"id": 34,"name": "kite","supercategory": "none"},{"id": 35,"name": "baseball bat","supercategory": "none"},{"id": 36,"name": "baseball glove","supercategory": "none"},{"id": 37,"name": "skateboard","supercategory": "none"},{"id": 38,"name": "surfboard","supercategory": "none"},{"id": 39,"name": "tennis racket","supercategory": "none"},{"id": 40,"name": "bottle","supercategory": "none"},{"id": 41,"name": "wine glass","supercategory": "none"},{"id": 42,"name": "cup","supercategory": "none"},{"id": 43,"name": "fork","supercategory": "none"},{"id": 44,"name": "knife","supercategory": "none"},{"id": 45,"name": "spoon","supercategory": "none"},{"id": 46,"name": "bowl","supercategory": "none"},{"id": 47,"name": "banana","supercategory": "none"},{"id": 48,"name": "apple","supercategory": "none"},{"id": 49,"name": "sandwich","supercategory": "none"},{"id": 50,"name": "orange","supercategory": "none"},{"id": 51,"name": "broccoli","supercategory": "none"},{"id": 52,"name": "carrot","supercategory": "none"},{"id": 53,"name": "hot dog","supercategory": "none"},{"id": 54,"name": "pizza","supercategory": "none"},{"id": 55,"name": "donut","supercategory": "none"},{"id": 56,"name": "cake","supercategory": "none"},{"id": 57,"name": "chair","supercategory": "none"},{"id": 58,"name": "couch","supercategory": "none"},{"id": 59,"name": "potted plant","supercategory": "none"},{"id": 60,"name": "bed","supercategory": "none"},{"id": 61,"name": "dining table","supercategory": "none"},{"id": 62,"name": "toilet","supercategory": "none"},{"id": 63,"name": "tv","supercategory": "none"},{"id": 64,"name": "laptop","supercategory": "none"},{"id": 65,"name": "mouse","supercategory": "none"},{"id": 66,"name": "remote","supercategory": "none"},{"id": 67,"name": "keyboard","supercategory": "none"},{"id": 68,"name": "cell phone","supercategory": "none"},{"id": 69,"name": "microwave","supercategory": "none"},{"id": 70,"name": "oven","supercategory": "none"},{"id": 71,"name": "toaster","supercategory": "none"},{"id": 72,"name": "sink","supercategory": "none"},{"id": 73,"name": "refrigerator","supercategory": "none"},{"id": 74,"name": "book","supercategory": "none"},{"id": 75,"name": "clock","supercategory": "none"},{"id": 76,"name": "vase","supercategory": "none"},{"id": 77,"name": "scissors","supercategory": "none"},{"id": 78,"name": "teddy bear","supercategory": "none"},{"id": 79,"name": "hair drier","supercategory": "none"},{"id": 80,"name": "toothbrush","supercategory": "none"}]
}

代码实现

import cv2
import numpy as np
from pycocotools.coco import COCO
import os
import random
import argparse# 颜色生成器:为每个类别生成一个随机颜色
def get_color_map(num_classes):color_map = {}for i in range(num_classes):color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))color_map[i] = colorreturn color_mapdef draw_coco_segmentations(annotation_file, image_dir, output_dir, draw_bbox=False, draw_id=False,  alpha=0.5):# 创建输出文件夹if not os.path.exists(output_dir):os.makedirs(output_dir)# 加载 COCO 数据集coco = COCO(annotation_file)cat_ids = coco.getCatIds()color_map = get_color_map(len(cat_ids) + 10)  # 多留几个备用颜色# 获取所有图片 IDimg_ids = coco.getImgIds()for img_id in img_ids:# 获取图片信息img_info = coco.loadImgs(img_id)[0]img_path = os.path.join(image_dir, img_info['file_name'])if not os.path.exists(img_path):print(f"⚠️ 图片不存在: {img_path}")continuetry:# 读取图像img = cv2.imread(img_path)overlay = img.copy()except Exception as e:print(f"❌ 无法读取图片 {img_path}: {e}")continue# 获取该图的所有注解ann_ids = coco.getAnnIds(imgIds=img_info['id'])anns = coco.loadAnns(ann_ids)for ann in anns:# 获取类别颜色和 IDcategory_id = ann['category_id']instance_id = ann['id']  # 实例 ID,也可以使用 category_id 表示类别 IDcolor = color_map[category_id]# 绘制多边形分割区域for seg in ann['segmentation']:poly = np.array(seg).reshape((int(len(seg)/2), 2)).astype(np.int32)cv2.fillPoly(overlay, [poly], color=color)# 可选:绘制边界框if draw_bbox and 'bbox' in ann:x, y, w, h = map(int, ann['bbox'])cv2.rectangle(overlay, (x, y), (x + w, y + h), color=(0, 255, 255), thickness=2)# 可选:绘制 ID 文字if draw_id:# 获取文字起始位置(取第一个点)text_position = tuple(poly[0])text_position = (text_position[0] - 5, text_position[1] - 5)  # 稍微偏移一下text = str(category_id)  # 你可以改为 instance_id# 设置字体和大小font = cv2.FONT_HERSHEY_SIMPLEXfont_scale = 0.5thickness = 1text_color = (255, 255, 255)  # 白色文字bg_color = (0, 0, 0)  # 黑色背景# 获取文字大小并绘制带背景的文字(text_width, text_height), _ = cv2.getTextSize(text, font, font_scale, thickness)cv2.rectangle(overlay, text_position, (text_position[0] + text_width + 2, text_position[1] - text_height - 2),bg_color, -1)cv2.putText(overlay, text, text_position, font, font_scale, text_color, thickness)# 合并原图与覆盖层result = cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)# 保存结果out_path = os.path.join(output_dir, img_info['file_name'])cv2.imwrite(out_path, result)print(f"✅ 已处理并保存: {out_path}")print("🎉 全部图片标注完成!")if __name__ == '__main__':parser = argparse.ArgumentParser(description="批量绘制 COCO 分割标签到图像上")parser.add_argument('--annotation_file', type=str, required=False, default=r'annotations.json',help='COCO JSON 注解文件路径')parser.add_argument('--image_dir', type=str, required=False, default=r'JPEGImages',help='原始图片所在目录')parser.add_argument('--output_dir', type=str, required=False, default=r'draw',help='标注后图像输出目录')parser.add_argument('--draw_bbox', type=str, choices=['True', 'False'], required=False, default='False',help='是否同时绘制边界框(True/False)')parser.add_argument('--draw_id', type=str, choices=['True', 'False'], required=False, default='False',help='是否绘制类别ID(True/False)')parser.add_argument('--alpha', type=float, default=0.5,help='分割区域的透明度(0~1)')args = parser.parse_args()# 将'draw_bbox'参数从字符串转换为布尔值args.draw_bbox = args.draw_bbox == 'True'args.draw_id = args.draw_id == 'True'draw_coco_segmentations(annotation_file=args.annotation_file,image_dir=args.image_dir,output_dir=args.output_dir,draw_bbox=args.draw_bbox,draw_id=args.draw_id,alpha=args.alpha)

输出结果

在这里插入图片描述

在这里插入图片描述

  • 由于本人水平有限,难免出现错漏,敬请批评改正。
  • 更多精彩内容,可点击进入Python日常小操作专栏、OpenCV-Python小应用专栏、YOLO系列专栏、自然语言处理专栏或我的个人主页查看
  • YOLOv8 Ultralytics:使用Ultralytics框架训练RT-DETR实时目标检测模型
  • 基于DETR的人脸伪装检测
  • YOLOv7训练自己的数据集(口罩检测)
  • YOLOv8训练自己的数据集(足球检测)
  • YOLOv5:TensorRT加速YOLOv5模型推理
  • YOLOv5:IoU、GIoU、DIoU、CIoU、EIoU
  • 玩转Jetson Nano(五):TensorRT加速YOLOv5目标检测
  • YOLOv5:添加SE、CBAM、CoordAtt、ECA注意力机制
  • YOLOv5:yolov5s.yaml配置文件解读、增加小目标检测层
  • Python将COCO格式实例分割数据集转换为YOLO格式实例分割数据集
  • YOLOv5:使用7.0版本训练自己的实例分割模型(车辆、行人、路标、车道线等实例分割)
  • 使用Kaggle GPU资源免费体验Stable Diffusion开源项目

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/diannao/89609.shtml
繁体地址,请注明出处:http://hk.pswp.cn/diannao/89609.shtml
英文地址,请注明出处:http://en.pswp.cn/diannao/89609.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

光纤(FC)交换机与以太网(网络)交换机的区别

光纤通道交换机(FC交换机)与普通以太网交换机(网络交换机)在用途、协议、性能、可靠性等方面存在显著差异,主要区别如下: 1. 用途与网络类型 FC交换机 主要用于存储区域网络(SAN)&a…

电磁场有限元方法EX2.2-里兹法求解泊松方程控制的边值问题

电磁场有限元方法EX2.2-里兹法求解泊松方程控制的边值问题 简单学习一下有限元法的基础理论,书本为电磁场有限元经典教材: THE FINITE ELEMENT METHOD IN ELECTROMAGNETICS, JIAN-MING JIN 目录 电磁场有限元方法EX2.2-里兹法求解泊松方程控制的边值问…

云端备份与恢复策略:企业如何选择最安全的备份解决方案

更多云服务器知识,尽在hostol.com 想象一下,某个凌晨,你突然发现公司所有重要数据都被加密,系统崩溃,业务停摆。有人给你打来电话说:“一切都被勒索了,恢复费用可能需要几百万。”这时&#xf…

OSPF高级特性之FRR

一、概述 众所周知,IGP当中链路状态路由协议(OSPF、ISIS)之所以可以代替我们的矢量路由协议(RIP),就是因为链路状态路由协议可以根据某些特性快速的感知到路由的变化从而改变路径。 前面我们已经介绍过了OSPF的其中一个快速收敛的机制,SPF算法,本章节将介绍另一个快速收敛机制,…

多元化国产主板,满足更高性能、更高安全的金融发展

在金融行业数字化转型的浪潮中,对于核心硬件的性能与安全需求达到了前所未有的高度。国产主板应运而生,凭借其卓越的多元化特性,为金融领域带来了高性能运算与高安全防护的双重保障,成为推动金融行业发展的关键力量。以高能计算机…

数据库分布式架构:ShardingSphere 实践

一、数据库分布式架构概述 1.1 分布式架构概念 在当今数字化时代,随着业务的不断拓展和数据量的爆炸式增长,传统的单机数据库架构逐渐暴露出诸多局限性。例如,在电商大促期间,海量的订单数据和用户访问请求会让单机数据库不堪重…

【WRFDA教程第二期】运行WRFDA 3DVAR/4DVAR数据同化

目录 一、准备阶段:下载并解压测试数据二、运行 3DVAR 教学实验日志分析(wrfda.log)进阶实验建议:对比不同设置的影响输出文件说明 三、运行 4DVAR 教学实验步骤1:准备工作目录与环境变量步骤2:链接可执行文…

redis缓存三大问题分析与解决方案

什么是缓存? 缓存(Cache)是一种将热点数据缓存在内存中(如 Redis)以加快访问速度、减轻数据库压力的技术。 但引入缓存后可能出现 三大核心问题: 缓存穿透(Cache Penetration)缓存…

李宏毅机器学习笔记——梯度下降法

深度学习介绍 基于仿生学的一种自成体系的机器学习算法,包括但不限于图像识别、语音、文本领域。 梯度下降法 作为深度学习算法种常用的优化算法 梯度下降法,是一种基于搜索的最优化方法,最用是最小化一个损失函数。梯度下降是迭代法的一…

day50/60

浙大疏锦行 DAY 50 预训练模型CBAM模块 知识点回顾: resnet结构解析CBAM放置位置的思考针对预训练模型的训练策略 差异化学习率三阶段微调 ps:今日的代码训练时长较长,3080ti大概需要40min的训练时长 作业: 好好理解下resnet18的…

Vue3 之vite.config.js配置

一、示例 import { defineConfig } from vite import vue from vitejs/plugin-vue import path from path // https://vitejs.dev/config/ export default defineConfig({plugins: [vue()],base: ./,build: {assetsDir: static, //指定静态资源目录rollupOptions: {input: {mai…

利用Gpu训练

方法一: 分别对网络模型,数据(输入,标注),损失函数调用.cuda() 网络模型: if torch.cuda.is_available():netnet.cuda() 数据(训练和测试): if torch.cud…

使用excel中的MATCH函数进行匹配数据

一、背景 在平日处理数据时,经常需要将给定数据按照制定的数据进行排序,数量比较大时,逐个处理有点费事费力且容易出错,这时可借助excel表格中match函数进行精确匹配。 二、使用match函数–精确排序操作步骤 主要工作步骤&#xf…

SpringCloud系列(41)--SpringCloud Config分布式配置中心简介

前言:微服务意味着要将单体应用中的业务拆分成一个个子服务,每个服务的粒度相对较小,因此系统中会出现大量的服务,但由于每个服务都需要必要的配置信息才能运行,所以—套集中式的、动态的配置管理设施是必不可少的&…

wireshark介绍和使用

Wireshark 介绍 Wireshark 是一款开源的 网络协议分析工具(Packet Sniffer),用于捕获和分析网络数据包。它支持多种协议解析,适用于网络调试、安全分析、网络教学等场景。 官网:https://www.wireshark.org/ 特点&#…

【甲方安全建设】敏感数据检测工具 Earlybird 安装使用详细教程

文章目录 背景工具介绍安装方法一、Linux 与 macOS 安装流程二、Windows 系统安装流程(一)三、Windows 系统安装流程(二)四、错误处理使用说明模块与规则机制集成与运维建议结语背景 随着源代码泄露、配置误提交、密码硬编码等风险频发,企业源代码库中潜在的敏感信息泄漏…

异步Websocket构建聊天室

目录 Websocket技术背景 Websockec简介 实现websocket通信程序 实验环境: 服务端(阿里云ESC,VPC网络): 客户端1(本机): 通信模型: 实现功能逻辑: 源代码: 服务…

OpenCV CUDA模块设备层-----反向二值化阈值处理函数thresh_binary_inv_func()

操作系统:ubuntu22.04 OpenCV版本:OpenCV4.9 IDE:Visual Studio Code 编程语言:C11 算法描述 OpenCV CUDA 模块(cudev) 中的一个仿函数(functor)生成器,用于创建一个反向二值化阈值…

【实现一个时间MCP完整技术解析】

🕒 MCP Time Server 完整技术解析:从核心实现到文件架构的深度剖析 目前已上传npm库,chan-mcp-time-server,有兴趣的可以下载试试 创建时间: 2025年7月2日 🎯 项目概述与架构设计 核心问题定义 AI助手在处理时间相关…

类成员方法命名风格解析:动宾、纯动词与纯名词的选择之道

在软件开发的浩瀚代码海洋中,类成员方法的命名犹如指引开发者的灯塔,其重要性不言而喻。合理的命名不仅能让代码 “自我言说”,降低理解成本,还能提升开发效率,促进团队协作。常见的类成员方法命名风格可归纳为动宾结构…