切分前:health_shallow
切分后: (现在的health_shallow、hypertension_shallow就是训练集)
代码:
import os
import random
import shutil
import time
def MoveFile(imageDir,test_rate,save_test_dir):#三个参数,第一个为每个类别的所有图像在计算机中的位置
#第二个为移动的图片数目所占总的比例,最后一个为移动的图片保存的位置,
#为了方便直接把移动后的原文件夹里剩余的图片当做训练集
image_number = len(imageDir) #图片总数目
test_number = int(image_number * test_rate)#要移动的图片数目
print("要移动到%s目录下的图片数目为:%d"%(save_test_dir,test_number))
test_samples = random.sample(imageDir, test_number)#随机截取列表imageDir中数目为test_number的元素
# 移动图像到目标文件夹
if not os.path.exists(save_test_dir):
os.mkdir(save_test_dir)
print("save_test_dir has been created successfully!")
else:
print("save_test_dir already exited!")
for i,j in enumerate(test_samples):
shutil.move(test_samples[i], save_test_dir)
#原始路径
origion_paths = ['.\\shallow\health_shallow',".\\shallow\hypertension_shallow"]
# 保存路径
save_test_dirs = ['.\\shallow\\test_001health_shallow',".\\shallow\\test_002hypertension_shallow"]
test_rate = 0.2
for i,origion_path in enumerate(origion_paths):
image_list = os.listdir(origion_path) #获得原始路径下的所有图片的name(默认路径下都是图片)
image_Dir=[]
for x,y in enumerate(image_list):
image_Dir.append (os.path.join(origion_path, y))
print("%s目录下共有%d张图片!"%(origion_path,len(image_Dir)))
MoveFile(image_Dir,test_rate,save_test_dirs[i])
print("All datas has been moved successfully!")