-
Notifications
You must be signed in to change notification settings - Fork 75
/
HandHisto.py
70 lines (65 loc) · 1.85 KB
/
HandHisto.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
import cv2
import numpy as np
import pickle
def build_squares(img):
x, y, w, h = 420, 140, 10, 10
d = 10
imgCrop = None
crop = None
for i in range(10):
for j in range(5):
if np.any(imgCrop == None):
imgCrop = img[y:y+h, x:x+w]
else:
imgCrop = np.hstack((imgCrop, img[y:y+h, x:x+w]))
#print(imgCrop.shape)
cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 1)
x+=w+d
if np.any(crop == None):
crop = imgCrop
else:
crop = np.vstack((crop, imgCrop))
imgCrop = None
x = 420
y+=h+d
return crop
def get_hand_hist():
cam = cv2.VideoCapture(1)
if cam.read()[0]==False:
cam = cv2.VideoCapture(0)
x, y, w, h = 300, 100, 300, 300
flagPressedC, flagPressedS = False, False
imgCrop = None
while True:
img = cam.read()[1]
img = cv2.flip(img, 1)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
keypress = cv2.waitKey(1)
if keypress == ord('c'):
hsvCrop = cv2.cvtColor(imgCrop, cv2.COLOR_BGR2HSV)
flagPressedC = True
hist = cv2.calcHist([hsvCrop], [0, 1], None, [180, 256], [0, 180, 0, 256])
cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX)
elif keypress == ord('s'):
flagPressedS = True
break
if flagPressedC:
dst = cv2.calcBackProject([hsv], [0, 1], hist, [0, 180, 0, 256], 1)
dst1 = dst.copy()
disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10))
cv2.filter2D(dst,-1,disc,dst)
blur = cv2.GaussianBlur(dst, (11,11), 0)
blur = cv2.medianBlur(blur, 15)
ret,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thresh = cv2.merge((thresh,thresh,thresh))
#cv2.imshow("res", res)
cv2.imshow("Thresh", thresh)
if not flagPressedS:
imgCrop = build_squares(img)
#cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2)
cv2.imshow("Set hand histogram", img)
cam.release()
cv2.destroyAllWindows()
with open("hist", "wb") as f:
pickle.dump(hist, f)
get_hand_hist()