sample, shutil.move randomly extract pictures from files for movement (used to extract test set from training set)

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

  1. 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:Insert picture description here

Insert picture description here

Picture path list
Insert picture description here

2. Set the number of pictures that need to be moved

Insert picture description here
3. Get the list of names of random moving pictures
Insert picture description here
4. Move
Insert picture description here
Note: the end of the path
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43586192/article/details/110484109