Guest User

Untitled

a guest
Dec 1st, 2017
332
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 time
  4.  
  5. #Open Camera object
  6. cap = cv2.VideoCapture(0)
  7.  
  8. #Decrease frame size
  9. cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1000)
  10. cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 600)
  11.  
  12. def nothing(x):
  13. pass
  14.  
  15. # Function to find angle between two vectors
  16. def Angle(v1,v2):
  17. dot = np.dot(v1,v2)
  18. x_modulus = np.sqrt((v1*v1).sum())
  19. y_modulus = np.sqrt((v2*v2).sum())
  20. cos_angle = dot / x_modulus / y_modulus
  21. angle = np.degrees(np.arccos(cos_angle))
  22. return angle
  23.  
  24. # Function to find distance between two points in a list of lists
  25. def FindDistance(A,B):
  26. return np.sqrt(np.power((A[0][0]-B[0][0]),2) + np.power((A[0][1]-B[0][1]),2))
  27.  
  28.  
  29. # Creating a window for HSV track bars
  30. cv2.namedWindow('HSV_TrackBar')
  31.  
  32. # Starting with 100's to prevent error while masking
  33. h,s,v = 100,100,100
  34.  
  35. # Creating track bar
  36. cv2.createTrackbar('h', 'HSV_TrackBar',0,179,nothing)
  37. cv2.createTrackbar('s', 'HSV_TrackBar',0,255,nothing)
  38. cv2.createTrackbar('v', 'HSV_TrackBar',0,255,nothing)
  39.  
  40. while(1):
  41.  
  42. #Measure execution time
  43. start_time = time.time()
  44.  
  45. #Capture frames from the camera
  46. ret, frame = cap.read()
  47.  
  48. #Blur the image
  49. blur = cv2.blur(frame,(3,3))
  50.  
  51. #Convert to HSV color space
  52. hsv = cv2.cvtColor(blur,cv2.COLOR_BGR2HSV)
  53.  
  54. #Create a binary image with where white will be skin colors and rest is black
  55. mask2 = cv2.inRange(hsv,np.array([2,50,50]),np.array([15,255,255]))
  56.  
  57. #Kernel matrices for morphological transformation
  58. kernel_square = np.ones((11,11),np.uint8)
  59. kernel_ellipse= cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  60.  
  61. #Perform morphological transformations to filter out the background noise
  62. #Dilation increase skin color area
  63. #Erosion increase skin color area
  64. dilation = cv2.dilate(mask2,kernel_ellipse,iterations = 1)
  65. erosion = cv2.erode(dilation,kernel_square,iterations = 1)
  66. dilation2 = cv2.dilate(erosion,kernel_ellipse,iterations = 1)
  67. filtered = cv2.medianBlur(dilation2,5)
  68. kernel_ellipse= cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(8,8))
  69. dilation2 = cv2.dilate(filtered,kernel_ellipse,iterations = 1)
  70. kernel_ellipse= cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
  71. dilation3 = cv2.dilate(filtered,kernel_ellipse,iterations = 1)
  72. median = cv2.medianBlur(dilation2,5)
  73. ret,thresh = cv2.threshold(median,127,255,0)
  74.  
  75. #Find contours of the filtered frame
  76. contours, hierarchy, _= cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  77.  
  78. #Draw Contours
  79. #cv2.drawContours(frame, cnt, -1, (122,122,0), 3)
  80. #cv2.imshow('Dilation',median)
  81.  
  82. #Find Max contour area (Assume that hand is in the frame)
  83. max_area=100
  84. ci=0
  85. for i in range(len(contours)):
  86. cnt=contours[i]
  87. area = cv2.contourArea(cnt)
  88. if(area>max_area):
  89. max_area=area
  90. ci=i
  91.  
  92. #Largest area contour
  93. cnts = contours[ci]
  94.  
  95. #Find convex hull
  96. hull = cv2.convexHull(cnts)
  97.  
  98. #Find convex defects
  99. hull2 = cv2.convexHull(cnts,returnPoints = False)
  100. defects = cv2.convexityDefects(cnts,hull2)
  101.  
  102. #Get defect points and draw them in the original image
  103. FarDefect = []
  104. for i in range(defects.shape[0]):
  105. s,e,f,d = defects[i,0]
  106. start = tuple(cnts[s][0])
  107. end = tuple(cnts[e][0])
  108. far = tuple(cnts[f][0])
  109. FarDefect.append(far)
  110. cv2.line(frame,start,end,[0,255,0],1)
  111. cv2.circle(frame,far,10,[100,255,255],3)
  112.  
  113. #Find moments of the largest contour
  114. moments = cv2.moments(cnts)
  115.  
  116. #Central mass of first order moments
  117. if moments['m00']!=0:
  118. cx = int(moments['m10']/moments['m00']) # cx = M10/M00
  119. cy = int(moments['m01']/moments['m00']) # cy = M01/M00
  120. centerMass=(cx,cy)
  121.  
  122. #Draw center mass
  123. cv2.circle(frame,centerMass,7,[100,0,255],2)
  124. font = cv2.FONT_HERSHEY_SIMPLEX
  125. cv2.putText(frame,'Center',tuple(centerMass),font,2,(255,255,255),2)
  126.  
  127. #Distance from each finger defect(finger webbing) to the center mass
  128. distanceBetweenDefectsToCenter = []
  129. for i in range(0,len(FarDefect)):
  130. x = np.array(FarDefect[i])
  131. centerMass = np.array(centerMass)
  132. distance = np.sqrt(np.power(x[0]-centerMass[0],2)+np.power(x[1]-centerMass[1],2))
  133. distanceBetweenDefectsToCenter.append(distance)
  134.  
  135. #Get an average of three shortest distances from finger webbing to center mass
  136. sortedDefectsDistances = sorted(distanceBetweenDefectsToCenter)
  137. AverageDefectDistance = np.mean(sortedDefectsDistances[0:2])
  138.  
  139. #Get fingertip points from contour hull
  140. #If points are in proximity of 80 pixels, consider as a single point in the group
  141. finger = []
  142. for i in range(0,len(hull)-1):
  143. if (np.absolute(hull[i][0][0] - hull[i+1][0][0]) > 80) or ( np.absolute(hull[i][0][1] - hull[i+1][0][1]) > 80):
  144. if hull[i][0][1] <500 :
  145. finger.append(hull[i][0])
  146.  
  147. #The fingertip points are 5 hull points with largest y coordinates
  148. finger = sorted(finger,key=lambda x: x[1])
  149. fingers = finger[0:5]
  150.  
  151. #Calculate distance of each finger tip to the center mass
  152. fingerDistance = []
  153. for i in range(0,len(fingers)):
  154. distance = np.sqrt(np.power(fingers[i][0]-centerMass[0],2)+np.power(fingers[i][1]-centerMass[0],2))
  155. fingerDistance.append(distance)
  156.  
  157. #Finger is pointed/raised if the distance of between fingertip to the center mass is larger
  158. #than the distance of average finger webbing to center mass by 130 pixels
  159. result = 0
  160. for i in range(0,len(fingers)):
  161. if fingerDistance[i] > AverageDefectDistance+130:
  162. result = result +1
  163.  
  164. #Print number of pointed fingers
  165. cv2.putText(frame,str(result),(100,100),font,2,(255,255,255),2)
  166.  
  167. #show height raised fingers
  168. #cv2.putText(frame,'finger1',tuple(finger[0]),font,2,(255,255,255),2)
  169. #cv2.putText(frame,'finger2',tuple(finger[1]),font,2,(255,255,255),2)
  170. #cv2.putText(frame,'finger3',tuple(finger[2]),font,2,(255,255,255),2)
  171. #cv2.putText(frame,'finger4',tuple(finger[3]),font,2,(255,255,255),2)
  172. #cv2.putText(frame,'finger5',tuple(finger[4]),font,2,(255,255,255),2)
  173. #cv2.putText(frame,'finger6',tuple(finger[5]),font,2,(255,255,255),2)
  174. #cv2.putText(frame,'finger7',tuple(finger[6]),font,2,(255,255,255),2)
  175. #cv2.putText(frame,'finger8',tuple(finger[7]),font,2,(255,255,255),2)
  176.  
  177. #Print bounding rectangle
  178. x,y,w,h = cv2.boundingRect(cnts)
  179. img = cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
  180.  
  181. cv2.drawContours(frame,[hull],-1,(255,255,255),2)
  182.  
  183. ##### Show final image ########
  184. cv2.imshow('Dilation',frame)
  185. ###############################
  186.  
  187. #Print execution time
  188. #print time.time()-start_time
  189.  
  190. #close the output video by pressing 'ESC'
  191. k = cv2.waitKey(5) & 0xFF
  192. if k == 27:
  193. break
  194.  
  195.  
  196. cap.release()
  197. cv2.destroyAllWindows()
Advertisement
Add Comment
Please, Sign In to add comment