Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
This script corrects path of voc annotations to new one -- when the files are transferred to another system
import glob, os
import argparse
import xml.etree.ElementTree as ET
import ntpath
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--images", required=True, help="enter path where images are stored")
parser.add_argument("-l", "--labels", required=True, help="enter path where labels are stored")
args = parser.parse_args()
images_path = None
labels_path = None
try:
images_path = os.path.join(args.images)
labels_path = os.path.join(args.labels)
except Exception as e:
print ("Invalid path provided in argument", e)
def get_xml_files():
curr_dir = os.getcwd()
os.chdir(labels_path)
xml_files = []
for file in glob.glob("*.xml"):
xml_files.append(os.path.join(labels_path, file))
os.chdir(curr_dir)
return xml_files
def get_img_files():
curr_dir = os.getcwd()
os.chdir(images_path)
img_files = []
for file in glob.glob("*"):
if(file[:-3]) == "jpg" or "png" or "jpeg":
img_files.append(os.path.join(images_path, file))
os.chdir(curr_dir)
return img_files
def correct_xml_file_paths():
xml_files = get_xml_files()
for file in xml_files:
tree = ET.parse(file)
root = tree.getroot()
label_img_path_xml = root.find("path")
label_img_path = label_img_path_xml.text
head, tail = ntpath.split(label_img_path)
image_name = tail
label_img_path_xml.text = os.path.join(images_path, image_name)
tree.write(file)
if __name__== "__main__":
xml_files = correct_xml_file_paths()
print(xml_files)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment