forked from UCSD-TIES/DVS-Python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEye.py
More file actions
392 lines (319 loc) · 13 KB
/
Eye.py
File metadata and controls
392 lines (319 loc) · 13 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
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
""" A class to perform actions on a eye. A eye can get its own pupil and
its own keypoints or sclera (depending on the algorithm)
"""
from Pupil import *
import cv2.cv as cv
import cv2
import numpy as np
from PIL import Image
import PIL.ImageOps
import math
from sys import maxint
DEBUG = False
########## Descriptive Variables for tweakable constants ###############
# Threshold parameters
LOWER_RED_RANGE = np.array((100,0,0))
UPPER_RED_RANGE = np.array((255,255,255))
# Erode and dilate parameters
ERODE_ITERATIONS = 1
DILATE_ITERATIONS = 1
# NOTE: tweaking any or all of these vars seems to only eliminate
# erroneous circles, not move the position of the circles detected
# Circle detection parameters
CIRCLE_RESOLUTION_RATIO = 1
# The minimum distance between circle centerpoints
CIRCLE_MIN_DISTANCE = 32
# I'm not exactly sure what the THRESHOLD ones do. See link for more info:
# http://www.adaptive-vision.com/en/technical_data/documentation/3.0/filters/FeatureDetection/cvHoughCircles.html
# You will need to look at the above url on archive.org. The actual site no longer has that page.
CIRCLE_THRESHOLD_1 = 10
# The accumulator threshold. The higher this is the less circles you get.
CIRCLE_THRESHOLD_2 = 2
CIRCLE_MIN_RADIUS = 10
CIRCLE_MAX_RADIUS = 500
# Circle drawing parameters
CIRCLE_COLOR = (0, 0, 255)
THICKNESS = 3
LINE_TYPE = 8
SHIFT = 0
# Smooth parameters
APERTURE_WIDTH = 9
APERTURE_HEIGHT = 9
# Canny parameters
CANNY_THRESHOLD_1 = 32
CANNY_THRESHOLD_2 = 2
############## Utility Methods ###################
def draw_circles(storage, output):
if DEBUG:
print "We are in draw_circles"
for i in range(0,len(storage)):
radius = storage[i, 2]
center = (storage[i, 0], storage[i, 1])
if DEBUG:
print "Radius: " + str(radius)
print "Center: " + str(center)
cv.Circle(output, center, radius, CIRCLE_COLOR,
THICKNESS, LINE_TYPE, SHIFT)
############## Eye Class ###################
class Eye:
""" This class has attributes :
cv2.cv.cvmat eyePhoto - a cropped photo of the eye
tuple eyeRegion - a region that represents the exact location of the eye
Pupil eyePupil - the eye's pupil
"""
def __init__(self, photo, region):
""" Initializes eyePhoto and eyeRegion and calls findPupil, findSclera, and
findKeypoints in an effort to populate the rest of the attributes
"""
if DEBUG:
print "We're here in eye's __init__"
print "And our region is: " + str(region)
print "This photo is a " + str(type(photo))
#photo.show()
# Initalize whole eye attributes to the values passed in
self.eyePhoto = photo
self.eyeRegion = region
# Initialize the rest of the attributes to None so that they exist
self.eyePupil = None
# Set the rest of the attributes by finding them
self.findPupil()
################# Utility Methods #########################################
def findPupil(self):
""" Detects a pupil in a photo of an eye and constructs a Pupil object
Uses opencv libarary methods to detect a pupil. Algorithm found here:
http://opencv-code.com/tutorials/pupil-detection-from-an-eye-image/
Algorithm Overview:
Load the source image.
Threshold based on a range of red.
Invert the photo.
Erode and dilate to reduce noise.
Find the contours.
Smooth to improve canny edge detection.
Canny edge detection.
Hough circle detection.
Choose the most central circle.
Then initializes eyePupil by constructing a new pupil object.
Returns false if no pupil is found
Args:
None
Return:
bool - True if there were no issues. False for any error
"""
# Load the source image and convert to cv mat
# eyePhoto is already stored as a mat. There is no need to convert
#eye = cv.GetMat(self.eyePhoto)
if DEBUG:
print "We're here in findPupil()"
print "EYE: " + str(self.eyePhoto)
print "The type of eyePhoto is: " + str(type(self.eyePhoto))
if not self.eyePhoto:
return False
# Convert to a numpy array
eyeArr = np.asarray(self.eyePhoto)
# Find the red in the photo
thresh = cv2.inRange(eyeArr,LOWER_RED_RANGE,UPPER_RED_RANGE)
if DEBUG:
cv.ShowImage("Binary", cv.fromarray(thresh))
cv.WaitKey(0)
cv.DestroyWindow("Binary")
# Invert the threshholded photo
rows = len(thresh)
for i in range(0,rows):
for j in range(0,len(thresh[i])):
thresh[i][j] = 255 - thresh[i][j]
if DEBUG:
cv.ShowImage("Inverted Thresh", cv.fromarray(thresh))
cv.WaitKey(0)
cv.DestroyWindow("Inverted Thresh")
# Erode and dilate the image to get rid of noise
erode = cv2.erode(thresh,None,iterations = ERODE_ITERATIONS)
if DEBUG:
cv.ShowImage("Erode", cv.fromarray(erode))
cv.WaitKey(0)
cv.DestroyWindow("Erode")
dilate = cv2.dilate(erode,None,iterations = DILATE_ITERATIONS)
if DEBUG:
cv.ShowImage("Dilate", cv.fromarray(dilate))
cv.WaitKey(0)
cv.DestroyWindow("Dilate")
# Find countours in the image
contours, hierarchy = cv2.findContours(dilate,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
# Draw the contours in white
cv2.drawContours(dilate,contours,-1,(255,255,255),-1)
if DEBUG:
cv.ShowImage("Contours", cv.fromarray(dilate))
cv.WaitKey(0)
cv.DestroyWindow("Contours")
smooth = cv.fromarray(dilate)
cv.Smooth(cv.fromarray(dilate),smooth,
cv.CV_GAUSSIAN,APERTURE_WIDTH,APERTURE_HEIGHT)
if DEBUG:
cv.ShowImage("Smooth", smooth)
cv.WaitKey(0)
cv.DestroyWindow("Smooth")
cv.Canny(smooth, smooth, CANNY_THRESHOLD_1, CANNY_THRESHOLD_2)
if DEBUG:
cv.ShowImage("Canny", smooth)
cv.WaitKey(0)
cv.DestroyWindow("Canny")
storage = cv.CreateMat((self.eyePhoto).width, 1, cv.CV_32FC3)
CIRCLE_MAX_RADIUS = self.eyePhoto.width
cv.HoughCircles(smooth, storage, cv.CV_HOUGH_GRADIENT, CIRCLE_RESOLUTION_RATIO, CIRCLE_MIN_DISTANCE,
CIRCLE_THRESHOLD_1, CIRCLE_THRESHOLD_2, CIRCLE_MIN_RADIUS, CIRCLE_MAX_RADIUS)
if DEBUG:
print "STORAGE: " + str(storage)
print np.asarray(storage)
finalCircle = None
if storage.rows != 0 and storage.cols != 0:
# NOTE: Each circle is stored as centerX, centerY, radius
storage = np.asarray(storage)
# Find the most centered circle
centerX = self.eyePhoto.width / 2
centerY = self.eyePhoto.height / 2
if DEBUG:
print "CenterX = " + str(centerX)
print "CenterY = " + str(centerY)
minDist = maxint
minCircleIndex = -1
for i in range(len(storage) - 1):
#radius = storage[i, 0, 2]
if DEBUG:
print "We're on circle elimination with i = " + str(i)
print "MinDist = " + str(minDist)
print "minCircleIndex = " + str(minCircleIndex)
x = storage[i, 0, 0]
y = storage[i, 0, 1]
dist = math.hypot(centerX - x, centerY - y)
if dist < minDist:
minDist = dist
minCircleIndex = i
if DEBUG:
#draw all the potential circles
draw_circles(np.array([[storage[i, 0, 0], storage[i, 0, 1],storage[i, 0, 2]]]),self.eyePhoto)
if DEBUG:
cv.ShowImage("Eye with all circles", self.eyePhoto)
cv.WaitKey(0)
cv.DestroyWindow("Eye with all circles")
if minCircleIndex != -1:
finalCircle = np.array([[storage[minCircleIndex, 0, 0], storage[minCircleIndex, 0, 1],storage[minCircleIndex, 0, 2]]])
if DEBUG:
print "Final Circle = " + str(finalCircle)
print "We're drawin some circles now"
draw_circles(finalCircle,self.eyePhoto)
if DEBUG:
cv.ShowImage("Eye with Circles",self.eyePhoto)
cv.WaitKey(0)
cv.DestroyWindow("Eye with Circles")
# Do the various setting that needs to be done for the class structure
if finalCircle != None:
# The pupil region is stored as a tuple : (centerXCoor, centerYCoor, radius)
region = (finalCircle[0,0], finalCircle[0,1], finalCircle[0,2])
self.setPupil(region)
return True
else:
#region = None
#self.setPupil(region)
# A pupil was not found
return False
def pupilRemove(self, region):
""" Crops the eye photo to show only the pupil
and then returns it.
Args:
tuple region - the coordinates of the pupil circle in
the form (centerX, centerY, radius)
Return:
cv2.cv.cvmat - the photo of just the pupil
"""
# TODO: Should these be rows - 1 and cols -1 to avoid going
# off the edge of the picture?
maxX = self.eyePhoto.rows
maxY = self.eyePhoto.cols
if DEBUG:
print "In pupilRemove starting boundary checking"
print "region: " + str(region)
# Converting to (topLeftX, topLeftY, width, height)
# and boundary checking
if region[0]-region[2] < 0:
topLeftX = 0
elif region[0]-region[2] > maxX:
topLeftX = maxX
else:
topLeftX = region[0]-region[2]
if region[1]-region[2] < 0:
topLeftY = 0
elif region[1]-region[2] > maxY:
topLeftY = maxY
else:
topLeftY = region[1]-region[2]
if region[2] <= 0:
width = 1
height = 1
elif topLeftX + (2 * region[2]) > maxX:
width = maxX - topLeftX
else:
width = 2 * region[2]
if topLeftY + (2 * region[2]) > maxY:
height = maxY - topLeftY
else:
height = 2 * region[2]
if DEBUG:
print "In pupilRemove ending boundary checking"
# These calculations will often give long (decimal) values. Pixel based coordinates
# must be ints so we cast them
crop = (np.int(topLeftX), np.int(topLeftY), np.int(width), np.int(height))
if DEBUG:
print "In pupilRemove. Crop is: " + str(crop)
print "Region passed to pupil remove: " + str(region)
print "And here's crop: " + str(crop)
print "Before crop we have type: " + str(type(self.eyePhoto))
print self.eyePhoto
print "The num of rows is " + str(self.eyePhoto.rows)
cv.ShowImage("We're cropping", self.eyePhoto)
cv.WaitKey(0)
cv.DestroyWindow("We're cropping")
'''
if crop[0] < 0:
crop[0] = 0
if crop[1] < 0:
crop[1] = 0
if crop[2] < 0:
crop[2] = abs(crop[2])
elif crop[2] = 0:
crop[2] = 1
else:
'''
if DEBUG:
print "Finally doing cv subrect"
pupil = cv.GetSubRect(self.eyePhoto, crop)
if DEBUG:
print "After crop we have type: " + str(type(pupil))
cv.ShowImage("Cropped", pupil)
cv.WaitKey(0)
cv.DestroyWindow("Cropped")
return pupil
#################### Getters ##################################
def getEyePhoto(self):
""" Returns a photo of the eye """
return self.eyePhoto
def getEyeRegion(self):
""" Returns a region representing the eye """
return self.eyeRegion
def getPupil(self):
""" Returns the Pupil object for this eye """
return self.eyePupil
#################### Setters ##################################
def setEyePhoto(self,photo):
""" Sets eyePhoto to the photo passed in as argument"""
self.eyePhoto = photo
def setEyeRegion(self,region):
""" Sets eyeRegion to the region passed in as argument"""
self.eyeRegion = region
def setPupil(self,region):
""" Sets eyePupil to a new Pupil object constructed from
the region passed in as argument"""
if DEBUG:
print "We're in set pupil just before pupilRemove and our region is: " + str(region)
pupilPhoto = self.pupilRemove(region)
if DEBUG:
print "We're in setPupil just before making a new pupil object"
self.eyePupil = Pupil(pupilPhoto, region)