-
Notifications
You must be signed in to change notification settings - Fork 160
Expand file tree
/
Copy pathsort_of_clevr_generator.py
More file actions
279 lines (231 loc) · 8.92 KB
/
sort_of_clevr_generator.py
File metadata and controls
279 lines (231 loc) · 8.92 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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import cv2
import os
import numpy as np
import random
#import cPickle as pickle
import pickle
import warnings
import argparse
parser = argparse.ArgumentParser(description='Sort-of-CLEVR dataset generator')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--t-subtype', type=int, default=-1,
help='Force ternary questions to be of a given type')
args = parser.parse_args()
random.seed(args.seed)
np.random.seed(args.seed)
train_size = 9800
test_size = 200
img_size = 75
size = 5
question_size = 18 ## 2 x (6 for one-hot vector of color), 3 for question type, 3 for question subtype
q_type_idx = 12
sub_q_type_idx = 15
"""Answer : [yes, no, rectangle, circle, r, g, b, o, k, y]"""
nb_questions = 10
dirs = './data'
colors = [
(0,0,255),##r
(0,255,0),##g
(255,0,0),##b
(0,156,255),##o
(128,128,128),##k
(0,255,255)##y
]
try:
os.makedirs(dirs)
except:
print('directory {} already exists'.format(dirs))
def center_generate(objects):
while True:
pas = True
center = np.random.randint(0+size, img_size - size, 2)
if len(objects) > 0:
for name,c,shape in objects:
if ((center - c) ** 2).sum() < ((size * 2) ** 2):
pas = False
if pas:
return center
def build_dataset():
objects = []
img = np.ones((img_size,img_size,3)) * 255
for color_id,color in enumerate(colors):
center = center_generate(objects)
if random.random()<0.5:
start = (center[0]-size, center[1]-size)
end = (center[0]+size, center[1]+size)
cv2.rectangle(img, start, end, color, -1)
objects.append((color_id,center,'r'))
else:
center_ = (center[0], center[1])
cv2.circle(img, center_, size, color, -1)
objects.append((color_id,center,'c'))
ternary_questions = []
binary_questions = []
norel_questions = []
ternary_answers = []
binary_answers = []
norel_answers = []
"""Non-relational questions"""
for _ in range(nb_questions):
question = np.zeros((question_size))
color = random.randint(0,5)
question[color] = 1
question[q_type_idx] = 1
subtype = random.randint(0,2)
question[subtype+sub_q_type_idx] = 1
norel_questions.append(question)
"""Answer : [yes, no, rectangle, circle, r, g, b, o, k, y]"""
if subtype == 0:
"""query shape->rectangle/circle"""
if objects[color][2] == 'r':
answer = 2
else:
answer = 3
elif subtype == 1:
"""query horizontal position->yes/no"""
if objects[color][1][0] < img_size / 2:
answer = 0
else:
answer = 1
elif subtype == 2:
"""query vertical position->yes/no"""
if objects[color][1][1] < img_size / 2:
answer = 0
else:
answer = 1
norel_answers.append(answer)
"""Binary Relational questions"""
for _ in range(nb_questions):
question = np.zeros((question_size))
color = random.randint(0,5)
question[color] = 1
question[q_type_idx+1] = 1
subtype = random.randint(0,2)
question[subtype+sub_q_type_idx] = 1
binary_questions.append(question)
if subtype == 0:
"""closest-to->rectangle/circle"""
my_obj = objects[color][1]
dist_list = [((my_obj - obj[1]) ** 2).sum() for obj in objects]
dist_list[dist_list.index(0)] = 999
closest = dist_list.index(min(dist_list))
if objects[closest][2] == 'r':
answer = 2
else:
answer = 3
elif subtype == 1:
"""furthest-from->rectangle/circle"""
my_obj = objects[color][1]
dist_list = [((my_obj - obj[1]) ** 2).sum() for obj in objects]
furthest = dist_list.index(max(dist_list))
if objects[furthest][2] == 'r':
answer = 2
else:
answer = 3
elif subtype == 2:
"""count->1~6"""
my_obj = objects[color][2]
count = -1
for obj in objects:
if obj[2] == my_obj:
count +=1
answer = count+4
binary_answers.append(answer)
"""Ternary Relational questions"""
for _ in range(nb_questions):
question = np.zeros((question_size))
rnd_colors = np.random.permutation(np.arange(5))
# 1st object
color1 = rnd_colors[0]
question[color1] = 1
# 2nd object
color2 = rnd_colors[1]
question[6 + color2] = 1
question[q_type_idx + 2] = 1
if args.t_subtype >= 0 and args.t_subtype < 3:
subtype = args.t_subtype
else:
subtype = random.randint(0, 2)
question[subtype+sub_q_type_idx] = 1
ternary_questions.append(question)
# get coordiantes of object from question
A = objects[color1][1]
B = objects[color2][1]
if subtype == 0:
"""between->1~4"""
between_count = 0
# check is any objects lies inside the box
for other_obj in objects:
# skip object A and B
if (other_obj[0] == color1) or (other_obj[0] == color2):
continue
# Get x and y coordinate of third object
other_objx = other_obj[1][0]
other_objy = other_obj[1][1]
if (A[0] <= other_objx <= B[0] and A[1] <= other_objy <= B[1]) or \
(A[0] <= other_objx <= B[0] and B[1] <= other_objy <= A[1]) or \
(B[0] <= other_objx <= A[0] and B[1] <= other_objy <= A[1]) or \
(B[0] <= other_objx <= A[0] and A[1] <= other_objy <= B[1]):
between_count += 1
answer = between_count + 4
elif subtype == 1:
"""is-on-band->yes/no"""
grace_threshold = 12 # half of the size of objects
epsilon = 1e-10
m = (B[1]-A[1])/((B[0]-A[0]) + epsilon ) # add epsilon to prevent dividing by zero
c = A[1] - (m*A[0])
answer = 1 # default answer is 'no'
# check if any object lies on/close the line between object A and object B
for other_obj in objects:
# skip object A and B
if (other_obj[0] == color1) or (other_obj[0] == color2):
continue
other_obj_pos = other_obj[1]
# y = mx + c
y = (m*other_obj_pos[0]) + c
if (y - grace_threshold) <= other_obj_pos[1] <= (y + grace_threshold):
answer = 0
elif subtype == 2:
"""count-obtuse-triangles->1~6"""
obtuse_count = 0
# disable warnings
# the angle computation may fail if the points are on a line
warnings.filterwarnings("ignore")
for other_obj in objects:
# skip object A and B
if (other_obj[0] == color1) or (other_obj[0] == color2):
continue
# get position of 3rd object
C = other_obj[1]
# edge length
a = np.linalg.norm(B - C)
b = np.linalg.norm(C - A)
c = np.linalg.norm(A - B)
# angles by law of cosine
alpha = np.rad2deg(np.arccos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)))
beta = np.rad2deg(np.arccos((a ** 2 + c ** 2 - b ** 2) / (2 * a * c)))
gamma = np.rad2deg(np.arccos((a ** 2 + b ** 2 - c ** 2) / (2 * a * b)))
max_angle = max(alpha, beta, gamma)
if max_angle >= 90 and max_angle < 180:
obtuse_count += 1
warnings.filterwarnings("default")
answer = obtuse_count + 4
ternary_answers.append(answer)
ternary_relations = (ternary_questions, ternary_answers)
binary_relations = (binary_questions, binary_answers)
norelations = (norel_questions, norel_answers)
img = img/255.
dataset = (img, ternary_relations, binary_relations, norelations)
return dataset
print('building test datasets...')
test_datasets = [build_dataset() for _ in range(test_size)]
print('building train datasets...')
train_datasets = [build_dataset() for _ in range(train_size)]
#img_count = 0
#cv2.imwrite(os.path.join(dirs,'{}.png'.format(img_count)), cv2.resize(train_datasets[0][0]*255, (512,512)))
print('saving datasets...')
filename = os.path.join(dirs,'sort-of-clevr.pickle')
with open(filename, 'wb') as f:
pickle.dump((train_datasets, test_datasets), f)
print('datasets saved at {}'.format(filename))