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 제스처 인식 에 관 한 자 료 는 다른 관련 글 을 주목 하 세 요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
로마 숫자를 정수로 또는 그 반대로 변환그 중 하나는 로마 숫자를 정수로 변환하는 함수를 만드는 것이었고 두 번째는 그 반대를 수행하는 함수를 만드는 것이었습니다. 문자만 포함합니다'I', 'V', 'X', 'L', 'C', 'D', 'M' ; 문자열이 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.