* coding:utf-8 *
import xml.etree.ElementTree as ET
from xml.etree import ElementTree
import pickle
import os
from os import listdir, getcwd
from os.path import join
import cv2
import numpy as np
from PIL import Image
classes = [“1”] # 自行车检测
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(image_id):
# if os.path.exists(‘E:/food-xml/%’ % (image_id)):
# list_file_train = open(‘D:/10_14/train.txt’, ‘a+’, encoding=‘utf-8’)
# list_file_train.write(‘D:/10_14/yoloData/%s.jpg\n’ % (str(image_id)))
# list_file_train.close()
in_file = open('D:/Users/h2410796/Desktop/xml/7/%s.xml' % (image_id), encoding='utf-8')
out_file = open('D:/Users/h2410796/Desktop/txt/7/%s.txt' % (image_id), 'a', encoding='utf-8') # 生成txt格式文件
tree = ET.parse(in_file)
root = tree.getroot()
for obj in root.iter('object'):
cls = obj.find('name').text
if cls not in classes:
continue
cls_id = classes.index(cls)
xmlbox = obj.find('bndbox')
# print(type(xmlbox.find('xmin').text))
b = (float(xmlbox.find('xmin').text)-650, float(xmlbox.find('xmax').text)-650, float(xmlbox.find('ymin').text)-1950,
float(xmlbox.find('ymax').text)-1950)
bb = convert((w, h), b)
out_file.write(str(cls_id) + " " + " ".join([str(a) for a in bb]) + '\n')
# cv2.imwrite(r'./data/duodianpian' + '/' + str(i.split('/')[2].split('\\')[1]), dst)
# cv2.waitKey(0)
ann_path=“D:/Users/h2410796/Desktop/suoyou/7/”
filelist = os.listdir(ann_path)
for files in filelist:
filename0 = os.path.splitext(files)[0][:-1]
img_name = os.path.splitext(files)[0] + ‘.jpg’
fileimgpath = ann_path + img_name
im = Image.open(fileimgpath)
w = int(im.size[0])
h = int(im.size[1])
print(filename0)# 读取文件名
convert_annotation(filename0)