Advertisement
Guest User

Untitled

a guest
Jun 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.01 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import copy
  4. import os
  5. import math
  6. #from appscript import app
  7.  
  8. # Environment:
  9. # OS : Mac OS EL Capitan
  10. # python: 3.5
  11. # opencv: 2.4.13
  12.  
  13. # parameters
  14. cap_region_x_begin=0.5 # start point/total width
  15. cap_region_y_end=0.8 # start point/total width
  16. threshold = 45 # BINARY threshold
  17. blurValue = 41 # GaussianBlur parameter
  18. bgSubThreshold = 50
  19. learningRate = 0
  20.  
  21. # variables
  22. delay = 32
  23. delay1 = delay
  24. delay2 = delay
  25. delay3 = delay
  26. oncmd = './on.sh'
  27. offcmd = './off.sh'
  28. slidecmd25 = './slide25.sh'
  29. cmd = './meshtest'
  30. isBgCaptured = 0 # bool, whether the background captured
  31. on = delay
  32. off = delay
  33. dim = delay
  34. reset = 0
  35. triggerSwitch = False # if true, keyborad simulator works
  36.  
  37. def printThreshold(thr):
  38. print("! Changed threshold to "+str(thr))
  39.  
  40.  
  41. def removeBG(frame):
  42. fgmask = bgModel.apply(frame,learningRate=learningRate)
  43. # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
  44. # res = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
  45.  
  46. kernel = np.ones((3, 3), np.uint8)
  47. fgmask = cv2.erode(fgmask, kernel, iterations=1)
  48. res = cv2.bitwise_and(frame, frame, mask=fgmask)
  49. return res
  50.  
  51.  
  52. def calculateFingers(res,drawing): # -> finished bool, cnt: finger count
  53. # convexity defect
  54. hull = cv2.convexHull(res, returnPoints=False)
  55. if len(hull) > 3:
  56. defects = cv2.convexityDefects(res, hull)
  57. if type(defects) != type(None): # avoid crashing. (BUG not found)
  58.  
  59. cnt = 0
  60. for i in range(defects.shape[0]): # calculate the angle
  61. s, e, f, d = defects[i][0]
  62. start = tuple(res[s][0])
  63. end = tuple(res[e][0])
  64. far = tuple(res[f][0])
  65. a = math.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)
  66. b = math.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)
  67. c = math.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)
  68. angle = math.acos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) # cosine theorem
  69. if angle <= math.pi / 2: # angle less than 90 degree, treat as fingers
  70. cnt += 1
  71. cv2.circle(drawing, far, 8, [211, 84, 0], -1)
  72. return True, cnt
  73. return False, 0
  74.  
  75.  
  76. # Camera
  77. camera = cv2.VideoCapture(0)
  78. camera.set(10,200)
  79. cv2.namedWindow('trackbar')
  80. cv2.createTrackbar('trh1', 'trackbar', threshold, 100, printThreshold)
  81.  
  82.  
  83. while camera.isOpened():
  84. ret, frame = camera.read()
  85. threshold = cv2.getTrackbarPos('trh1', 'trackbar')
  86. frame = cv2.bilateralFilter(frame, 5, 50, 100) # smoothing filter
  87. frame = cv2.flip(frame, 1) # flip the frame horizontally
  88. cv2.rectangle(frame, (int(cap_region_x_begin * frame.shape[1]), 0),
  89. (frame.shape[1], int(cap_region_y_end * frame.shape[0])), (255, 0, 0), 2)
  90. cv2.imshow('original', frame)
  91.  
  92. # Main operation
  93. if isBgCaptured == 1: # this part wont run until background captured
  94. img = removeBG(frame)
  95. img = img[0:int(cap_region_y_end * frame.shape[0]),
  96. int(cap_region_x_begin * frame.shape[1]):frame.shape[1]] # clip the ROI
  97. cv2.imshow('mask', img)
  98.  
  99. # convert the image into binary image
  100. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  101. blur = cv2.GaussianBlur(gray, (blurValue, blurValue), 0)
  102. cv2.imshow('blur', blur)
  103. ret, thresh = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY)
  104. cv2.imshow('ori', thresh)
  105.  
  106.  
  107. # get the coutours
  108. thresh1 = copy.deepcopy(thresh)
  109. _,contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
  110. length = len(contours)
  111. maxArea = -1
  112. if length > 0:
  113. for i in range(length): # find the biggest contour (according to area)
  114. temp = contours[i]
  115. area = cv2.contourArea(temp)
  116. if area > maxArea:
  117. maxArea = area
  118. ci = i
  119.  
  120. res = contours[ci]
  121. hull = cv2.convexHull(res)
  122. drawing = np.zeros(img.shape, np.uint8)
  123. cv2.drawContours(drawing, [res], 0, (0, 255, 0), 2)
  124. cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 3)
  125.  
  126. isFinishCal,cnt = calculateFingers(res,drawing)
  127. if triggerSwitch is True:
  128. if isFinishCal is True:
  129. #print (cnt)
  130. if cnt == 4:#on
  131. if on < delay1:
  132. on = on + 1
  133. elif on >= delay1:
  134. #os.system(oncmd)
  135. print('on received')
  136. #os.system(cmd)
  137. on = 0
  138. if cnt == 2:#off
  139. if off < delay1:
  140. off = off + 1
  141. elif off >= delay1:
  142. #os.system(offcmd)
  143. print('off received')
  144. #os.system(cmd)
  145. off = 0
  146. if cnt == 1:
  147. if dim < delay2:
  148. dim = dim + 1
  149. elif dim >= delay2:
  150. #os.system(slidecmd25)
  151. print('dim received')
  152. dim = 0
  153. if cnt == 0:
  154. if reset < delay3:
  155. reset = reset + 1
  156. print(reset)
  157. elif reset >= delay3:
  158.  
  159. print( 'Background captured!')
  160. bgModel = None
  161. #triggerSwitch = False
  162. isBgCaptured = 0
  163. bgModel = cv2.createBackgroundSubtractorMOG2(0, bgSubThreshold)
  164. isBgCaptured = 1
  165. isFinishCal = True
  166. triggerSwitch = True
  167. reset = 0
  168. print(reset)
  169.  
  170. #app('System Events').keystroke(' ') # simulate pressing blank space
  171. elif True:
  172. reset = reset + 1
  173.  
  174. cv2.imshow('output', drawing)
  175.  
  176. # Keyboard OP
  177. k = cv2.waitKey(10)
  178. if k == 27: # press ESC to exit
  179. break
  180. elif k == ord('b'): # press 'b' to capture the background
  181. bgModel = cv2.createBackgroundSubtractorMOG2(0, bgSubThreshold)
  182. isBgCaptured = 1
  183. print( 'Background captured!')
  184. elif k == ord('r'): # press 'r' to reset the background
  185. bgModel = None
  186. triggerSwitch = False
  187. isBgCaptured = 0
  188. print ('Background reset!')
  189. elif k == ord('n'):
  190. triggerSwitch = True
  191. print ('Command mode on!')
  192. elif k == ord('m'):
  193. triggerSwitch = False
  194. print ('Command mode off!')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement