原文:https://blog.csdn.net/m0_37940759/article/details/115212083
完整代码:
import xml. etree. ElementTree as ET
import pickle
import os
from os import getcwd
import numpy as np
from PIL import Image
import shutil
import matplotlib. pyplot as plt
import imgaug as ia
from imgaug import augmenters as iaa
ia. seed( 1 )
def read_xml_annotation ( root, image_id) :
in_file = open ( os. path. join( root, image_id) )
tree = ET. parse( in_file)
root = tree. getroot( )
bndboxlist = [ ]
for object in root. findall( 'object' ) :
bndbox = object . find( 'bndbox' )
xmin = int ( bndbox. find( 'xmin' ) . text)
xmax = int ( bndbox. find( 'xmax' ) . text)
ymin = int ( bndbox. find( 'ymin' ) . text)
ymax = int ( bndbox. find( 'ymax' ) . text)
bndboxlist. append( [ xmin, ymin, xmax, ymax] )
bndbox = root. find( 'object' ) . find( 'bndbox' )
return bndboxlist
def change_xml_annotation ( root, image_id, new_target) :
new_xmin = new_target[ 0 ]
new_ymin = new_target[ 1 ]
new_xmax = new_target[ 2 ]
new_ymax = new_target[ 3 ]
in_file = open ( os. path. join( root, str ( image_id) + '.xml' ) )
tree = ET. parse( in_file)
xmlroot = tree. getroot( )
object = xmlroot. find( 'object' )
bndbox = object . find( 'bndbox' )
xmin = bndbox. find( 'xmin' )
xmin. text = str ( new_xmin)
ymin = bndbox. find( 'ymin' )
ymin. text = str ( new_ymin)
xmax = bndbox. find( 'xmax' )
xmax. text = str ( new_xmax)
ymax = bndbox. find( 'ymax' )
ymax. text = str ( new_ymax)
tree. write( os. path. join( root, str ( "%06d" % ( str ( id ) + '.xml' ) ) ) )
def change_xml_list_annotation ( root, image_id, new_target, saveroot, id ) :
in_file = open ( os. path. join( root, str ( image_id) + '.xml' ) )
tree = ET. parse( in_file)
elem = tree. find( 'filename' )
elem. text = ( str