当前位置:   article > 正文

paddledetection yolo格式数据转换_paddle segment 格式转换

paddle segment 格式转换

1 json转单个xml

from pycocotools.coco import COCO
import numpy as np
import tqdm
import argparse


def arg_parser():
    parser = argparse.ArgumentParser('code by rbj')
    parser.add_argument('--annotation_path', type=str,
                        default='/data/m/365/365/annotations/train/zhiyuan_objv2_train.json')
    parser.add_argument('--save_base_path', type=str, default='/data/m/365/365/annotations/txt/')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = arg_parser()
    annotation_path = args.annotation_path
    save_base_path = args.save_base_path

    data_source = COCO(annotation_file=annotation_path)
    catIds = data_source.getCatIds()
    categories = data_source.loadCats(catIds)
    categories.sort(key=lambda x: x['id'])
    classes = {}
    coco_labels = {}
    coco_labels_inverse = {}
    for c in categories:
        coco_labels[len(classes)] = c['id']
        coco_labels_inverse[c['id']] = len(classes)
        classes[c['name']] = len(classes)

    img_ids = data_source.getImgIds()
    for index, img_id in tqdm.tqdm(enumerate(img_ids), desc='change .json file to .txt file'):
        img_info = data_source.loadImgs(img_id)[0]
        file_name = img_info['file_name'].split('.')[0]
        file_name = file_name[file_name.rfind('/') + 1:]
        # print(file_name)
        height = img_info['height']
        width = img_info['width']

        save_path = save_base_path + file_name + '.txt'
        print(save_path)
        with open(save_path, mode='w') as fp:
            annotation_id = data_source.getAnnIds(img_id)
            boxes = np.zeros((0, 5))
            if len(annotation_id) == 0:
                fp.write('')
                continue
            annotations = data_source.loadAnns(annotation_id)
            lines = ''
            for annotation in annotations:
                box = annotation['bbox']
                # some annotations have basically no width / height, skip them
                if box[2] < 1 or box[3] < 1:
                    continue
                #top_x,top_y,width,height---->cen_x,cen_y,width,height
                box[0] = round((box[0] + box[2] / 2) / width, 6)
                box[1] = round((box[1] + box[3] / 2) / height, 6)
                box[2] = round(box[2] / width, 6)
                box[3] = round(box[3] / height, 6)
                # label = coco_labels_inverse[annotation['category_id']]
                label = 1
                lines = lines + str(label)
                for i in box:
                    lines += ' ' + str(i)
                lines += '\n'
            fp.writelines(lines)
    print('finish')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

2 txt转xml

import os  
  
def txt_to_xml(txt_dir_path, xml_dir_path):  
    
    for filename in os.listdir(txt_dir_path):  
        if not filename.endswith('.txt'):  
            continue  
        
        img_name = os.path.splitext(filename)[0]  
       
        xml_file_path = os.path.join(xml_dir_path, img_name + '.xml')  
      
        with open(os.path.join(txt_dir_path, filename), 'r') as f:  
            lines = f.readlines()  
            
            xml_content = '<?xml version="1.0" encoding="UTF-8"?>\n'  
            xml_content += '<annotation>'  
            
            for line in lines:  
                 
                fields = line.strip().split(' ')  
                
                width = int(float(fields[0]))  
                height = int(float(fields[1]))  
                
                xml_line = '<object class="{}" x="{}" y="{}" width="{}" height="{}"></object>'.format(  
                    fields[2], fields[3], fields[4], width, height)  
               
                xml_content += xml_line  
          
            xml_content += '</annotation>'  
            with open(xml_file_path, 'w') as f:  
                f.write(xml_content)  
                print('XML文件已保存:', xml_file_path)  

if __name__ == '__main__':
    txtDir = '/data/m/365/365/txt'
    xmlDir = '/data/m/365/365/annotations/'

    txt_to_xml(txtDir, xmlDir)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/510309?site
推荐阅读
相关标签
  

闽ICP备14008679号