how to crop images from their annotations XML format?

Viewed 7

I have one folder which contains images and their annotations of bounding boxes in XML format. I have tried this script, but there is no result and no errors. can someone help me to solve this and thank you. the rest of my code in the comment..

original_file = r"C:\Users\probook\Downloads\Compressed\crop\train"
dst = r"C:\Users\probook\Downloads\Compressed\crop\save"


def check_folder_exists(path):
    if not os.path.exists(path):
        try:
            os.makedirs(path)
            print('create ' + path)
        except OSError as e:
            if e.errno != errno.EEXIST:
                raise
seed_arr = []
for xml_file in glob.glob('train/*.xml'):
    root = ET.parse(xml_file).getroot()
    filename = root.find('filename').text

    for type_tag in root.findall('size'):
        #file_name = type_tag.find('filename').text
         width = type_tag.find('width').text
         height = type_tag.find('height').text

    for type_tag in root.findall('object'):
        class_name = type_tag.find('name').text
        xmin = type_tag.find('bndbox/xmin').text
        ymin = type_tag.find('bndbox/ymin').text
        xmax = type_tag.find('bndbox/xmax').text
        ymax = type_tag.find('bndbox/ymax').text
        all_list = [filename, width, height,
                   class_name, xmin, ymin, xmax, ymax]

       seed_arr.append(all_list)

seed_arr.sort()

for index, line in enumerate(seed_arr):
    filename = line[0]
    width = line[1]
    height = line[2]
    class_name = line[3]
    xmin = line[4]
    ymin = line[5]
    xmax = line[6]
    ymax = line[7]

           load_img_path = os.path.join(original_file, filename)

   save_class_path = os.path.join(dst, class_name)
   check_folder_exists(save_class_path)
   save_img_path = os.path.join(save_class_path, 
   str(index)+'_'+filename)

   img = Image.open(load_img_path)
   crop_img = img.crop((int(xmin), int(ymin), int(xmax), int(ymax)))
   im1 = crop_img.resize(64 , 64)
   im1.save(save_img_path, 'JPEG')
   print('save ' + save_img_path)
0 Answers
Related