def count_fingers(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Otsu's thresholding after Gaussian filtering
img = cv2.GaussianBlur(img, (5, 5), 0)
ret, mask = cv2.threshold(img, 0, 255,
cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
cv2.imshow("Threshold", mask)
(_, cnts, _) = cv2.findContours(mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
list_far = []
list_end = []
if cnts:
areas = [cv2.contourArea(c) for c in cnts]
max_index = np.argmax(areas)
cnt = cnts[max_index]
M = cv2.moments(cnt)
cx = int(M['m10']/M['m00'])
cy = int(M['m01']/M['m00'])
hull1 = cv2.convexHull(cnt)
hull2 = cv2.convexHull(cnt, returnPoints=False)
try:
defects = cv2.convexityDefects(cnt, hull2)
except Exception, e:
defects = None
print e
counter = 0
if defects is not None:
for i in range(defects.shape[0]):
s, e, f, d = defects[i, 0]
# start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
if d < 20000:
continue
if far[1] >= (cy+40):
continue
diff1 = abs(end[0]-far[0])
if diff1 > 100:
continue
cv2.line(img, end, far, (0, 0, 0), 2, 8)
cv2.imshow("hand", img)
cv2.waitKey(1)
list_far.append(far)
list_end.append(end)
counter += 1
return mask, counter, hull1, (cx, cy), list_far, list_end
评论列表
文章目录