首先,我们来看一下xml文件的格式,以了解我们需要修改的地方在哪
从xml文件的格式我们可以知道,在对图片进行resize后,只需将xml文件中的object对应的坐标乘以缩放的比例以及修改xml文件中的size为目标图形的大小即可,代码如下:
在使用下面的代码时,只需修改对应的文件夹路径及目标图像的宽高即可。
如果觉得有帮助,点个免费的赞再走呗。
import os
import cv2
import numpy as np
import xml.etree.ElementTree as ET
img_path_old = r'E:\images\original' # 原图片文件夹路径
img_path_new = r'E:\images\resize640' # 修改大小后的图片文件夹路径
xml_path_old = r'E:\labels\original' # 原xml的文件夹路径
xml_path_new = r'E:\labels\resize640' # 新xml的文件夹路径
if not os.path.exists(img_path_new): os.makedirs(img_path_new)
if not os.path.exists(xml_path_new): os.makedirs(xml_path_new)
c_w, c_h = 640, 640 # 目标图片的尺寸
def edit_xml(xml_file, ratio, i):
all_xml_file = os.pa