-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConvexHullFingerCountRealTime.py
208 lines (151 loc) · 5.63 KB
/
ConvexHullFingerCountRealTime.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
import cv2
import numpy as np
def getRange(image):
avgH = np.average(image[:,:,0])
avgL = np.average(image[:,:,1])
avgS = np.average(image[:,:,2])
stdH = np.std(image[:,:,0])
stdL = np.std(image[:,:,1])
stdS = np.std(image[:,:,2])
return [avgH-2*stdH, avgL-2*stdL, avgS-2*stdS], [avgH+stdH, avgL+stdL, avgS+stdS]
def calcDistance(pt1, pt2):
x_diff = (pt1[0]-pt2[0])
y_diff = (pt1[1]-pt2[1])
return int(np.sqrt(x_diff**2+y_diff**2))
def getConvexHull(imgSrc, mask):
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) != 0:
c = max(contours, key=cv2.contourArea)
hull = cv2.convexHull(c, returnPoints=False)
hull[::-1].sort(axis=0)
if cv2.contourArea(c)/(imgSrc.shape[0]*imgSrc.shape[1]) >= 0.14:
# print('The area is:', cv2.contourArea(
# c)/(imgSrc.shape[0]*imgSrc.shape[1]))
defects = cv2.convexityDefects(c, hull)
reducedHullPoints = gethullClusters(hull, c)
reducedDefects = getDefectClusters(c, defects)
hullAreaFraction = getHullArea(
reducedHullPoints)/(imgSrc.shape[0]*imgSrc.shape[1])
# print('the convex hull area is', hullAreaFraction)
drawHullPoints(imgSrc, reducedHullPoints)
drawDefects(imgSrc, c, reducedDefects)
if hullAreaFraction<=0.19 and hullAreaFraction>=0.17:
return 1
elif hullAreaFraction<=0.17:
return 0
else:
return len(reducedDefects)+1
def getHullArea(hullPtList):
pt_list = []
for pt in hullPtList:
pt_list.append(np.asarray([pt]))
pt_list = np.asarray(pt_list)
area = cv2.contourArea(pt_list)
return area
def getDefectClusters(contour, defects):
clusterPts = []
for defect in defects:
dis = defect[0][3]
ptA = contour[defect[0][0]][0]
ptB = contour[defect[0][1]][0]
defectPt = contour[defect[0][2]][0]
sideA = np.linalg.norm(ptB-defectPt)
sideB = np.linalg.norm(ptA-defectPt)
defectSide = np.linalg.norm(ptB-ptA)
# finding the angle
alpha = np.arccos((np.square(sideA) + np.square(sideB) -
np.square(defectSide))/(2*sideA*sideB))
# converting it into degrees
alpha = alpha*(180/np.pi)
# print(':',alpha)
if dis >= 3600 and alpha < 90.0:
clusterPts.append(defect)
# print()
return clusterPts
pass
def getRequiredDefects(defects):
defectClusters = getDefectClusters(defects)
pass
def gethullClusters(hull, contour):
listPoints = []
for pointIdx in hull:
listPoints.append(list(contour[pointIdx[0]][0]))
return getClusters(listPoints)
def drawHullPoints(imgSrc, pointsList):
for pt in pointsList:
# print('::',pt)
imgSrc = cv2.circle(imgSrc, (pt[0], pt[1]), 13, (255, 0, 255), 1)
def getClusters(pointSet, thres=30):
clusterPts = []
for pt in pointSet:
if clusterPts == []:
clusterPts.append((pt[0], pt[1]))
else:
inserted = False
for clusterCenter in clusterPts:
if calcDistance(clusterCenter, ((pt[0], pt[1]))) <= thres:
clusterCenter = (
(clusterCenter[0]+pt[0])//2, (clusterCenter[1]+pt[1])//2)
inserted = True
break
if not inserted:
clusterPts.append((pt[0], pt[1]))
return clusterPts
def drawDefects(imgSrc, contour, ptsList):
for i in range(len(ptsList)):
s, e, f, d = ptsList[i][0]
start = tuple(contour[s][0])
end = tuple(contour[e][0])
far = tuple(contour[f][0])
cv2.line(imgSrc, start, end, [0, 255, 0], 2)
cv2.circle(imgSrc, far, 5, [0, 0, 255], 2)
cv2.circle(imgSrc, start, 5, [255, 255, 255], 2)
cv2.circle(imgSrc, end, 5, [255, 255, 255], 2)
def drawConvexHull(imgSrc, hull):
cv2.drawContours(imgSrc, [hull], -1, (255, 0, 0), 2)
font = cv2.FONT_HERSHEY_SIMPLEX
thickness =2
fontScale = 1
color = (0,0,0)
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if not cap:
print('Camera cant be opened')
exit()
writeImage = None
index=0
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 1)
frameHSV = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
cv2.rectangle(frame, (330 , 90), (620, 400), (255,255,255), 2)
roi = frame[92:388, 332:618]
# if registeredBackground:
roiHSV = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
# if lowerHSV == [] and upperHSV == []:
# print('Ha')
# lowerHSV, upperHSV = getRange(roiHSV)
mask = cv2.inRange(roiHSV, (36,46,141), (88, 166, 211))
mask = 255-mask
try:
detection = getConvexHull(roi, mask)
if detection !=None:
frame = cv2.putText(frame, str(detection), (350,117), font,
fontScale, color, thickness, cv2.LINE_AA)
except:
frame = cv2.putText(frame, 'No Detection ', (350,117), font,
fontScale, color, thickness, cv2.LINE_AA)
# print('===================================>Detected:', detection)
cv2.imshow('mask', mask)
cv2.imshow('my roi',roi)
cv2.imshow('frame', frame)
if writeImage:
cv2.imwrite('./res/'+str(index)+'.png', frame[92:388, 332:618])
pressedKey = cv2.waitKey(1) & 0xFF
index+=1
if pressedKey == ord('q'):
break
elif pressedKey == ord('w'):
writeImage = True
cap.release()
cv2.destroyAllWindows()