-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdata_preparation.py
More file actions
150 lines (126 loc) · 4.16 KB
/
data_preparation.py
File metadata and controls
150 lines (126 loc) · 4.16 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""Please download the data from
https://www.kaggle.com/datasets/vencerlanz09/agricultural-pests-image-dataset
and rename it to `Pest Images.zip`
"""
from PIL import Image
from pathlib import Path, PurePath
from tqdm import tqdm
import os
import shutil
import numpy as np
import pandas as pd
import zipfile
def unzip_file(path):
print("Unzipping...")
file = zipfile.ZipFile("Pest Images.zip")
file.extractall(path)
print("Unzipping done.\n")
def check_dimensions(path):
container = []
for directory in path.rglob("*"):
if "ipynb" in directory.as_posix():
continue
if directory.is_file():
class_ = {}
class_["name"] = PurePath(directory.parent).parts[-1]
class_["path"] = directory
size = Image.open(directory).size
class_["width"] = size[0]
class_["height"] = size[1]
container.append(class_)
df = pd.DataFrame(container)
print("Each class' dimension")
print(df.groupby("name").describe())
print("")
return df
def split_data(
dataframe,
seed=None,
train_frac=0.7,
val_frac=0.3,
test_frac=0.1,
):
np.random.seed(seed)
MASK_INDEX = dataframe.groupby("name").sample(frac=1 - train_frac).index
train = (
dataframe.iloc[dataframe.index.difference(MASK_INDEX)]
.copy()
.reset_index(drop=True)
)
val_test = dataframe.iloc[MASK_INDEX].copy().reset_index(drop=True)
TEST_MASK = val_test.groupby("name").sample(frac=test_frac / val_frac).index
val = (
val_test.iloc[val_test.index.difference(TEST_MASK)]
.copy()
.reset_index(drop=True)
)
test = val_test.iloc[TEST_MASK].copy().reset_index(drop=True)
return train, test, val
def copy_to_target(
source_path,
target_path,
train_data,
test_data,
val_data,
color_mode="rgb",
):
print(f"Copying files {color_mode=}...\n")
if color_mode == "grayscale":
for path, target in ((train_data.path, "train"),(test_data.path, "test"),(val_data.path, "val"),):
# Split Type folder
print(f"\t{target}")
split_type = target_path / color_mode / target
for source in tqdm(path):
# Class folder
class_folder = split_type / source.relative_to(source_path).parent
class_folder.mkdir(exist_ok=True, parents=True)
img = Image.open(source).convert("L")
img = Image.fromarray(np.repeat(np.expand_dims(np.array(img), -1), 3, -1)) # 3 Channel grayscale
img.save(class_folder / f'{source.parts[-1].split(".")[0]}.JPEG', 'JPEG')
return
for path, target in ((train_data.path, "train"),(test_data.path, "test"),(val_data.path, "val"),):
# Split Type folder
print(f"\t{target}")
split_type = target_path / color_mode / target
for source in tqdm(path):
# Class folder
class_folder = split_type / source.relative_to(source_path).parent
class_folder.mkdir(exist_ok=True, parents=True)
shutil.copy(source, class_folder)
return
def main():
print("Process started...")
shutil.rmtree("Data", ignore_errors=True)
CWD = Path()
RAW_DATA_PATH = CWD / "Data" / "Raw Data"
SPLIT_DATA = CWD / "Data" / "Split Data"
RAW_DATA_PATH.mkdir(exist_ok=True, parents=True)
SPLIT_DATA.mkdir(exist_ok=True, parents=True)
unzip_file(RAW_DATA_PATH)
df = check_dimensions(RAW_DATA_PATH)
train, test, val = split_data(
dataframe=df, seed=0, train_frac=0.8, val_frac=0.2, test_frac=0
)
# Train count
print("Train Count")
print(train.name.value_counts())
print("")
# Validation count
print("Validation Count")
print(val.name.value_counts())
print("")
# Test count
print("Test Count")
print(test.name.value_counts())
print("")
copy_to_target(
source_path=RAW_DATA_PATH,
target_path=SPLIT_DATA,
train_data=train,
test_data=test,
val_data=val,
# color_mode="grayscale"
)
print("Data split done successfully.")
if __name__ == "__main__":
main()