帮我写一段代码,将文件夹中的图片数据名称划分,并写入为val.txt,train.txt,teat.txt中
时间: 2024-10-22 13:19:02 浏览: 33
当然可以。这里是一个简单的Python脚本示例,它使用os模块来遍历文件夹,然后根据指定的比例划分图片到val.txt, train.txt, 和 test.txt 文件中。假设我们有80%的数据用于训练,10%用于验证,剩下的10%用于测试。
```python
import os
import random
# 指定图片文件夹路径
img_folder = 'your_image_folder_path'
# 图片文件后缀名
file_extension = ['.jpg', '.jpeg', '.png']
# 计算每个文件的数量和划分比例
total_files = sum(len(files) for _, _, files in os.walk(img_folder))
train_ratio = 0.8
val_ratio = 0.1
test_ratio = 0.1
train_count = int(total_files * train_ratio)
val_count = int(total_files * val_ratio)
# 随机打乱所有文件的顺序
all_files = [f for _, _, files in os.walk(img_folder) for f in files if f.endswith(file_extension)]
random.shuffle(all_files)
# 分割并写入文件
with open('train.txt', 'w') as train_file, \
open('val.txt', 'w') as val_file, \
open('test.txt', 'w') as test_file:
train_file.write('\n'.join(all_files[:train_count]))
val_file.write('\n'.join(all_files[train_count : train_count + val_count]))
test_file.write('\n'.join(all_files[train_count + val_count:]))
阅读全文