在数据处理和机器学习任务中,我们经常需要从大规模数据集中随机抽取一定数量的图像及其对应的标签文件,以便进行模型训练、验证或测试。手动操作不仅耗时,而且容易出错。为了解决这个问题,我们可以编写一个Python脚本,使用os、random和shutil库来自动化这个过程。本文将详细介绍如何编写一个随机抽取图像及其对应标签文件的脚本。
准备工作
在开始之前,请确保你的系统上已经安装了Python环境。os、random和shutil是Python标准库,自带无需安装。
脚本源码
以下是完整的Python脚本源码,该脚本可以从指定的源文件夹中随机抽取指定数量的图像文件及其对应的标签文件,并复制到目标文件夹中。
import os
import random
import shutil
# 源文件夹路径
source_image_folder = r"D:\A_Data\VOCdevkit\VOC2007\JPEGImages"
source_label_folder = r"D:\A_Data\VOCdevkit\VOC2007\Annotations"
# 目标文件夹路径
destination_image_folder = r"D:\A_Data\VOCdevkit\VOC2007\JPEGImages1"
destination_label_folder = r"D:\A_Data\VOCdevkit\VOC2007\Annotations1"
# 抽取的图像数量
num_images_to_copy = 20
# 检查目标文件夹是否存在,如果不存在,则创建它们
os.makedirs(destination_image_folder, exist_ok=True)
os.makedirs(destination_label_folder, exist_ok=True)
# 获取源图像文件夹下所有图像文件的路径
image_files = [f for f in os.listdir(source_image_folder) if os.path.isfile(os.path.join(source_image_folder, f))]
# 获取源标签文件夹下所有标签文件的路径
label_files = [f for f in os.listdir(source_label_folder) if os.path.isfile(os.path.join(source_label_folder, f))]
# 确保图像文件和标签文件命名相对应
image_files_set = set(os.path.splitext(f)[0] for f in image_files)
label_files_set = set(os.path.splitext(f)[0] for f in label_files)
common_files = list(image_files_set.intersection(label_files_set))
# 随机选择要复制的图像文件和标签文件
selected_files = random.sample(common_files, min(num_images_to_copy, len(common_files)))
# 复制图像文件和标签文件到目标文件夹
for file in selected_files:
# 源图像文件路径和目标图像文件路径
source_image_file = os.path.join(source_image_folder, file + os.path.splitext(image_files[0])[1])
destination_image_file = os.path.join(destination_image_folder, os.path.basename(source_image_file))
# 源标签文件路径和目标标签文件路径
source_label_file = os.path.join(source_label_folder, file + os.path.splitext(label_files[0])[1])
destination_label_file = os.path.join(destination_label_folder, os.path.basename(source_label_file))
# 复制图像文件和标签文件
shutil.copyfile(source_image_file, destination_image_file)
shutil.copyfile(source_label_file, destination_label_file)
print("复制完成!")
使用说明
- 修改
source_image_folder
和source_label_folder
为源文件夹路径,destination_image_folder
和destination_label_folder
为目标文件夹路径。 - 运行脚本,程序会随机选择指定数量的图像文件及其对应的标签文件,并复制到目标文件夹中。
- 确保图像文件和标签文件命名相对应,否则程序无法正常运行。
总结
这个脚本可以帮助你轻松地随机抽取指定数量的图像及其对应的标签文件,节省了大量的时间和精力。希望这个教程对你有所帮助。如果你有任何问题或建议,欢迎在评论区留言讨论。
感谢阅读!