1、功能简介
每次用labelimg标注完数据,得到批量的xml文件后,考虑到部分图片需要跳过不用标注,为了整理一一对应的图片和xml文件,下面的脚本就能排上用场了,支持jpg、jpeg、bmp图片格式(后续新图片格式也可自行添加)
第一个路径为原图片和xml路径;
第二个路径为整理好的数据路径;
2、代码
上代码:
import os
import glob
import shutil
def find_matching_image(xml_file_path):
"""
根据给定的 XML 文件路径,找到对应的同名 JPG、JPEG 或 BMP 图片路径。
:param xml_file_path: XML 文件的完整路径
:return: 对应的图片路径(JPG、JPEG 或 BMP),如果找不到则返回 None
"""
# 获取 XML 文件的目录和文件名(不带后缀)
xml_dir = os.path.dirname(xml_file_path)
xml_filename = os.path.splitext(os.path.basename(xml_file_path))[0]
# 构造可能的图片文件路径
possible_extensions = [".jpg", ".jpeg", ".bmp"]
for ext in possible_extensions:
image_file_path = os.path.join(xml_dir, f"{xml_filename}{ext}")
if os.path.exists(image_file_path):
return image_file_path
return None
def process_directory(source_directory, destination_directory):
"""
处理指定目录下的所有 XML 文件,找到对应的图片,并将它们复制到目标目录。
:param source_directory: 包含 XML 文件的源目录
:param destination_directory: 目标目录
"""
# 创建目标目录(如果不存在)
os.makedirs(destination_directory, exist_ok=True)
# 查找目录下所有的 XML 文件
xml_files = glob.glob(os.path.join(source_directory, "*.xml"))
# 遍历每个 XML 文件
for xml_file in xml_files:
image_file = find_matching_image(xml_file)
if image_file:
# 构造目标路径
dest_xml_file = os.path.join(destination_directory, os.path.basename(xml_file))
dest_image_file = os.path.join(destination_directory, os.path.basename(image_file))
# 复制文件
shutil.move(xml_file, dest_xml_file)
shutil.move(image_file, dest_image_file)
print(f"XML 文件: {xml_file} -> {dest_xml_file}")
print(f"图片文件: {image_file} -> {dest_image_file}")
print("-" * 40)
else:
print(f"找不到对应的图片文件: {xml_file}")
print("-" * 40)
if __name__ == "__main__":
# 指定源目录和目标目录
source_directory = r"D:\1"
destination_directory = r"D:\2"
# 处理目录
process_directory(source_directory, destination_directory)
接下来就能愉快的训练了!!!
本文由博客一文多发平台 OpenWrite 发布!