【问题标题】:how to crop images from their annotations XML format?如何从注释 XML 格式裁剪图像?
【发布时间】:2023-01-14 20:11:04
【问题描述】:

我有一个文件夹,其中包含图像及其 XML 格式的边界框注释。我试过这个脚本,但没有结果,也没有错误。有人可以帮我解决这个问题吗,谢谢。我的其余代码在评论中..

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)

【问题讨论】:

    标签: python annotations crop


    【解决方案1】:

    您可以改用此脚本:

    cut ROI from xml annotations

    1. 克隆存储库。
    2. 使用conda install -c conda-forge xmltodict安装xmltodict
    3. 将图像和相应的 xml 注释复制到数据文件夹中(在克隆的 repo 目录中)。
    4. 启动 jupyter notebook 并运行 main_classification.ipynb 文件。

    【讨论】:

      猜你喜欢
      • 2022-08-23
      • 2020-08-12
      • 1970-01-01
      • 2013-02-02
      • 2021-11-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      • 2012-11-16
      相关资源
      最近更新 更多