2

我想从训练数据集中随机选择 10 张图像作为测试数据。如果我只将选定的数据复制到目标路径,它就可以工作。但是如果我想删除源数据,它只能删除其中的一部分。我尝试了 os.remove() 和 shutil.move() 函数,但问题仍然存在。以下是我的脚本:

for label in labels:

    training_data_path_ch1 = os.path.join(training_data_folder, label, 'ch1')
    test_data_path_ch1 = os.path.join(test_data_folder, label, 'ch1')
    training_data_path_ch5 = os.path.join(training_data_folder, label, 'ch5')
    test_data_path_ch5 = os.path.join(test_data_folder, label, 'ch5')

    ch1_imgs = listdir(training_data_path_ch1)

    # Randomly select 10 images
    ch1_mask = np.random.choice(len(ch1_imgs), 10)
    ch1_selected_imgs = [ch1_imgs[i] for i in ch1_mask]

    for selected_img in ch1_selected_imgs:
        ch1_img_path = os.path.join(training_data_path_ch1, selected_img)
        shutil.copy2(ch1_img_path, test_data_path_ch1)
        os.remove(ch1_img_path)

    print('Successfully move ' + label + ' ch1 images')

我添加了一张图片来显示运行状态。

错误信息 可以看到,程序确实可以复制图片并删除部分图片,但是为什么不能全部删除呢?

有任何想法吗?我很感激任何帮助!

4

1 回答 1

6

在:

ch1_mask = np.random.choice(len(ch1_imgs), 10)

您可能会多次返回相同的索引,这意味着您正在尝试复制您已经复制和删除的文件(因此您无法在删除时再次复制它),而是通过replace=False,例如:

ch1_mask = np.random.choice(len(ch1_imgs), 10, replace=False)
于 2017-09-22T09:09:00.030 回答