• 提取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".

  • 相关阅读:
    实现fastdfs防盗链功能
    pytorch环境、jupyter、pycharm
    再见 Typescript,你好 Javascript 原生打字 ✨
    【设计模式】原型模式
    Flink之常用处理函数
    【Linux】基础IO_1
    【FreeRTOS】12 任务通知——更省资源的同步方式
    自主式模块化无人机设计
    TinyWebServer学习笔记-
    计算机操作系统 第五章 虚拟存储器(3)
  • 原文地址:https://blog.csdn.net/hesongzefairy/article/details/104348298