陕西省建设资格注册中心网站,wordpress 插件player,公司网站建设基本流程,无锡网站建设365caiyi1#xff1a;需求背景 
目标检测研究中#xff0c;通常不同的模型需要不同的数据格式#xff0c;如yolo需要txt、rcnn需要coco等#xff0c;因此就需要对标注的数据格式进行转换。 
通常的数据格式有txt、coco(json)、Pascal VOC、xml等。 
本文的需求是txt转coco#xff…1需求背景 
目标检测研究中通常不同的模型需要不同的数据格式如yolo需要txt、rcnn需要coco等因此就需要对标注的数据格式进行转换。 
通常的数据格式有txt、coco(json)、Pascal VOC、xml等。 
本文的需求是txt转coco下面提供一种可行的代码可完全复制 
2格式转换代码 
需要修改的内容是 
1图像和txt数据集的路径。这个是自己配制的一般在dataset里面。将图像路径赋给images_dirtxt路径赋给annotations_dir即可。 # 路径配置根据自己的路径修改 images_dir   annotations_dir   2categories内的映射字典。详情可以打开自己的txt文件查看每一类对应的class_number例如我们这里的yolo格式中的GD图像分类编号对应0则映射字典出设置为【0: xxx,】其他内容同理。 # 类别映射字典根据自己的内容修改 categories  {     0: xxx, } # 后面可以加1、2、3... 3数据集图像的大小参数。在以下位置处的【image_width】和【image_height】替换为自己图像的分辨率。 # TODO: 如果每张图片的大小都一样你可以在这里指定         # 如果大小不一样你需要读取图片文件来获取实际尺寸         image_width  960         image_height  960 4json文件的保存位置。在以下位置处的路径【xxx.json】修改为自己的想要存放的绝对路径/相对路径即可。 # 将COCO数据结构写入JSON文件保存的json路径自己修改 with open(xxx.json, w) as json_file:     json.dump(coco_output, json_file, indent4) 完整代码如下  
import json
import os# 路径配置根据自己的路径修改
images_dir  /home/ubuntu/datasets
annotations_dir  /home/ubuntu/datasets# 类别映射字典根据自己的内容修改
categories  {0: xxx,
}# COCO格式的基本结构
coco_output  {info: {},licenses: [],images: [],annotations: [],categories: [{id: k, name: v, supercategory: } for k, v in categories.items()]
}# 图片和标注的ID计数器
image_id  1
annotation_id  1# 遍历annotations目录下的所有TXT文件
for filename in os.listdir(annotations_dir):if filename.endswith(.txt):# 假设文件名与图片文件名一致不包含扩展名image_filename  filename.replace(.txt, .jpg)image_path  os.path.join(images_dir, image_filename)# TODO: 如果每张图片的大小都一样你可以在这里指定# 如果大小不一样你需要读取图片文件来获取实际尺寸image_width  960image_height  960# 添加图片信息到COCO数据结构coco_output[images].append({id: image_id,file_name: image_filename,width: image_width,height: image_height})# 读取每个TXT文件并添加标注信息txt_file_path  os.path.join(annotations_dir, filename)with open(txt_file_path, r) as file:for line in file:class_id, x_center, y_center, width, height  map(float, line.strip().split())# COCO要求bbox是[x_min, y_min, width, height]而不是中心点坐标x_min  (x_center - width / 2) * image_widthy_min  (y_center - height / 2) * image_heightwidth  width * image_widthheight  height * image_height# 添加标注信息coco_output[annotations].append({id: annotation_id,image_id: image_id,category_id: class_id,bbox: [x_min, y_min, width, height],area: width * height,segmentation: [],  # 如果你有分割信息可以在这里添加iscrowd: 0})annotation_id  1# 更新图片IDimage_id  1# 将COCO数据结构写入JSON文件保存的json路径自己修改
with open(xxx.json, w) as json_file:json.dump(coco_output, json_file, indent4)print(Conversion completed!)