* Codificación: UTF-8 *
importación xml.etree.ElementTree como ET
de importación xml.etree elementtree
importación salmuera
OS importación
de importación listdir OS, getcwd
de importación os.path unirse a
la importación cv2
numpy importación como np
del PIL de Importación de imágenes
clases = [ "1"] Detección de bicicletas #
def convert (tamaño, caja):
dw = 1. / tamaño [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):
# si os.path.exists ( 'E: comida-xml / /%' % (image_id)):
# list_file_train = abierto ( '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: / Usuarios / h2410796 / Desktop / suoyou / 7 /”
filelist = os.listdir (ann_path)
para los archivos de lista de archivos:
filename0 = os.path.splitext (archivos) [0] [: - 1]
img_name = os.path.splitext (archivos) [0] + '.jpg'
fileimgpath = ann_path + img_name
im = Image.open (fileimgpath)
w = int (im.size [0])
h = int (im.size [1] )
impresión (filename0) # leer el nombre del archivo
convert_annotation(filename0)