import glob
import xml.dom.minidom
import cv2
from PIL import Image
import matplotlib.pyplot as plt
import os
# 定义待批量裁剪图像的路径地址
IMAGE_INPUT_PATH = 'D:/Object Detection/2021V1/JPEGImages'
XML_INPUT_PATH = 'D:/Object Detection/2021V1/Annotations'
# 定义裁剪后的图像存放地址
IMAGE_OUTPUT_PATH = 'D:/Object Detection/2021V1/1'
XML_OUTPUT_PATH = 'D:/Object Detection/2021V1/2'
imglist = os.listdir(IMAGE_INPUT_PATH)
xmllist = os.listdir(XML_INPUT_PATH)
for i in range(len(imglist)):
# 每个图像全路径
image_input_fullname = IMAGE_INPUT_PATH + '/' + imglist[i]
xml_input_fullname = XML_INPUT_PATH + '/' + xmllist[i]
image_output_fullname = IMAGE_OUTPUT_PATH + '/' + imglist[i]
xml_output_fullname = XML_OUTPUT_PATH + '/' + xmllist[i]
# 定义缩放信息 以等比例缩放到416为例
dom = xml.dom.minidom.parse(xml_input_fullname)
root = dom.documentElement
# 读取标注目标框
objects = root.getElementsByTagName("bndbox")
for object in objects:
xmin = object.getElementsByTagName("xmin")
xmin_data = round(float(xmin[0].firstChild.data))
# xmin[0].firstChild.data =str(int(xmin1 * x))
ymin = object.getElementsByTagName("ymin")
ymin_data = round(float(ymin[0].firstChild.data))
xmax = object.getElementsByTagName("xmax")
xmax_data = round(float(xmax[0].firstChild.data))
ymax = object.getElementsByTagName("ymax")
ymax_data = round(float(ymax[0].firstChild.data))
img = cv2.imread(image_input_fullname)
height, width = img.shape[:2]
scale1 = 256 / height
scale2 = 256 / width
height = 256
width = 256
# 更新xml
width_xml = root.getElementsByTagName("width")
width_xml[0].firstChild.data = width
height_xml = root.getElementsByTagName("height")
height_xml[0].firstChild.data = height
print(scale1)
print(scale2)
xmin[0].firstChild.data = round(xmin_data * scale2)
ymin[0].firstChild.data = round(ymin_data * scale1)
xmax[0].firstChild.data = round(xmax_data * scale2)
ymax[0].firstChild.data = round(ymax_data * scale1)
# 另存更新后的文件
with open(xml_output_fullname, 'w') as f:
dom.writexml(f, addindent=' ', encoding='utf-8')
# 测试缩放效果
img = cv2.resize(img, (width, height))
# xmin, ymin, xmax, ymax分别为xml读取的坐标信息
left_top = (int(xmin_data * scale2), int(ymin_data * scale1))
right_down = (int(xmax_data * scale2), int(ymax_data * scale1))
# cv2.rectangle(img, left_top, right_down, (255, 0, 0), 1)
cv2.imwrite(image_output_fullname, img)
版权声明:本文在CSDN博主「qq_43289516」的原创文章上修改部分代码实现同步缩放的功能,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_43289516/article/details/106473687