# !/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from imutils import paths
import cv2
from tqdm import tqdm
classes = []
def raad_voc_names(txt_path):
with open(txt_path, 'r') as f:
for line in f.readlines():
line = line.strip()
classes.append(line)
def convert(size, box):
dw = 1. / size[0]
dh = 1. / size[1]
x = (box[0] + box[1]) / 2.0
y = (box[2] + box[3]) / 2.0
w = box[1] - box[0]
h = box[3] - box[2]
x = x * dw
w = w * dw
y = y * dh
h = h * dh
return (x, y, w, h)
def convert_annotation(xml_root, anno_txt_root, image_id, Image_root):
in_file = open(os.path.join(xml_root, '{}.xml'.format(image_id)))
out_file = open(os.path.join(anno_txt_root, '{}.txt'.format(image_id)), 'w')
tree = ET.parse(in_file)
root = tree.getroot()
size = root.find('size') # 根据不同的xml标注习惯修改
if size:
w = int(size.find('width').text)
h = int(size.find('height').text)
else:
jpg_img_patch = Image_root + image_id + '.jpg'
jpg_img = cv2.imread(jpg_img_patch)
h, w, _ = jpg_img.shape # cv2读取的图片大小格式是w,h
for obj in root.iter('object'):
difficult = obj.find('difficult')
if difficult:
difficult = obj.find('difficult').text
else:
difficult = 0
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))
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
if __name__ == '__main__':
wd = getcwd()
print(wd)
voc_names = os.path.join(wd, 'voc.names')
raad_voc_names(voc_names)
Image_root = r'D:\data\voc\VOCdevkit\VOC2007\JPEGImages'
xml_root = r'D:\data\voc\VOCdevkit\VOC2007\Annotations'
yolo_anno = r'D:\data\voc\VOCdevkit\VOC2007\yolo_anno'
fileList = os.listdir(Image_root)
for path in tqdm(fileList):
image_ids = path.split(".")
image_id = image_ids[0]
convert_annotation(xml_root, yolo_anno, image_id, Image_root)
Reference:
https://blog.csdn.net/jiugeshao/article/details/116084611
|