将数据集中图片平分多个文件夹中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# 分割数据集代码将1个文件夹中的图片分开存到4个文件夹中
import os
import shutil
import random

# 源图片文件夹路径
source_folder = "C:\\Browser_download\\Bing\\coco2017\\train2017\\train2017"

# 目标文件夹路径,你可以根据需要修改这些路径
destination_folder_1 = "C:\\Browser_download\\Bing\\coco2017\\train2017\\tr1"
destination_folder_2 = "C:\\Browser_download\\Bing\\coco2017\\train2017\\tr2"
destination_folder_3 = "C:\\Browser_download\\Bing\\coco2017\\train2017\\tr3"
destination_folder_4 = "C:\\Browser_download\\Bing\\coco2017\\train2017\\tr4"

# 创建目标文件夹
os.makedirs(destination_folder_1, exist_ok=True)
os.makedirs(destination_folder_2, exist_ok=True)
os.makedirs(destination_folder_3, exist_ok=True)
os.makedirs(destination_folder_4, exist_ok=True)

# 获取源文件夹中的所有图片文件
image_files = [f for f in os.listdir(source_folder) if f.endswith(('.jpg', '.jpeg', '.png', '.gif', '.bmp'))]

# 打乱图片文件的顺序
random.shuffle(image_files)

# 将图片分成四等份
total_images = len(image_files)
quarter = total_images // 4
# 分别将图片复制到四个目标文件夹中
for i, image_file in enumerate(image_files):
if i < quarter:
destination = destination_folder_1
elif i < 2 * quarter:
destination = destination_folder_2
elif i < 3 * quarter:
destination = destination_folder_3
else:
destination = destination_folder_4

source_path = os.path.join(source_folder, image_file)
destination_path = os.path.join(destination, image_file)

shutil.copy(source_path, destination_path)

print("图片已成功分开放到四个文件夹中。")