- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsplit_data.py
More file actions
Latest commit
56 lines (43 loc) · 2.11 KB
/
Copy pathsplit_data.py
File metadata and controls
56 lines (43 loc) · 2.11 KB
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
47
48
49
50
51
52
53
54
55
56
importos
importshutil
fromsklearn.model_selectionimporttrain_test_split
# Define the paths
dataset_dir=r"D:\PhD\Year - IV\Datasets\private\group_species_dataset"# Replace with your dataset directory
output_dir=r"D:\PhD\Year - IV\Datasets\private\species_dataset"# Replace with your desired output directory
# Create the output directories for each category
categories= [namefornameinos.listdir(dataset_dir) ifos.path.isdir(os.path.join(dataset_dir, name))]
# Create train and test directories
train_dir=os.path.join(output_dir, 'train_data')
test_dir=os.path.join(output_dir, 'test_data')
os.makedirs(train_dir, exist_ok=True)
os.makedirs(test_dir, exist_ok=True)
# Create category directories in train and test directories
forcategoryincategories:
os.makedirs(os.path.join(train_dir, category), exist_ok=True)
os.makedirs(os.path.join(test_dir, category), exist_ok=True)
# Function to copy files
defcopy_files(file_list, source_dir, dest_dir):
forfileinfile_list:
# shutil.copy(os.path.join(source_dir, file), os.path.join(dest_dir, file))
shutil.move(os.path.join(source_dir, file), os.path.join(dest_dir, file))
# Load images and labels
images= []
labels= []
forcategoryincategories:
category_dir=os.path.join(dataset_dir, category)
forimg_fileinos.listdir(category_dir):
ifimg_file.endswith(('.png', '.jpg', '.jpeg', '.JPG')):
images.append(img_file)
labels.append(category)
# Split the dataset
train_images, test_images, train_labels, test_labels=train_test_split(images, labels, stratify=labels, test_size=0.25, random_state=42)
# Copy files to respective directories
forimg, labelinzip(train_images, train_labels):
source_dir=os.path.join(dataset_dir, label)
dest_dir=os.path.join(train_dir, label)
copy_files([img], source_dir, dest_dir)
forimg, labelinzip(test_images, test_labels):
source_dir=os.path.join(dataset_dir, label)
dest_dir=os.path.join(test_dir, label)
copy_files([img], source_dir, dest_dir)
print("Data successfully split and moved to train_data and test_data directories.")