当前位置: 首页 > news >正文

对coco格式的分割标注生成二值mask

@对coco格式的分割标注生成二值mask

对coco格式的分割标注生成二值mask

给定_annotations.coco.json文件,将里面的特定类别解码批量生成二值mask,代码如下:

import json from pathlib import Path import numpy as np from PIL import Image from pycocotools import mask as maskUtils def decode_coco_rle(rle: dict) -> np.ndarray: """ 使用 pycocotools 官方实现解码 COCO RLE,返回 0/255 的二值掩码。 rle 形如 {"counts": "...", "size": [height, width]}。 """ # 有些版本要求 counts 为 bytes,这里兼容处理一下 if isinstance(rle.get("counts"), str): rle = rle.copy() rle["counts"] = rle["counts"].encode("utf-8") mask = maskUtils.decode(rle) # H x W,0/1 uint8 # 统一转为 0/255 mask = (mask.astype(np.uint8)) * 255 return mask def main(): root = Path(__file__).resolve().parent coco_path = root / "_annotations.coco.json" images_dir = root / "images" masks_dir = root / "mask" masks_dir.mkdir(exist_ok=True) # 只保留的类别 id TARGET_CATEGORY_ID = 1 with coco_path.open("r", encoding="utf-8") as f: coco = json.load(f) # image_id -> image_info image_map = {img["id"]: img for img in coco["images"]} # image_id -> 该图像下、且 category_id == 1 的所有标注 annos_by_image = {} for anno in coco["annotations"]: if anno.get("category_id") != TARGET_CATEGORY_ID: # 忽略 category_id 为 0 或其它的标注 continue img_id = anno["image_id"] annos_by_image.setdefault(img_id, []).append(anno) # 对每张图,合成只包含 category_id == 1 的 mask for image_id, info in image_map.items(): height = info["height"] width = info["width"] mask = np.zeros((height, width), dtype=np.uint8) for anno in annos_by_image.get(image_id, []): seg = anno["segmentation"] # 只处理 RLE 字典形式 if not isinstance(seg, dict) or "counts" not in seg: continue decoded = decode_coco_rle(seg) # 多个实例取最大,合并为一张前景=255 的二值图 mask = np.maximum(mask, decoded) # 保存为灰度图(0/255) out_path = masks_dir / info["file_name"] Image.fromarray(mask, mode="L").save(out_path) print(f"saved: {out_path}") print("全部处理完成。") if __name__ == "__main__": main()

coco格式的存储形式示例如下:

http://www.cnnetsun.cn/news/88828.html

相关文章:

  • LangChain工具使用:简化AI函数调用
  • Docker 镜像打包为 tar 并在其他环境加载运行(离线部署实战指南)
  • Docker 镜像体积优化实战:从 1GB 到 100MB
  • LobeChat能否分配任务?团队协作智能调度
  • LobeChat能否拒绝不当请求?安全护栏实践
  • 基于Docker安装的TensorRT镜像实现高并发推理
  • LobeChat能否支持WebRTC?实时音视频通话功能展望
  • 基于STM32单片机双轴追光系统光照自动向日寻光蓝牙无线APP/WiFi无线APP/摄像头视频监控/云平台设计S344
  • Linly-Talker容器化构建与部署指南
  • Plotly Dash多页面仪表盘的构建框架
  • 数据可视化中色彩运用的核心指南
  • 通过“回馈行动“支持美国退伍军人掌握数据技术
  • 智能网页工作便签备忘录HTML源码
  • Deep Learning for Person Re-identification:A Survey and Outlook阅读笔记
  • 国内口碑好的牦牛绒混纺纱线供应商推荐,含 90%羊毛+10%
  • 测试左移与右移的实施方法
  • 【Maven安装配置】
  • 从原理到实战:STM8S103F3最小系统原理图绘制与PCB设计全攻略
  • 本地部署 Excalidraw 手绘白板教程
  • int32 - int32MAX 出现异常
  • Qwen-Image微调实战:让模型认识新车
  • 路由策略与策略路由
  • 软件测试面试题及答案,2026春招必看版
  • 基于飞桨实现图像分类:从LeNet到ResNet
  • 基于单片机的智能窗帘控制系统设计(光照+遥控)【附代码】
  • LobeChat插件系统开发指南:拓展你的AI应用边界
  • 基于单片机的智能燃气泄漏报警与关闭系统设计【附代码】
  • 基于单片机的智能水位控制系统设计(水箱+自动补水)【附代码】
  • LobeChat本地安装详细步骤指南
  • 《12个月服务期!黑龙江炉渣外运处置项目公开招标》