|
| 1 | +import cv2 |
| 2 | +import numpy as np |
| 3 | +import pickle |
| 4 | + |
| 5 | +def build_squares(img): |
| 6 | + x, y, w, h = 420, 140, 10, 10 |
| 7 | + d = 10 |
| 8 | + imgCrop = None |
| 9 | + crop = None |
| 10 | + for i in range(10): |
| 11 | + for j in range(5): |
| 12 | + if np.any(imgCrop == None): |
| 13 | + imgCrop = img[y:y+h, x:x+w] |
| 14 | + else: |
| 15 | + imgCrop = np.hstack((imgCrop, img[y:y+h, x:x+w])) |
| 16 | + #print(imgCrop.shape) |
| 17 | + cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 1) |
| 18 | + x+=w+d |
| 19 | + if np.any(crop == None): |
| 20 | + crop = imgCrop |
| 21 | + else: |
| 22 | + crop = np.vstack((crop, imgCrop)) |
| 23 | + imgCrop = None |
| 24 | + x = 420 |
| 25 | + y+=h+d |
| 26 | + return crop |
| 27 | + |
| 28 | +def get_hand_hist(): |
| 29 | + cam = cv2.VideoCapture(1) |
| 30 | + if cam.read()[0]==False: |
| 31 | + cam = cv2.VideoCapture(0) |
| 32 | + x, y, w, h = 300, 100, 300, 300 |
| 33 | + flagPressedC, flagPressedS = False, False |
| 34 | + imgCrop = None |
| 35 | + while True: |
| 36 | + img = cam.read()[1] |
| 37 | + img = cv2.flip(img, 1) |
| 38 | + img = cv2.resize(img, (640, 480)) |
| 39 | + hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) |
| 40 | + |
| 41 | + keypress = cv2.waitKey(1) |
| 42 | + if keypress == ord('c'): |
| 43 | + hsvCrop = cv2.cvtColor(imgCrop, cv2.COLOR_BGR2HSV) |
| 44 | + flagPressedC = True |
| 45 | + hist = cv2.calcHist([hsvCrop], [0, 1], None, [180, 256], [0, 180, 0, 256]) |
| 46 | + cv2.normalize(hist, hist, 0, 255, cv2.NORM_MINMAX) |
| 47 | + elif keypress == ord('s'): |
| 48 | + flagPressedS = True |
| 49 | + break |
| 50 | + if flagPressedC: |
| 51 | + dst = cv2.calcBackProject([hsv], [0, 1], hist, [0, 180, 0, 256], 1) |
| 52 | + dst1 = dst.copy() |
| 53 | + disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(10,10)) |
| 54 | + cv2.filter2D(dst,-1,disc,dst) |
| 55 | + blur = cv2.GaussianBlur(dst, (11,11), 0) |
| 56 | + blur = cv2.medianBlur(blur, 15) |
| 57 | + ret,thresh = cv2.threshold(blur,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) |
| 58 | + thresh = cv2.merge((thresh,thresh,thresh)) |
| 59 | + #cv2.imshow("res", res) |
| 60 | + cv2.imshow("Thresh", thresh) |
| 61 | + if not flagPressedS: |
| 62 | + imgCrop = build_squares(img) |
| 63 | + #cv2.rectangle(img, (x,y), (x+w, y+h), (0,255,0), 2) |
| 64 | + cv2.imshow("Set hand histogram", img) |
| 65 | + cam.release() |
| 66 | + cv2.destroyAllWindows() |
| 67 | + with open("hist", "wb") as f: |
| 68 | + pickle.dump(hist, f) |
| 69 | + |
| 70 | + |
| 71 | +get_hand_hist() |
0 commit comments