Problem Description:
Randomly move 2 copies of the pictures in the training set (accounting for 0.1) to form a verification set and a test set
Complete code
import shutil
import random
import os
'''
获取所有图片的路径;
移动图片的数目
获取随机移动图片的名称列表
移动图片
'''
# shutil.move(train_path,verify_path)
# random.sample()
def move_file(file_dir, dst_dir):
path_dir = os.listdir(file_dir) # 源图像路径
file_num = len(path_dir)
rate = 0.1 # 移走图片的比率
# move_num=int(file_num*rate)
move_num = 200
sample = random.sample(path_dir, move_num) # 随机移动的图片名称
for name in sample:
shutil.move(file_dir + name, dst_dir + name)
return
if __name__ == '__main__':
# 注意最后有一个斜杠!!!
train_path = r'G:/00_deeplearning/机器学习/01_code/data/分纤箱外景照/train_image/' # 原图文件
aim_path = r'G:/00_deeplearning/机器学习/01_code/data/分纤箱外景照/test_image/' # 目标文件夹
move_file(train_path, aim_path)
Problem solving ideas
- Get all image path list
At this time, list is the name of each image to be extracted, not the complete path
Storage image path:
Picture path list
2. Set the number of pictures that need to be moved
3. Get the list of names of random moving pictures
4. Move
Note: the end of the path