-
Notifications
You must be signed in to change notification settings - Fork 0
/
sort_of_clevr_generator.py
365 lines (286 loc) · 13.7 KB
/
sort_of_clevr_generator.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
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
import cv2
import os
import numpy as np
import random
import pickle
import argparse
parser = argparse.ArgumentParser(description='PyTorch Relations-from-Stream sort-of-CLVR dataset builder')
parser.add_argument('--dir', type=str, default='./data',
help='Directory in which to store the dataset')
parser.add_argument('--seed', type=int, default=10, metavar='S',
help='random seed (default: 10)')
parser.add_argument('--add_tricky', action='store_true', default=True,
help='Add the tricky cases')
parser.add_argument('-f', type=str, default='', help='Fake for Jupyter notebook import')
args = parser.parse_args()
dirs = args.dir
random.seed(args.seed)
np.random.seed(args.seed)
train_size, test_size = 9800, 200
img_size, size = 75, 5 # Size of img total, radius of sprite
question_size = 11 ##6 for one-hot vector of color, 2 for question type, 3 for question subtype
"""Question:[r, g, b, o, k, y, q1, q2, s1, s2, s3]"""
# answer is returned as an integer index within the following:
"""Answer : [yes, no, rectangle, circle, r, g, b, o, k, y]"""
"""Answer : [yes, no, rectangle, circle, 1, 2, 3, 4, 5, 6]""" # for counting
nb_questions = 10 # questions generated about each image
colors = [
(0,0,255), ##r red
(0,255,0), ##g green
(255,0,0), ##b blue
(0,156,255), ##o orange
(128,128,128), ##k grey
(0,255,255) ##y yellow
]
colors_str = 'red green blue orange grey yellow'.split()
def center_generate(objects):
# Generates a set of centers that do not overlap
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
image_number=0
def build_dataset(nb_questions=nb_questions):
global image_number
image_number+=1
print("image %6d" % (image_number,))
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'))
"""Non-relational questions"""
norel_questions, norel_answers = [], []
for i in range(nb_questions):
question = np.zeros((question_size))
color = random.randint(0,5)
question[color] = 1
question[6] = 1
subtype = random.randint(0,2)
question[subtype+8] = 1
norel_questions.append(question)
"""Answer : [yes, no, rectangle, circle, r, g, b, o, k, y]"""
if subtype == 0:
"""query shape->rectangle/circle"""
answer = 2 if objects[color][2] == 'r' else 3
elif subtype == 1:
"""query horizontal position->yes/no"""
answer = 0 if objects[color][1][0] < img_size/2 else 1
elif subtype == 2:
"""query vertical position->yes/no"""
answer = 0 if objects[color][1][1] < img_size/2 else 1
norel_answers.append(answer)
"""Relational questions"""
birel_questions, birel_answers = [], []
for i in range(nb_questions):
question = np.zeros((question_size))
color = random.randint(0,5)
question[color] = 1
question[7] = 1
subtype = random.randint(0,2)
question[subtype+8] = 1
birel_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))
answer = 2 if objects[closest][2] == 'r' else 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))
answer = 2 if objects[furthest][2] == 'r' else 3
elif subtype == 2:
"""count->1~6"""
"""Answer : [yes, no, rectangle, circle, 1, 2, 3, 4, 5, 6]"""
my_obj = objects[color][2]
count = -1
for obj in objects:
if obj[2] == my_obj:
count +=1
answer = count+4
birel_answers.append(answer)
"""Tricky questions"""
trirel_questions, trirel_answers = [], []
for i in range(nb_questions):
question = np.zeros((question_size))
question[6] = 1 # Both 6 and 7 set
question[7] = 1 # Both 6 and 7 set
subtype = random.randint(0,2)
#subtype=2 # Fix for now
question[subtype+8] = 1
trirel_questions.append(question)
if subtype == 0:
"""How many things are colinear with 2 chosen colours?"""
min_dist = size*5.
while True:
arr = sorted( random.sample(range(0, 6), 2) ) # pick 2 distinct colours, sorted
arr_obj = [ objects[i][1] for i in arr ]
#print("Point 1 : ", colors_str[ objects[ arr[0] ][0] ])
#print("Point 2 : ", colors_str[ objects[ arr[1] ][0] ])
# Want distant to that line to be <shape_size
s1 = arr_obj[1]-arr_obj[0]
#s1_norm = s1 / np.linalg.norm( s1 )
if np.linalg.norm(s1)>min_dist:
break
min_dist *= 0.95 # Make sure it will happen eventually
print("min_dist -> ", min_dist)
for i in arr:question[i]=1
count = -2 # Exclude original things (so min==0) 0=='circle'
for obj in objects:
if np.linalg.norm( np.cross(arr_obj[1]-obj[1], s1) ) / np.linalg.norm( s1 ) < size*2.:
#print("Colinear : ", colors_str[ obj[0] ])
count +=1
answer = count+3
elif subtype == 1:
"""How many things are eqidistant from 2 chosen colours?"""
min_dist = size*5.
while True:
arr = sorted( random.sample(range(0, 6), 2) ) # pick 2 distinct colours, sorted
arr_obj = [ objects[i][1] for i in arr ]
s1 = arr_obj[1] - arr_obj[0]
if np.linalg.norm(s1)>min_dist:
break
min_dist *= 0.95 # Make sure it will happen eventually
print("min_dist -> ", min_dist)
for i in arr:question[i]=1
unit_v = s1 / np.linalg.norm(s1)
count = 0 # (min==0) 0=='circle'
for obj in objects:
proj = arr_obj[1] + np.dot( unit_v, obj[1]-arr_obj[1]) * unit_v
#d1, d2 = np.linalg.norm( arr_obj[1]-obj[1] ), np.linalg.norm( arr_obj[0]-obj[1] )
d1, d2 = np.linalg.norm( arr_obj[1]-proj ), np.linalg.norm( arr_obj[0]-proj )
#print(" Test %10s : %3.0f -%3.0f = %3.0f vs %3.0f" % ( colors_str[ obj[0] ], d1, d2, np.abs(d1-d2), size*2.,))
if np.abs( d1-d2 ) < size*2.:
#print("Equidistant : ", colors_str[ obj[0] ])
count +=1
answer = count+3
elif subtype == 2:
"""How many things are on clockwise side of line joining 2 chosen colours?"""
min_dist = size*5.
while True:
arr = sorted( random.sample(range(0, 6), 2) ) # pick 2 distinct colours, sorted
arr_obj = [ objects[i][1] for i in arr ]
s1 = arr_obj[1]-arr_obj[0]
if np.linalg.norm(s1)>min_dist:
break
min_dist *= 0.95 # Make sure it will happen eventually
print("min_dist -> ", min_dist)
for i in arr:question[i]=1
count = 0 # (min==0) 0=='circle'
for obj in objects:
if np.cross(arr_obj[1]-obj[1], s1) >0.0:
#print("Clockwise : ", colors_str[ obj[0] ])
count +=1
answer = count+3
elif subtype == -1:
"""three colours enclose 'big' area -> yes/no"""
arr = sorted( random.sample(range(0, 6), 3) ) # pick 3 distinct colours, sorted
arr_obj = [ objects[i][1] for i in arr ]
s1, s2 = arr_obj[1]-arr_obj[0], arr_obj[2]-arr_obj[0]
area = 0.5 * np.cross( s1, s2 )
#print("area = ", area)
#normed = np.abs(area) / np.linalg.norm(s1) / np.linalg.norm(s2)
#print("normed = ", normed)
for i in arr:question[i]=1
answer = 0 if np.abs(area)>img_size*img_size/15. else 1
elif subtype == -1:
"""three colours are ordered clockwise -> yes/no"""
iter=0
while True:
#print("clockwise")
arr = sorted( random.sample(range(0, 6), 3) ) # pick 3 distinct colours, sorted
arr_obj = [ objects[i][1] for i in arr ]
#for i in [0,1,2]:print( arr_obj[i] )
# Enclosed area : (http://code.activestate.com/recipes/576896-3-point-area-finder/)
# sign => direction of 'winding'
area = 0.5 * np.cross( arr_obj[1]-arr_obj[0], arr_obj[2]-arr_obj[0] )
#print("area=", area)
if np.abs(area)>img_size*img_size/(10.+iter): # Should not be near co-linear (make it easier...)
for i in arr:question[i]=1
answer = 0 if area>0. else 1
break
iter += 1
elif subtype == -3:
"""What shape is the most isolated -> rectangle/circle"""
iter=0
while True:
if iter>10: print("most isolated %d" % iter)
arr = sorted( random.sample(range(0, 6), 3) ) # pick 3 distinct colours, sorted
arr_obj = [ objects[i][1] for i in arr ]
#for i in [0,1,2]:print( arr_obj[i] )
(l0, l1, l2) = [ np.linalg.norm( arr_obj[i] - arr_obj[ (i+1) % 3 ] ) for i in [0,1,2] ]
#print( "(l0, l1, l2)", (l0, l1, l2))
a = 1. + 1./(1.+iter/10.) # Descends slowly to 1...
furthest=-1
# test : both connected > alpha*opposite
if l2>l1*a and l0>l1*a: furthest=0
if l0>l2*a and l1>l2*a: furthest=1
if l1>l0*a and l2>l0*a: furthest=2
if furthest>=0:
for i in arr:question[i]=1
furthest_o = objects[arr[furthest]]
#print( "objects[arr[furthest]]", colors[furthest_o[0]], furthest_o[2] )
answer = 2 if furthest_o[2] == 'r' else 3
break
iter += 1
trirel_answers.append(answer)
norelations = (norel_questions, norel_answers)
birelations = (birel_questions, birel_answers)
trirelations = (trirel_questions, trirel_answers)
img = img/255.
dataset = (img, norelations, birelations, trirelations)
return dataset
#"""Question:[r, g, b, o, k, y, q1, q2, s1, s2, s3]"""
# Answer is returned as an integer index within the following:
#"""Answer : [yes, no, rectangle, circle, r, g, b, o, k, y]"""
#"""Answer : [yes, no, rectangle, circle, 1, 2, 3, 4, 5, 6]""" # for counting
## Ideas for tougher questions :
# How many things are colinear with 2 chosen colours?
# How many things are eqidistant from 2 chosen colours?
# How many things are on clockwise side of line joining 2 chosen colours?
# For the 3 highlighted colours, are they a 'large' triangle (area)
# For the 3 highlighted colours, are they clockwise (in order)
# For the 3 highlighted colours, what is shape of most isolated one?
# For the 3 highlighted colours, do they enclose another object
# For the 3 highlighted colours, are they in a row? (any orientation - tricky to define)
# For the 2 highlighted colours, what shape is between them?
## Not so tough
# For the n highlighted colours, are they all the same shape?
# But two different => no. So don't have to think more than two deep...
# For the 3 highlighted colours, are they in a row? (horizontal or vertical)
# Can cheat by counting total in a row or column if orientated
## alternative within Jupyter notebook :
# import sort_of_clevr_generator
if __name__ == "__main__":
try:
os.makedirs(dirs)
except:
print('directory {} already exists'.format(dirs))
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))