使用人脸识别控制舵机转动

洛洛格可猜格罗克 60cm2019-11-162167 次点击1 人感谢
import cv2
import numpy as np
import os
import time

# gpio函数
import RPi.GPIO as GPIO

# 定义舵机旋转角度关于pwm的函数
def tonum(num):
fm=10.0/180.0
num = num*fm + 2.5
num = int(num * 10)/10.0
return num

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)
p25 = GPIO.PWM(25, 50)
p25.start(tonum(90))
#########################################

recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

font = cv2.FONT_HERSHEY_SIMPLEX

# 创建id计数器
id = 0

# 名字对应id ==> Lan: id=1
names = ['None', 'Lan', 'Yi', 'FortheHorde', 'FortheAlliance', 'Soilder']

# 初始化并开启摄像头
cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video widht
cam.set(4, 480) # set video height

# 定义人脸识别的最小框
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)

angle = 90

while True:
ret, img =cam.read()
img = cv2.flip(img, -1) # Flip vertically
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
gray,
scaleFactor = 1.2,
minNeighbors = 5,
minSize = (int(minW), int(minH)),
)
######################################
for(x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
id, confidence = recognizer.predict(gray[y:y+h,x:x+w])

# Check if confidence is less them 100 ==> "0" is perfect match
if (confidence < 100):
id = names[id]
confidence = " {‌‌‌0}%".format(round(100 - confidence))

# 启动舵机,并判断是否为主人,检测到人脸打开门,再次检测到人脸则复原

if id in names:
if angle == 0:
p25.ChangeDutyCycle(tonum(90))
angle = 90
time.sleep(5)
elif angle == 90:
p25.ChangeDutyCycle(tonum(0))
angle = 0
time.sleep(5)
# 不是主人,则舵机不响应
else:
id = "unknown"
confidence = " {‌‌‌0}%".format(round(100 - confidence))
cam = cv2.VideoCapture(0)
cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)
id = 0
cv2.imshow('camera',img)

##########################
#num = int(input("num: "))
#if num < 0 or num > 180:
###########################

k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
if k == 27:
break

# 清除
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
/******************************分割线***************************************/
id所保存的数字分别对应着每个人的名字,之前录入的人脸在本地文件夹中,会从本地文件索引并匹配。以上为代码。
目的是在检测到人脸时让舵机发生转动,0°转为90°,90°转到0°。但是在加了sleep函数后,延迟结束的时候舵机依然会转动,而且输出的视频帧率会非常低,不知道该如何解决。
收藏 ♥ 感谢
Spoony 小组长 2019-11-16 
暂时不支持代码缩进,尴尬。。
洛洛格可猜格罗克 60cm 2019-11-16  ♥ 1
import cv2
import numpy as np
import os
import RPi.GPIO as GPIO
import time

def tonum(num):
fm=10.0/180.0
num = num*fm + 2.5
num = int(num * 10)/10.0
return num

GPIO.setmode(GPIO.BCM)
GPIO.setup(25, GPIO.OUT)
p25 = GPIO.PWM(25, 50)
p25.start(tonum(90))
#p25.ChangeDutyCycle(0)
time.sleep(0.02)


# 作用区
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

font = cv2.FONT_HERSHEY_SIMPLEX

#iniciate id counter
id = 0

# names related to ids: example ==> Marcelo: id=1, etc
names = ['None', 'Yan', 'Pan', 'Ilza', 'Z', 'W']

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
cam.set(3, 640) # set video widht
cam.set(4, 480) # set video height

# Define min window size to be recognized as a face
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)

# 角度
angle = 90

# 次数
index = 0
temp = 0

# shijian
t0 = time.time()
t1 = 0

while True:

ret, img =cam.read()
img = cv2.flip(img, -1) # Flip vertically
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
gray,
scaleFactor = 1.2,
minNeighbors = 5,
minSize = (int(minW), int(minH)),
)

for(x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
id, confidence = recognizer.predict(gray[y:y+h,x:x+w])

# Check if confidence is less them 100 ==> "0" is perfect match
if (confidence < 100):
id = names[id]
confidence = " {‌0}%".format(round(100 - confidence))

# 五秒为间隔
if ((t1 -t0) >= 5) | (y == 0) :
if id in names:
if angle == 90:
p25.ChangeDutyCycle(tonum(0))
time.sleep(0.02)
p25.ChangeDutyCycle(0)
time.sleep(0.2)
angle = 0
else:
p25.ChangeDutyCycle(tonum(90))
time.sleep(0.02)
p25.ChangeDutyCycle(0)
time.sleep(0.2)
angle = 90
index += 1

if index > temp:
t0 = time.time()
temp = index
t1 = round(time.time())

else:
id = "unknown"
confidence = " {‌0}%".format(round(100 - confidence))

cv2.putText(img, str(id), (x+5,y-5), font, 1, (255,255,255), 2)
cv2.putText(img, str(confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)

cv2.imshow('camera',img)

#p25.ChangeDutyCycle(tonum(num))
k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
if k == 27:
break

# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()
/****************************************************************/
这是后来我改的代码,加了时间间隔为5s左右,就是y -x,让舵机转一下,次数为index变量,但是后来舵机突然开始抖起来了。。。。。。。。。。感觉应该是对的。
SaSe 1m 2019-11-16  ♥ 2
建议:如果是硬件控制方面的问题,可以先单纯把硬件部分的程序拣出来测试。如果搞不定,可用其他库代替(如Gpiozero)。
wangxianyuan 10cm 2019-11-17 
看见这个变量就感觉是玩单片机的,p2^5,哈哈

登录注册 后可回复。