切分前:health_shallow
    image.png
    切分后: (现在的health_shallow、hypertension_shallow就是训练集)
    image.png

    代码:

    1. import os
    2. import random
    3. import shutil
    4. import time
    5. def MoveFile(imageDir,test_rate,save_test_dir):#三个参数,第一个为每个类别的所有图像在计算机中的位置
    6. #第二个为移动的图片数目所占总的比例,最后一个为移动的图片保存的位置,
    7. #为了方便直接把移动后的原文件夹里剩余的图片当做训练集
    8. image_number = len(imageDir) #图片总数目
    9. test_number = int(image_number * test_rate)#要移动的图片数目
    10. print("要移动到%s目录下的图片数目为:%d"%(save_test_dir,test_number))
    11. test_samples = random.sample(imageDir, test_number)#随机截取列表imageDir中数目为test_number的元素
    12. # 移动图像到目标文件夹
    13. if not os.path.exists(save_test_dir):
    14. os.mkdir(save_test_dir)
    15. print("save_test_dir has been created successfully!")
    16. else:
    17. print("save_test_dir already exited!")
    18. for i,j in enumerate(test_samples):
    19. shutil.move(test_samples[i], save_test_dir)
    20. #原始路径
    21. origion_paths = ['.\\shallow\health_shallow',".\\shallow\hypertension_shallow"]
    22. # 保存路径
    23. save_test_dirs = ['.\\shallow\\test_001health_shallow',".\\shallow\\test_002hypertension_shallow"]
    24. test_rate = 0.2
    25. for i,origion_path in enumerate(origion_paths):
    26. image_list = os.listdir(origion_path) #获得原始路径下的所有图片的name(默认路径下都是图片)
    27. image_Dir=[]
    28. for x,y in enumerate(image_list):
    29. image_Dir.append (os.path.join(origion_path, y))
    30. print("%s目录下共有%d张图片!"%(origion_path,len(image_Dir)))
    31. MoveFile(image_Dir,test_rate,save_test_dirs[i])
    32. print("All datas has been moved successfully!")