coco annotation 数据集json格式生成
使用opencv + python的方法来进行实现import osimport cv2# 打开类别标签和数字id的对应关系# 建立类别标签和数字id的对应关系# 读取images文件夹的图片名称# 读取Bbox信息w = 0# printimport osimport cv2root_path = "G:/dataset" ann_path = "C:/dataset/anno/" phase
·
annotation 数据集json格式生成
`
本文介绍了一个高效的数据转换工具,旨在将自定义的表格检测数据集自动转换为广泛使用的COCO数据格式。该工具通过解析原始的图像与文本标注,系统性地构建包含类别、图像信息及实例标注的标准化JSON文件。其核心优势在于能够精准处理四边形标注格式,完整保留表格的几何结构,同时确保与主流目标检测及实例分割框架的兼容性。此项工作为表格检测模型的训练与评估提供了高质量、标准化的数据基础,有效促进了相关研究的发展与复现。
前言
使用opencv + python的方法来进行实现
代码如下(示例):
import json
import os
import cv2
root_path = "G:/dataset"
ann_path = "C:/dataset/anno/"
phase = "train"
# 打开类别标签和数字id的对应关系
with open(os.path.join(root_path, 'classes.txt')) as f:
classes = f.read().strip()
dataset = {'categories': [], "images": [], "annotations": []}
# 建立类别标签和数字id的对应关系
for i, cls in enumerate(classes, 1):
dataset['categories'].append({'id': i, 'name': 'table', 'supercategory': 'table'})
print(dataset)
# 读取images文件夹的图片名称
indexes = [f for f in os.listdir(os.path.join(root_path, 'train'))]
# 读取Bbox信息
w = 0
for k, index in enumerate(indexes):
# print(index)
im = cv2.imread(os.path.join(root_path, 'train/') + index)
# 用opencv读取图片,得到图像的宽和高
height, width, _ = im.shape
# 添加图像的信息到dataset中
dataset['images'].append({'file_name': index,
'id': k,
'width': width,
'height': height})
with open(os.path.join(ann_path, index.replace('jpg', 'txt'))) as tr:
annos = tr.readlines()
for ii, anno in enumerate(annos):
parts = anno.strip().split(' ')
# 如果图像的名称和标记的名称对上,则添加标记
if parts[0] == index and len(parts) == 18:
print(parts[0])
# 类别
cls_id = parts[1]
# width = parts[2]
# height = parts[3]
# 面积
area = float(parts[4])
iscrowd = int(parts[5])
x1 = float(parts[6])
y1 = float(parts[7])
x2 = float(parts[8])
y2 = float(parts[9])
x3 = float(parts[10])
y3 = float(parts[11])
x4 = float(parts[12])
y4 = float(parts[13])
bbox1 = float(parts[14])
bbox2 = float(parts[15])
bbox3 = float(parts[16])
bbox4 = float(parts[17])
dataset['annotations'].append({
'area': area,
'bbox': [bbox1, bbox2, bbox3, bbox4],
'category_id': int(cls_id),
'id': w,
'image_id': k,
'iscrowd': 0,
'segmentation': [[x1, y1, x2, y2, x3, y3, x4, y4]]
})
w += 1
print(w)
# 保存结果的文件夹
print(dataset)
folder = os.path.join(root_path, 'annotations1')
if not os.path.exists(folder):
os.makedirs(folder)
json_name = os.path.join(root_path, 'annotations1/{}.json'.format(phase))
with open(json_name, 'w') as f:
json.dump(dataset, f)
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐



所有评论(0)