用代码将数据集的同名图像和标签txt文件按7:2:1的比例对应分割至不同文件夹下
时间: 2024-03-08 07:45:56 浏览: 18
好的,你可以使用以下 Python 代码来实现:
```python
import os
import random
import shutil
# 设置数据集路径
data_dir = "path/to/dataset"
# 设置输出路径
output_dir = "path/to/output"
# 创建输出文件夹
train_dir = os.path.join(output_dir, "train")
val_dir = os.path.join(output_dir, "val")
test_dir = os.path.join(output_dir, "test")
os.makedirs(train_dir, exist_ok=True)
os.makedirs(val_dir, exist_ok=True)
os.makedirs(test_dir, exist_ok=True)
# 获取所有图像文件
image_files = [os.path.join(data_dir, f) for f in os.listdir(data_dir) if f.endswith(".jpg")]
# 随机打乱顺序
random.shuffle(image_files)
# 计算数据集大小和分割比例
num_images = len(image_files)
num_train = int(num_images * 0.7)
num_val = int(num_images * 0.2)
num_test = num_images - num_train - num_val
# 将图像和标签文件分别移动到对应的文件夹中
for i, image_file in enumerate(image_files):
if i < num_train:
shutil.move(image_file, os.path.join(train_dir, os.path.basename(image_file)))
shutil.move(image_file[:-4] + ".txt", os.path.join(train_dir, os.path.basename(image_file)[:-4] + ".txt"))
elif i < num_train + num_val:
shutil.move(image_file, os.path.join(val_dir, os.path.basename(image_file)))
shutil.move(image_file[:-4] + ".txt", os.path.join(val_dir, os.path.basename(image_file)[:-4] + ".txt"))
else:
shutil.move(image_file, os.path.join(test_dir, os.path.basename(image_file)))
shutil.move(image_file[:-4] + ".txt", os.path.join(test_dir, os.path.basename(image_file)[:-4] + ".txt"))
```
你需要将 `path/to/dataset` 替换为你的数据集路径,将 `path/to/output` 替换为你的输出路径。代码将数据集中所有 `.jpg` 结尾的图像文件随机打乱顺序,并按照 7:2:1 的比例分割到训练、验证和测试文件夹中。同时,代码也会将每个图像文件同名的 `.txt` 文件一起移动到对应的文件夹中。