"""
#!/usr/bin/env python
# -*- coding:utf-8 -*-
@Project : Sample Generator
@File : 4.py
@Author : hxy-ZW
@Time : 2024/2/6 9:34
@Description:对比调整不同生成图片的标注
"""
import os
import xml.etree.ElementTree as ET
import cv2
import re
from xml.etree.ElementTree import parse
def read_image_width(image_path):
# 读取图片并获取宽度
img = cv2.imread(image_path)
return img.shape[1] # 返回宽度
def read_image_height(image_path):
# 读取图片并获取高度
img = cv2.imread(image_path)
return img.shape[0] # 返回高度
def adjust_annotations(input_folder1, input_folder2, output_folder1, output_folder2):
# 读取两个目录中的图片文件名
image_filenames1 = os.listdir(input_folder1)
image_filenames2 = os.listdir(input_folder2)
# 遍历两个目录中的图片文件名
for filename in image_filenames1:
if filename in image_filenames2:
# 获取两个目录中相同名称的图片路径
image_path1 = os.path.join(input_folder1, filename)
image_path2 = os.path.join(input_folder2, filename)
# 计算两个图片的宽度比值
width1 = read_image_width(image_path1)
width2 = read_image_width(image_path2)
scale_factor = width2 / width1
file_name1 = filename.replace("jpg", "xml")
# 创建或打开输出文件,并将比值写入标注文件
for file_name in os.listdir(output_folder1):
if file_name == file_name1:
# 构建文件的完整路径
file_path = os.path.join(output_folder1, file_name)
file_xml = filename.replace("xml", "jpg")
file_xml=re.sub(u"([^\u0030-\u0039])","",file_xml)
# 优化:使用 xml.etree.ElementTree 模块的 parse 方法加载 XML 文件
tree = parse(file_path)
# 获取根节点
root = tree.getroot()
obj = tree.getroot()
file_text=re.sub(u"([^\u0030-\u0039])", "", obj.find('filename').text)
if file_text ==file_xml :
for obj in root.findall('object'):
for bounding_box in obj.findall('bndbox'):
obj_struct = {}
obj_struct['bbox'] = (
int(bounding_box.find('xmin').text), int(bounding_box.find('ymin').text),
int(bounding_box.find('xmax').text), int(bounding_box.find('ymax').text))
print(obj_struct)
# 计算修改后的边界框坐标
defaultxmin = int(float(bounding_box.find('xmin').text) * scale_factor)
bounding_box.find('xmin').text = str(defaultxmin)
print(bounding_box.find('xmin').text)
defaultxmax = int(float(bounding_box.find('xmax').text) * scale_factor)
bounding_box.find('xmax').text = str(defaultxmax)
print(defaultxmax)
tree.write(os.path.join(output_folder2, file_name))
else:
continue
if __name__ == '__main__':
# 替换为实际的输入文件夹路径
input_folder1 = "F:\\png1"
# 替换为实际的输入文件夹路径
input_folder2 = "F:\\png2"
# 替换为实际的输出文件夹路径
output_folder1 = "F:\\xml"
output_folder2 = "F:\\xml2"
# 调用函数进行标注文件的调整
adjust_annotations(input_folder1, input_folder2, output_folder1, output_folder2)
print("已完成替换")
对比调整不同生成图片的标注
于 2024-02-06 15:21:00 首次发布