forked from cpicanco/player_plugins
/
vis_circle_on_contours.py
348 lines (287 loc) · 14.2 KB
/
vis_circle_on_contours.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
# -*- coding: utf-8 -*-
'''
Pupil Player Third Party Plugins by cpicanco
Copyright (C) 2016 Rafael Picanço.
The present file is distributed under the terms of the GNU General Public License (GPL v3.0).
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
# Hack from Pupil (v0.3.7.4 .. v0.4x):
# - plugin.py
# - vis_circle.py
# - circle_detector.py
from player_methods import transparent_circle
from plugin import Plugin
import numpy as np
import cv2
from vcc_methods import ellipses_from_findContours, get_cluster_hierarchy, ellipse_to_contour
from vcc_methods import PolygonTestRC, get_codes, get_512_colors
#from vcc_methods import find_edges, draw_contours
from pyglui import ui
from methods import denormalize
import sys
# pt_codes references
_XY = 0
_CODE = 1
# channel constants
_CH_B = 0
_CH_G = 1
_CH_R = 2
_CH_0 = 3
class Vis_Circle_On_Contours(Plugin):
"""
if gaze_point is outside all contours:
draw "outside"
elif gaze_point is inside contour_a only:
draw circle a
elif gaze_point is inside contour_b only:
draw circle b
elif gaze_point is (inside contour_a) and (inside contour_b):
draw circle c
elif ...:
draw circle ...
"""
def __init__(self, g_pool,
radius=20,
color=(0.0, 0.0, 1.0, 0.8),
thickness=2,
fill=True,
epsilon=0.007,
show_edges=True,
dist_threshold=20,
delta_area_threshold=20,
threshold=255,
ellipse_size=2.):
super(Vis_Circle_On_Contours, self).__init__(g_pool)
self.order = .8
self.uniqueness = "unique"
# initialize empty menu
self.menu = None
# provided color, default red
self.color = color
self.r = self.color[_CH_R]
self.g = self.color[_CH_G]
self.b = self.color[_CH_B]
self.a = self.color[_CH_0]
# shared configs
self.radius = radius
self.thickness = thickness
self.fill = fill
# detector
self.candraw = False
self.expected_contours = 9
self.ellipse_size = ellipse_size
self.epsilon = epsilon
self.show_edges = show_edges
self.dist_threshold = dist_threshold
self.delta_area_threshold = delta_area_threshold
self.threshold = threshold
# hardcoded colors, but a gradient could be assigned somehow based on provided one
# self.colors = [ (self.b, self.g, self.r, self.a), # red
# (1, 0, 0, self.a), # blue
# (0, 1, 0, self.a), # green
# (1, 1, 0, self.a), # blue marine
# (0, 1, 1, self.a), # yellow
# (1, 0, 1, self.a), # purple
# (0, 0, 1, self.a), # red
# (1, 1, 1, self.a), # white
# (0.5, 0.5, 0.5, self.a)] # gray
# for 9 expected contours we need 512 color ]
self.colors = get_512_colors()
self.codes = list(get_codes('-+', self.expected_contours))
self.ColorDictionary = dict(zip(self.codes, self.colors))
# self.ColorDictionary['+1-2'] = (1, 0, 0, self.a) # blue
# self.ColorDictionary['-1+2'] = (0, 1, 0, self.a) # green
# overide some target colors
self.ColorDictionary['+1-2-3-4-5-6-7-8-9'] = (1, 0, 0, self.a) # blue
self.ColorDictionary['-1+2-3-4-5-6-7-8-9'] = (0, 1, 0, self.a) # green
self.ColorDictionary['-1-2+3-4-5-6-7-8-9'] = (1, 1, 0, self.a) # blue marine
self.ColorDictionary['-1-2-3+4-5-6-7-8-9'] = (0, 1, 1, self.a) # yellow
self.ColorDictionary['-1-2-3-4+5-6-7-8-9'] = (1, 0, 1, self.a) # purple
self.ColorDictionary['-1-2-3-4-5+6-7-8-9'] = (0, 0, 1, self.a) # red
self.ColorDictionary['-1-2-3-4-5-6+7-8-9'] = (1, 1, 1, self.a) # white
self.ColorDictionary['-1-2-3-4-5-6-7+8-9'] = (0.5, 0.5, 0.5, self.a) # gray
self.ColorDictionary['-1-2-3-4-5-6-7-8+9'] = (0.75, 0.2, 0.5, self.a) # ?
#self.ColorDictionary['+1'] = (230, 50, 230, 150)
#self.ColorDictionary['-1'] = (0, 0, 0, 255)
def recent_events(self,events):
frame = events['frame']
if frame is not None:
# get image from frame
img = frame.img
# set color1
color1 = map(lambda x: int(x * 255),(self.b, self.g, self.r, self.a))
# cv2.THRESH_BINARY
# cv2.THRESH_BINARY_INV
# cv2.THRESH_TRUNC
# find raw ellipses from cv2.findContours
# the less the difference between ellipse area and source contour area are,
# the better a fit between ellipse and source contour will be
# delta_area_threshold gives the maximum allowed difference
ellipses = []
merge = []
ellipses, merge, ellipses_contours = ellipses_from_findContours(img,cv2_thresh_mode=cv2.THRESH_BINARY,delta_area_threshold=self.delta_area_threshold,threshold=self.threshold)
# for contour in ellipses_contours:
# print(contour.shape)
# break
alfa = self.ellipse_size
# if self.show_edges:
# #frame.img = cv2.merge(merge)
# #cv2.drawContours(frame.img, contained_contours,-1, (0,0,255))
# if ellipses:
# for ellipse in ellipses:
# center = ( int(round( ellipse[0][0] )), int( round( ellipse[0][1] )))
# axes = ( int( round( ellipse[1][0]/alfa )), int( round( ellipse[1][1]/alfa )))
# angle = int( round(ellipse[2] ))
# cv2.ellipse(img, center, axes, angle, startAngle=0, endAngle=359, color=color1, thickness=1, lineType=8, shift= 0)
# we need denormalized points for point polygon tests
pts = [denormalize(pt['norm_pos'],frame.img.shape[:-1][::-1],flip_y=True) for pt in events.get('gaze_positions',[])]
contour_count = 0
if ellipses:
# get area of all ellipses
ellipses_temp = [e[1][0]/2. * e[1][1]/2. * np.pi for e in ellipses]
ellipses_temp.sort()
# take the highest area as reference
area_threshold = ellipses_temp[-1]
# filtering by proportional area
ellipses_temp = []
for e in ellipses:
a,b = e[1][0] / 2., e[1][1] / 2.
ellipse_area = np.pi * a * b
if (ellipse_area/area_threshold) < .10:
pass
else:
ellipses_temp.append(e)
# cluster_hierarchy is ordenated by appearence order, from top left screen
# it is a list of clustered ellipses
cluster_hierarchy = []
cluster_hierarchy = get_cluster_hierarchy(
ellipses=ellipses_temp,
dist_threshold=self.dist_threshold)
# total_stm is expected to be the number of stimuli on screen
# total_stm = len(cluster_hierarchy)
# we need contours for point polygon tests, not ellipses
stm_contours = []
# cluster_set is the ellipse set associated with each stimulus on screen
temp = list(cluster_hierarchy)
for cluster_set in temp:
#print(len(cluster_set))
if len(cluster_set) > 2:
cluster_hierarchy.append(cluster_hierarchy.pop(cluster_hierarchy.index(cluster_set)))
for cluster_set in cluster_hierarchy:
if len(cluster_set) > 0:
# use only the smallest (first) ellipse for reference
ellipse = cluster_set[0]
stm_contours.append(ellipse_to_contour(ellipse, alfa))
if self.show_edges:
# for ellipse in cluster_set:
center = ( int(round( ellipse[0][0] )), int( round( ellipse[0][1] )))
axes = ( int( round( ellipse[1][0]/alfa )), int( round( ellipse[1][1]/alfa )))
angle = int( round(ellipse[2] ))
cv2.ellipse(frame.img, center, axes, angle, startAngle=0, endAngle=359, color=color1, thickness=1, lineType=8, shift= 0)
#print(stm_contours)
# pt_codes is a list tuples:
# tuple((denormalized point as a float x, y coordenate), 'string code given by the PointPolygonTextEx function')
# ex.: tuple([x, y], '+1-2')
# if self.show_edges:
# for contour in stm_contours: # populated by ellipse2Poly
# print(np.array([[c] for c in contour]).shape)
# sys.exit("contour")
# (x, y, w, h) = cv2.boundingRect(np.array([[c] for c in contour]))
# cv2.rectangle(frame.img, (x, y), (x+w, y+h), (255,0,0), 2)
# box = np.int0(cv2.cv.BoxPoints(cv2.minAreaRect(np.array([[c] for c in contour]))))
# cv2.drawContours(frame.img,[box],0,color1,1)
pt_codes = []
for pt in pts:
contour_count = 0
counter_code = ''
for contour in stm_contours:
contour_count, counter_code = PolygonTestRC(contour, pt, contour_count, counter_code)
# a single code for a single point
pt_codes.append((pt, counter_code))
#print(pt_codes)
# transparent circle parameters
radius = self.radius
if self.fill:
thickness= -1
else:
thickness = self.thickness
# each code specifies the color of each point
# in accordance with the self.ColorDictionary
if contour_count > 0:
for pt in pt_codes:
try:
#print(pt)
color = self.ColorDictionary[pt[_CODE]]
except KeyError:
#print(e)
color = map(lambda x: int(x * 255),(0, 0, 0, self.a))
transparent_circle(
frame.img,
pt[_XY],
radius = int(radius/2),
color = color,
thickness = thickness )
# do not find any contour
else:
for pt in pts:
transparent_circle(
frame.img,
pt,
radius = radius,
color = map(lambda x: int(x * 255),self.colors[-1]),
thickness = thickness )
cv2.putText(frame.img, '?', (int(pt[0] -10),int(pt[1]) +10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 1, lineType = cv2.CV_AA )
def init_gui(self):
# initialize the menu
self.menu = ui.Scrolling_Menu('Gaze Circles on Contours')
# add menu to the window
self.g_pool.gui.append(self.menu)
self.menu.append(ui.Button('Close', self.unset_alive))
self.menu.append(ui.Info_Text('Circle Properties'))
self.menu.append(ui.Slider('radius',self,min=1,step=1,max=100,label='Radius'))
self.menu.append(ui.Slider('thickness',self,min=1,step=1,max=15,label='Stroke width'))
self.menu.append(ui.Switch('fill',self,label='Fill'))
self.menu.append(ui.Info_Text('Detector Properties'))
self.menu.append(ui.Slider('ellipse_size',self,min=0,step=0.001,max=4,label='Ellipse Size'))
self.menu.append(ui.Slider('epsilon',self,min=0,step=1,max=1000.,label='Epsilon'))
self.menu.append(ui.Slider('dist_threshold',self,min=1,step=1,max=20000,label='Distance threshold'))
self.menu.append(ui.Slider('delta_area_threshold',self,min=0,step=0.1,max=20,label='Area threshold'))
self.menu.append(ui.Slider('threshold',self,min=0,step=1,max=255,label='Threshold'))
self.menu.append(ui.Slider('expected_contours',self,min=1, step=1, max=32, label='Expected contours (not working yet)'))
self.menu.append(ui.Switch('show_edges',self,label='Show edges'))
color_menu = ui.Growing_Menu('Colors')
color_menu.collapsed = True
color_menu.append(ui.Info_Text('Outside Color'))
color_menu.append(ui.Slider('r',self,min=0.0,step=0.05,max=1.0,label='Red'))
color_menu.append(ui.Slider('g',self,min=0.0,step=0.05,max=1.0,label='Green'))
color_menu.append(ui.Slider('b',self,min=0.0,step=0.05,max=1.0,label='Blue'))
color_menu.append(ui.Slider('a',self,min=0.0,step=0.05,max=1.0,label='Alpha'))
self.menu.append(color_menu)
def deinit_gui(self):
if self.menu:
self.g_pool.gui.remove(self.menu)
self.menu = None
def unset_alive(self):
self.alive = False
def gl_display(self):
pass
def get_init_dict(self):
return {'radius':self.radius,
'color':self.color,
'thickness':self.thickness,
'fill':self.fill,
'epsilon':self.epsilon,
'show_edges':self.show_edges,
'dist_threshold':self.dist_threshold,
'delta_area_threshold':self.delta_area_threshold,
'threshold':self.threshold,
'ellipse_size':self.ellipse_size}
def clone(self):
return Vis_Circle_On_Contours(**self.get_init_dict())
def cleanup(self):
""" called when the plugin gets terminated.
This happens either voluntarily or forced.
if you have a GUI or glfw window destroy it here.
"""
self.deinit_gui()