-
Notifications
You must be signed in to change notification settings - Fork 0
/
preprocessing.py
154 lines (105 loc) · 3.76 KB
/
preprocessing.py
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
151
152
153
154
"""A script for pre-processing a skew detection dataset"""
import argparse
import os
import pathlib
import random
from typing import Any
import numpy as np
import pandas as pd
from PIL import Image
from skimage.transform import rotate
from tqdm.auto import tqdm
import wandb
def parse_args() -> dict[str, Any]:
parser = argparse.ArgumentParser(__name__)
parser.add_argument(
"--data-dir", help="The local dataset dir", type=str, required=True
)
parser.add_argument(
"--artifact-dir", help="The local artifact dir", type=str, required=True
)
parser.add_argument("--artifact", help="The name of the W&B artifact", type=str)
parser.add_argument(
"--train-split", help="The train split", type=float, default=0.6
)
parser.add_argument(
"--valid-split", help="The valid split", type=float, default=0.2
)
parser.add_argument("--test-split", help="The test split", type=float, default=0.2)
parser.add_argument("--seed", help="The random seed", type=int, default=10)
args = parser.parse_args()
args = vars(args)
return args
def main(
data_dir: str,
artifact_dir: str,
artifact: str | None = None,
train_split: float = 0.6,
valid_split: float = 0.2,
test_split: float = 0.2,
seed: int = 10,
):
if not os.path.exists(data_dir):
message = f"No local dataset dir: {data_dir}"
raise ValueError(message)
cumsplit = train_split + valid_split + test_split
if cumsplit != 1.0:
message = (
f"The train, valid and test splits must sum up to 1.0 - "
f"({train_split}, {valid_split}, {test_split})"
)
raise ValueError(message)
if not os.path.exists(artifact_dir):
os.mkdir(artifact_dir)
images_dir = os.path.join(artifact_dir, "images")
annotations_dir = os.path.join(artifact_dir, "annotations")
os.mkdir(images_dir)
os.mkdir(annotations_dir)
examples = []
for split in tqdm(os.listdir(data_dir)):
split_dir = os.path.join(data_dir, split)
split_dir = pathlib.Path(split_dir)
for name in tqdm(os.listdir(split_dir)):
path = os.path.join(split_dir, name)
basename, skew = name.split("[")
skew, exte = skew.split("]")
skew = float(skew)
exte = exte.replace(".", "")
out_name = f"{basename}.{exte}"
out_path = os.path.join(images_dir, out_name)
if out_name in examples:
continue
image = Image.open(path)
array = np.asarray(image)
array = rotate(array, -skew, cval=1.0)
array = array * 255
array = array.astype(np.uint8)
image = Image.fromarray(array)
image.save(out_path)
examples.append(out_name)
random.seed(seed)
random.shuffle(examples)
num_examples = len(examples)
splits = []
for split in ["train", "valid", "test"]:
fullvar = f"{split}_split"
ratio = locals()[fullvar]
num_split = int(num_examples * ratio)
splits += [split] * num_split
dataframe = pd.DataFrame.from_records(
zip(examples, splits), columns=["filename", "split"]
)
for split in ["train", "valid", "test"]:
annot = dataframe[dataframe["split"] == split]
annot = annot.reset_index(drop=True)
annot_path = os.path.join(annotations_dir, f"{split}.csv")
annot.to_csv(annot_path, index=False)
if artifact is not None:
env = wandb.init()
artifact = wandb.Artifact(artifact, type="dataset")
artifact.add_dir(images_dir)
artifact.add_dir(annotations_dir)
env.log_artifact(artifact)
if __name__ == "__main__":
args = parse_args()
main(**args)