- .odgt转.json(coco)
import os
import json
from PIL import Image
def load_file(fpath):
assert os.path.exists(fpath)
with open(fpath,'r') as fid:
lines = fid.readlines()
records = [json.loads(line.strip('\n')) for line in lines]
return records
def crowdhuman2coco(odgt_path, json_path):
records = load_file(odgt_path)
json_dict = {"images": [], "annotations": [], "categories": []}
START_B_BOX_ID = 1
image_id = 1
bbox_id = START_B_BOX_ID
image = {}
annotation = {}
categories = {}
record_list = len(records)
print(record_list)
for i in range(record_list):
file_name = records[i]['ID'] + '.jpg'
im = Image.open("D:/DataSet/CrowdHuman/CrowdHuman_train/Images/" + file_name)
image = {'file_name': file_name, 'height': im.size[1], 'width': im.size[0],
'id': image_id}
json_dict['images'].append(image)
gt_box = records[i]['gtboxes']
gt_box_len = len(gt_box)
for j in range(gt_box_len):
category = gt_box[j]['tag']
if category not in categories:
new_id = len(categories) + 1
categories[category] = new_id
category_id = categories[category]
fbox = gt_box[j]['fbox']
ignore = 0
if "ignore" in gt_box[j]['head_attr']:
ignore = gt_box[j]['head_attr']['ignore']
if "ignore" in gt_box[j]['extra']:
ignore = gt_box[j]['extra']['ignore']
annotation = {'area': fbox[2] * fbox[3], 'iscrowd': ignore, 'image_id':
image_id, 'bbox': fbox, 'hbox': gt_box[j]['hbox'], 'vbox': gt_box[j]['vbox'],
'category_id': category_id, 'id': bbox_id, 'ignore': ignore, 'segmentation': []}
json_dict['annotations'].append(annotation)
bbox_id += 1
image_id += 1
for cate, cid in categories.items():
cat = {'supercategory': 'none', 'id': cid, 'name': cate}
json_dict['categories'].append(cat)
json_fp = open(json_path, 'w')
json_str = json.dumps(json_dict)
json_fp.write(json_str)
json_fp.close()
if __name__ == '__main__':
crowdhuman2coco(r'D:\DataSet\CrowdHuman\annotation_train.odgt', r'D:\DataSet\CrowdHuman\annotation_train\annotation.json')
- .json转.txt
import json
import os
import xml.etree.ElementTree as ET
import cv2
def xyxy2xywh(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[2]) / 2 * dw
y = (box[1] + box[3]) / 2 * dh
w = (box[2] - box[0]) * dw
h = (box[3] - box[1]) * dh
return (x, y, w, h)
def voc2yolo(path):
print(len(os.listdir(path)))
pic_path = r'D:\DataSet\46_CUHK Occlusion Dataset\images'
txt_out_path = r'D:\DataSet\46_CUHK Occlusion Dataset\labels\txt'
for file in os.listdir(path):
print(file)
if "json" in str(file):
with open(os.path.join(path, file), 'r') as f:
data = json.load(f)
print(data)
points = data['shapes'][0]['points']
pic_name = os.path.join(pic_path, data['imagePath'])
txt_name = data['imagePath'].split(".")[0] + ".txt"
imread = cv2.imread(pic_name)
h = imread.shape[0]
w = imread.shape[1]
print(imread.shape)
xmin = points[0][0]
ymin = points[0][1]
xmax = points[2][0]
ymax = points[2][1]
box = [float(xmin), float(ymin), float(xmax),
float(ymax)]
print(box)
bbox = xyxy2xywh((w, h), box)
print(bbox)
with open(os.path.join(txt_out_path, txt_name), 'w') as out_file:
out_file.write(str(0) + " " + " ".join(str(x) for x in bbox) + '\n')
out_file.close()
if __name__ == '__main__':
path = r'D:\DataSet\46_CUHK Occlusion Dataset\labels\json'
voc2yolo(path)
- .xml转.txt
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join
def convert(size, box):
x_center = (box[0] + box[1]) / 2.0
y_center = (box[2] + box[3]) / 2.0
x = x_center / size[0]
y = y_center / size[1]
w = (box[1] - box[0]) / size[0]
h = (box[3] - box[2]) / size[1]
return (x, y, w, h)
def convert_annotation(xml_files_path, save_txt_files_path, classes):
xml_files = os.listdir(xml_files_path)
print(xml_files)
for xml_name in xml_files:
print(xml_name)
xml_file = os.path.join(xml_files_path, xml_name)
out_txt_path = os.path.join(save_txt_files_path, xml_name.split('.')[0] + '.txt')
out_txt_f = open(out_txt_path, 'w')
tree = ET.parse(xml_file)
root = tree.getroot()
size = root.find('size')
w = int(size.find('width').text)
h = int(size.find('height').text)
for obj in root.iter('object'):
difficult = obj.find('difficult').text
cls = obj.find('name').text
if cls not in classes or int(difficult) == 1:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
float(xmlbox.find('ymax').text))
print(w, h, b)
bb = convert((w, h), b)
out_txt_f.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
if __name__ == "__main__":
classes = ['bird','cat', 'cow', 'dog', 'horse', 'sheep', 'person']
xml_files1 = r'D:\DataSet\person_datasets\CUHK01\xml'
save_txt_files1 = r'D:\DataSet\person_datasets\CUHK01\txt'
convert_annotation(xml_files1, save_txt_files1, classes)