• COCO格式json切分为labelme可识别json


    coco数据格式相关内容参考之前博客

    切分的关键在于将coco_json中的annotation信息转化为labelme中shape的坐标信息

    labelme中shape需要的是多边形的点坐标,存储格式为[[x1,y1], [x2,y2]......]

    1. import os
    2. import json
    3. import pycocotools.mask as mask_utils
    4. from pycocotools.coco import COCO
    5. import cv2
    6. json_path = ''
    7. # 读取json(这里重复读取了,懒得改)
    8. with open(json_path, 'r') as f:
    9. coco_data = json.load(f)
    10. coco = COCO(json_path)
    11. output_json = ''
    12. os.makdirs(output_json, exist_ok=True)
    13. for image_data in coco_data['images']:
    14. image_id = image_data['id']
    15. image_file_name = image_data['file_name']
    16. # 创建labelme的json数据结构,这里也可以读一个labelme的json直接替换
    17. labelme_data = {
    18. 'version': '4.5.7',
    19. 'flags':{},
    20. 'shapes':[],
    21. 'imagePath':image_file_name,
    22. 'imageData':None,
    23. 'imageHeight':image_data['height'],
    24. 'imageWidth':image_data['width']
    25. }
    26. # 查找当前图像的标签数据
    27. for annotation in coco_data['annotations']:
    28. if annotation['image_id'] == image_id:
    29. category_id = annotation['category_id']
    30. # 构建labelme多边形点
    31. rle = coco.annToRLE(annotation)
    32. mask = mask_utils.decode(rle)
    33. mask[mask == 1] = 255
    34. # mask轮廓
    35. contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    36. for contour in contours:
    37. if len(contour) < 3:
    38. continue
    39. seg_xy = [[int(x), int(y)] for x,y in contour.reshape(-1, 2)]
    40. # 创建labelme的shape结构
    41. shape = {
    42. 'label': str(category_id),
    43. 'points': seg_xy,
    44. 'group_id': None,
    45. 'shape_type': 'polygon',
    46. 'flags': {}
    47. }
    48. # 将shape添加到labelme结构中
    49. labelme_data['shapes'].append(shape)
    50. # 将labelme结构写入json文件中
    51. labelme_json_file = os.path.join(output_json, os.path.splitext(image_file_name)[0]+'.json')
    52. with open(labelme_json_file, 'w') as labelme_f:
    53. json.dump(labelme_data, labelme_f, indent=2)

  • 相关阅读:
    图文详解线性回归与局部加权线性回归+房价预测实例
    汽车社媒营销创新玩法,品牌“自爆”不走寻常路
    4.1 Redis哨兵模式
    WSL2外部网络设置
    【系统设计】本地生活之附近商家 LBS 服务实现
    NanoPC-T4 Debian buster root用户自动登录
    VScode 安装插件后依然不能理解lombok注释的问题
    上海财经大学如何构建量化高频数据中心?
    动态库静态库对比
    在线安装qt5.15之后任意版本
  • 原文地址:https://blog.csdn.net/hesongzefairy/article/details/103076037