Python 제스처 인식 실현

7246 단어 python손짓식별
이것 은 github 의 소스 프로그램 을 참고 한 것 입 니 다.참고 소스:https://github.com/lzane/Fingers-Detection-using-OpenCV-and-Python
이 를 바탕 으로 약간의 수정 보충 을 한 후 손가락 끝의 검 측 을 실현 할 수 있 으 며 windows 시스템 에서 손가락 수 를 판단 하여 키보드 조작 을 모 의 할 수 있다.아래 는 직접 소스 프로그램 에 올 라 가 상세 한 주석 을 달 아 이해 하기 편리 하 다.
환경:python 3.6+opencv 3.4.0
코드 는 다음 과 같 습 니 다:

import cv2
import numpy as np
import copy
import math
import win32api
import win32con

#   
cap_region_x_begin = 0.5 #   /   
cap_region_y_end = 0.8
threshold = 60 #      
blurValue = 41 #       
bgSubThreshold = 50
learningRate = 0

#   
isBgCaptured = 0 #     ,        
triggerSwitch = False #     ,        


def printThreshold(thr):
  print("! Changed threshold to " + str(thr))


def removeBG(frame): #    
  fgmask = bgModel.apply(frame, learningRate=learningRate) #      
  kernel = np.ones((3, 3), np.uint8)
  fgmask = cv2.erode(fgmask, kernel, iterations=1) #              。
  res = cv2.bitwise_and(frame, frame, mask=fgmask) #          
  return res

#   /   
camera = cv2.VideoCapture(0)  #         ,     1        
camera.set(10, 200)  #      
cv2.namedWindow('trackbar') #      
cv2.resizeWindow("trackbar", 640, 200) #        
cv2.createTrackbar('threshold', 'trackbar', threshold, 100, printThreshold)
#createTrackbar Opencv  API,                     ,        ,         。

while camera.isOpened():
  ret, frame = camera.read()
  threshold = cv2.getTrackbarPos('threshold', 'trackbar') #           (       )
  # frame = cv2.cvtColor(frame,cv2.COLOR_RGB2YCrCb)
  frame = cv2.bilateralFilter(frame, 5, 50, 100) #     
  frame = cv2.flip(frame, 1) #    0: X   (    )    0: Y   (    )    0:  X   ,  Y   ,     180°
  cv2.rectangle(frame, (int(cap_region_x_begin * frame.shape[1]), 0),(frame.shape[1], int(cap_region_y_end * frame.shape[0])), (0, 0, 255), 2)
  #     frame.shape[0]  frame     frame.shape[1]  frame      :opencv    BGR  
  cv2.imshow('original', frame)  #             

  #    
  if isBgCaptured == 1: # isBgCaptured == 1         
    img = removeBG(frame) #    
    img = img[0:int(cap_region_y_end * frame.shape[0]),int(cap_region_x_begin * frame.shape[1]):frame.shape[1]] #           
    cv2.imshow('mask', img)

    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #               
    blur = cv2.GaussianBlur(gray, (blurValue, blurValue), 0) #     
    cv2.imshow('blur', blur)
    ret, thresh = cv2.threshold(blur, threshold, 255, cv2.THRESH_BINARY) #     
    cv2.imshow('binary', thresh)

    # get the coutours
    thresh1 = copy.deepcopy(thresh)
    _, contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    #       :   '_'      ,_            ,      。
    length = len(contours)
    maxArea = -1
    if length > 0:
      for i in range(length): #        (    )
        temp = contours[i]
        area = cv2.contourArea(temp) #        
        if area > maxArea:
          maxArea = area
          ci = i

      res = contours[ci] #         
      hull = cv2.convexHull(res) #    (      )   
      drawing = np.zeros(img.shape, np.uint8)
      cv2.drawContours(drawing, [res], 0, (0, 255, 0), 2)  #        
      cv2.drawContours(drawing, [hull], 0, (0, 0, 255), 3) #      

      moments = cv2.moments(res) #            
      center = (int(moments['m10'] / moments['m00']), int(moments['m01'] / moments['m00']))
      cv2.circle(drawing, center, 8, (0,0,255), -1)  #    

      fingerRes = []  #    
      max = 0; count = 0; notice = 0; cnt = 0
      for i in range(len(res)):
        temp = res[i]
        dist = (temp[0][0] -center[0])*(temp[0][0] -center[0]) + (temp[0][1] -center[1])*(temp[0][1] -center[1]) #            
        if dist > max:
          max = dist
          notice = i
        if dist != max:
          count = count + 1
          if count > 40:
            count = 0
            max = 0
            flag = False  #   
            if center[1] < res[notice][0][1]:  #        
              continue
            for j in range(len(fingerRes)): #       
              if abs(res[notice][0][0]-fingerRes[j][0]) < 20 :
                flag = True
                break
            if flag :
              continue
            fingerRes.append(res[notice][0])
            cv2.circle(drawing, tuple(res[notice][0]), 8 , (255, 0, 0), -1) #    
            cv2.line(drawing, center, tuple(res[notice][0]), (255, 0, 0), 2)
            cnt = cnt + 1

      cv2.imshow('output', drawing)
      print(cnt)
      if triggerSwitch is True:
        if cnt >= 3:
          print(cnt)
          # app('System Events').keystroke(' ') # simulate pressing blank space
          win32api.keybd_event(32, 0, 0, 0) #       32
          win32api.keybd_event(32, 0, win32con.KEYEVENTF_KEYUP, 0) #      

  #       
  k = cv2.waitKey(10)
  if k == 27: #   ESC  
    break
  elif k == ord('b'): #   'b'     
    bgModel = cv2.createBackgroundSubtractorMOG2(0, bgSubThreshold)
    #Opencv   BackgroundSubtractorMOG2        ,                       。
    isBgCaptured = 1
    print('!!!Background Captured!!!')
  elif k == ord('r'): #   'r'     
    bgModel = None
    triggerSwitch = False
    isBgCaptured = 0
    print('!!!Reset BackGround!!!')
  elif k == ord('n'):
    triggerSwitch = True
    print('!!!Trigger On!!!')
프로그램 실행:프로그램 을 실행 한 후 키보드 의 b 키 를 누 르 면 배경 을 포착 할 수 있 습 니 다.
실행 결과:

주:아 날로 그 클릭 스페이스 바 부분 은 보이 지 않 았 습 니 다.관심 있 는 것 은 시도 해 보 세 요.(n 키 를 누 르 면 키보드 조작 을 아 날로 그 할 수 있 습 니 다)
보:이 프로그램 은 빛 의 영향 을 많이 받 아 단조 로 운 배경 에서 만 효과 가 좋 습 니 다.
보충
나중에 이 프로그램 을 실행 할 때 오류 가 발생 했 습 니 다.다음 과 같 습 니 다.

원인:opencv 버 전의 원인 은 opencv 4.0.0 버 전 이후 find Contours 의 반환 값 은 contours,hierarchy 두 개의 매개 변수 만 있 고 더 이상 세 개의 매개 변수 가 없습니다!
해결 방법:
방법 1:
opencv 버 전 변경 
방법 2:
코드  _,contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)   ...로 바꾸다  contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)   되다
이상 은 Python 이 제스처 인식 을 실현 하 는 상세 한 내용 입 니 다.Python 제스처 인식 에 관 한 자 료 는 다른 관련 글 을 주목 하 세 요!

좋은 웹페이지 즐겨찾기