-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_img_from_json.py
More file actions
176 lines (160 loc) · 6.06 KB
/
process_img_from_json.py
File metadata and controls
176 lines (160 loc) · 6.06 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import json
import os
from PIL import Image
import argparse
RAW_DATA_PATH = os.path.join("obj_det", "imgs")
PROCESSED_TRAIN_DATA_PATH = "C:\\Users\\shubh\\OneDrive\\Desktop\\ENTR 390\\Dataset\\Train"
PROCESSED_VAL_DATA_PATH = os.path.join("obj_det", "imgs")
JSON_F = "C:\\Users\\shubh\\OneDrive\\Desktop\\ENTR 390\\Dataset\\Mobility.json"
NEW_SHAPE = (100, 100)
TRAIN_TO_VAL_RATIO = 0.7
def gen_json():
json_f = {
'obj': [
{
'f_name' : 'lol.png',
'label': 'dude',
'size_x': 540,
'size_y': 900,
'dim': [180,30,180,30] # xmax, xmin, ymax, ymin
},
{
'f_name' : 'ksk.png',
'label': 'eecs',
'size_x': 540,
'size_y': 900,
'dim': [180,30,180,30] # xmax, xmin, ymax, ymin
},
]
}
return json_f
def write_json(j, train=True):
if train:
print("write train json file...")
with open('train.json', 'w') as f:
json.dump(j, f)
else:
print("write val json file...")
with open('val.json', 'w') as f:
json.dump(j, f)
# process images and create updated json file
def process_images():
train_j = {'obj':[]}
val_j = {'obj':[]}
j = {}
with open(JSON_F, 'r') as f:
j = json.load(f)
index = 0
divide = len(j['obj']) * TRAIN_TO_VAL_RATIO
for idx, obj in enumerate(j['obj']):
if (idx < divide):
if obj['label'] != 'NA':
region = (obj['dim'][1], obj['dim'][3], obj['dim'][0], obj['dim'][2])
f_name = crop_and_resize_image(obj['f_name'], region=region, index=index, train=True)
obj['f_name'] = f_name
if obj['label']=='wheelchair':
train_j['obj'].append({
'f_name': f_name,
'label': obj['label'],
'size_x': obj['size_x'],
'size_y': obj['size_y'],
'dim': region
})
index += 1
else:
train_j['obj'].append({
'f_name': f_name,
'label': 'not_wheelchair',
'size_x': obj['size_x'],
'size_y': obj['size_y'],
'dim': region
})
index += 1
if (idx % 100 == 0):
write_json(train_j, train=True)
else:
if obj['label'] != 'NA':
region = (obj['dim'][1], obj['dim'][3], obj['dim'][0], obj['dim'][2])
f_name = crop_and_resize_image(obj['f_name'], region=region, index=index, train=False)
obj['f_name'] = f_name
if obj['label']=='wheelchair':
val_j['obj'].append({
'f_name': f_name,
'label': obj['label'],
'size_x': obj['size_x'],
'size_y': obj['size_y'],
'dim': region
})
index += 1
else:
val_j['obj'].append({
'f_name': f_name,
'label': 'not_wheelchair',
'size_x': obj['size_x'],
'size_y': obj['size_y'],
'dim': region
})
index += 1
if (idx % 100 == 0):
write_json(val_j, train=False)
def num_objects(f_name, j):
# Given json file and the image file name, return number of objects detected
# in the image.
#
# Input- f_name: name of the image (string)
# j: json file (Dict)
#
# Output- : number of objects detected in the image
return len(j.get(f_name))
def find_region(f_name, j, idx):
# Given json file and the image file name and the index of the object
# , return the region of the object in the json file.
#
# Input- f_name: name of the image (string)
# j: json file (Dict)
# idx: index of the object (Int)
#
# Output- : tuple represents the region of the object
try:
obj = j.get(f_name)[idx]
return (obj.get("left"), obj.get("up"), obj.get("right"), obj.get("down"))
except Exception as e:
print("Exception happened in finding region: {}".format(str(e)))
def crop_and_resize_image(f_name, region, index, train=True, save=True):
img_path = os.path.join(os.getcwd(), RAW_DATA_PATH, f_name)
if f_name.endswith('.jpg') or f_name.endswith('.png'):
f_name = f_name[:-4] + '_' + str(index) + f_name[-4:]
if train:
save_path = os.path.join(os.getcwd(), PROCESSED_TRAIN_DATA_PATH, f_name)
else:
save_path = os.path.join(os.getcwd(), PROCESSED_VAL_DATA_PATH, f_name)
try:
img = Image.open(img_path)
img = img.crop(region).resize(NEW_SHAPE)
if save:
img.save(save_path)
return f_name
except:
print("failed to process image")
exit(1)
return img
def parse_args():
global RAW_DATA_PATH, PROCESSED_TRAIN_DATA_PATH, PROCESSED_VAL_DATA_PATH, JSON_F, NEW_SHAPE
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--shape", nargs=2, default=(32, 32), required=False)
parser.add_argument("-j", "--json", nargs='*', default="my.json", required=False)
parser.add_argument("-r", "--raw", nargs=1, default="d", required=False)
parser.add_argument("-p", "--processed", nargs=1, default="done", required=False)
args = parser.parse_args()
# RAW_DATA_PATH = args.raw
# PROCESSED_DATA_PATH = args.processed
# JSON_F = args.json
# NEW_SHAPE = (int(args.shape[0]), int(args.shape[1]))
if __name__ == "__main__":
ans = "pineapple"
if os.path.exists("val.json") or os.path.exists("val.json"):
ans = input("YOU SURE??? ")
if (ans != "pineapple"):
exit()
parse_args()
process_images()