• 提取coco格式json信息生成图片mask


    书接上文coco详解内容,一整个json文件可读性非常差,有时候需要将json文件中的信息提取出来生成图像对应的mask,代码涉及pycocotools工具使用:

    1. import os
    2. import numpy as np
    3. import pycocotools.mask as mask_utils
    4. from pycocotools.coco import COCO
    5. import cv2
    6. from tqdm import tqdm
    7. # 根据自己情况设置图片、json以及mask保存路径
    8. img_path = ''
    9. json_path = ''
    10. save_mask = ''
    11. os.makedirs(save_mask, exist_ok=True)
    12. # 通过pycocotools加载json文件
    13. coco = COCO(json_path)
    14. # 获取json中的图像id
    15. images_ids = coco.getImgIds()
    16. # 逐图处理
    17. for img_id in tqdm(images_ids):
    18. # 根据图像唯一id获取对应信息
    19. img_info = coco.loadImgs(img_id)[0]
    20. img_files_path = os.path.join(img_path, img_info['file_name'])
    21. height, width = img_info['height'], img_info['width']
    22. # 根据图像id获取对应标签信息
    23. ann_ids = coco.getAnnIds(imgIds=img_id)
    24. anns = coco.loadAnns(ann_ids)
    25. # 逐实例处理(一个图像存在多个实例)
    26. for ann in anns:
    27. rle = coco.annToRLE(ann)
    28. mask = mask_utils.decode(rle)
    29. mask[mask == 1] = 255 # 调整mask中的像素值
    30. # 保存mask
    31. mask_name = img_info['file_name'].replace('.jpg', f'_{ann['category_id']}.jpg')
    32. cv2.imwrite(os.path.join(save_mask, mask_name), mask)

    附:

    1. # The following API functions are defined:
    2. # COCO - COCO api class that loads COCO annotation file and prepare data structures.
    3. # getAnnIds - Get ann ids that satisfy given filter conditions.
    4. # getCatIds - Get cat ids that satisfy given filter conditions.
    5. # getImgIds - Get img ids that satisfy given filter conditions.
    6. # loadAnns - Load anns with the specified ids.
    7. # loadCats - Load cats with the specified ids.
    8. # loadImgs - Load imgs with the specified ids.
    9. # annToMask - Convert segmentation in an annotation to binary mask.
    10. # showAnns - Display the specified annotations.
    11. # loadRes - Load algorithm results and create API for accessing them.
    12. # download - Download COCO images from mscoco.org server.
    13. # Throughout the API "ann"=annotation, "cat"=category, and "img"=image.
    14. # Help on each functions can be accessed by: "help COCO>function".

  • 相关阅读:
    如何看待PyTorch 2.0?
    雅思口语同替高分表达
    Hexagon_V65_Programmers_Reference_Manual(6)
    《Docker极简教程》--Docker镜像--Docker镜像的管理
    Java Stream 函数式接口外部实例的引用
    01Java语言概述
    ubuntu21.04 + 编译 debian11 报错解决过程
    【无标题】放大放大放大
    SpringBoot+Thymeleaf上传头像并回显【表单提交】
    数字工厂中的SCADA(数据采集与监控系统)
  • 原文地址:https://blog.csdn.net/hesongzefairy/article/details/104348298