你正在做的事情很好。
要仅修复鼠标移动,您可以从屏幕尺寸中减去 x,y 移动。但随后将其扩展到整个屏幕pyautogui.moveTo(x,y)会非常不准确且嘈杂。为了更流畅,您可以使用
pyautogui.moveRel(None, steps)
话虽如此,如果您首先使用面部级联,则很难移动面部以进行相应的鼠标运动。我想说,使用面部方向(例如向左或向右倾斜)会更好。
在下面的代码中,我使用眼级联进行左右运动。因此,稍微倾斜脸部就足以进行运动。我在 OpenCV 3.2 上工作,因此如果需要,请根据您的版本进行必要的更改。
CODE
import numpy as np
import cv2
import pyautogui
right = cv2.CascadeClassifier('haarcascade_righteye_2splits.xml')
left = cv2.CascadeClassifier('haarcascade_lefteye_2splits.xml')
smile = cv2.CascadeClassifier('haarcascade_smile.xml')
cam=cv2.VideoCapture(0)
blank=np.zeros((480,848,3),dtype=np.uint8) # Change this correctly to size of your image frame
fix=0
print "press y to set reference box for y motion" #set a reference initially for y motion
while(cam.isOpened()):
ret,img = cam.read()
r=0
l=0
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
r_eye= right.detectMultiScale(gray, 1.9, 9)
l_eye= left.detectMultiScale(gray, 1.9, 9) #Change these values according to face distance from screen
for (rx,ry,rw,rh) in r_eye:
cv2.rectangle(img,(rx,ry),(rx+rw,ry+rh),(255,255,0),2)
r_c=(rx+rw/2,ry+rh/2)
r=1
for (lx,ly,lw,lh) in l_eye:
cv2.rectangle(img,(lx,ly),(lx+lw,ly+lh),(0,255,255),2)
l_c=(lx+lw/2,ly+lh/2)
l=1
if(r*l):
if(l_c[0]-r_c[0]>50):
cv2.line(img,r_c,l_c,(0,0,255),4)
mid=((r_c[0]+l_c[0])/2,(r_c[1]+l_c[1])/2)
cv2.circle(img,mid,2,(85,25,100),2)
if(fix==1): # Change this part of code according to what you want
# for motion along y direction
if( mid[1]<one[1]):
pyautogui.moveRel(None, -15)
if(mid[1]>two[1]):
pyautogui.moveRel(None, 15)
if(cv2.waitKey(1))== ord('y'):
blank=np.zeros_like(img)
one=(mid[0]-60,r_c[1]-7) # Change the Value 60,7 to change box dimentions
two=(mid[0]+60,l_c[1]+7) # Change the Value 60,7 to change box dimentions
cv2.rectangle(blank,one,two,(50,95,100),2)
fix=1
elif(r) : pyautogui.moveRel(-30, None) # Change the Value and Sign to change speed and direction
elif (l): pyautogui.moveRel(30, None) # Change the Value and Sign to change speed and direction
img=cv2.bitwise_or(img,blank)
cv2.imshow('img',img)
if(cv2.waitKey(1))==27:break
cv2.destroyAllWindows()
代码中需要按y设置一个y轴运动的参考框。开箱即用,双眼将进行运动。
我们可以为鼠标单击添加微笑级联,但目前这有点不准确且缓慢。需要找出更好的选择,例如点击眼睛或其他东西。
这是让事情正常运行的非常基本的代码。在神经网络中标记面部表情可能会好得多,但速度也是一个因素。