Python按照类划分文件夹

采用的是Cars-196数据集

文件目录

cars:

        -car_ims(里面全是图片)

        -cars_annos.mat(标签文件)

from scipy.io import loadmat
import os
import shutil
basepath = r"D:\A_Datasets\cars"
# get image list
annos = loadmat(os.path.join(basepath, 'cars_annos.mat'),
                squeeze_me=True)['annotations']
kind = 'test'
zeroshot=True
imlbs = []
for entry in annos:
    label = int(entry[5])
    istrain = bool(entry[6])
    if zeroshot:
        istrain = True if (label <= 98) else False
    if (istrain and kind == 'test') or (
            not istrain and kind == 'train'):
        continue
    imlbs.append((
        os.path.join(basepath, entry[0]), label))
imlbs = sorted(imlbs, key=lambda x: x[0])

print(f'Cars-196[{kind}]: Got {len(imlbs)} Images.')
for index in range(len(imlbs)):
    image_path, label = imlbs[index]
    file_name = str(index)
    if kind == "test" :
        new_file_path = os.path.join(basepath, "test",str(label))
    elif kind =="train":
        new_file_path = os.path.join(basepath, "train", str(label))
    if not os.path.exists(new_file_path):
        print("路径 " + new_file_path + " 不存在,正在创建......")
        os.makedirs(new_file_path)
    shutil.copy(image_path, new_file_path)