这是借鉴了github上的一个源程序,参考源:https://github.com/lzane/Fingers-Detection-using-OpenCV-and-Python
自己在这个基础上做了一点修改补充后,可以实现手指指尖的检测,并且可以在windows系统下通过判断手指数目,来模拟键盘操作。下面直接上源程序,并做了详细注释,方便理解。
环境:python3.6+opencv3.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(