树莓派实现人脸识别迎宾功能

实现逻辑

利用opencv的检测人脸功能,检测到人脸后播放mp3

实现步骤

1.安装opencv调用摄像头进行人脸识别

1
2
sudo apt-get install libopencv-dev
sudo apt-get install python-opencv

2.判断是否存在人脸,然后使用pygame来播放mp3

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import cv2
import time
from pygame import mixer
mixer.init()
mixer.music.load('/home/pi/xx.mp3')

cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)
face_cascade = cv2.CascadeClassifier(r'haarcascade_frontalface_default.xml')

while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
#gray = frame
faces = face_cascade.detectMultiScale(gray, scaleFactor = 1.15, minNeighbors = 5, minSize = (5, 5))
if len(faces):
print('y1es')
mixer.music.play()
time.sleep(5)
mixer.music.stop()
else:
print('n1o')
for(x, y, w, h) in faces:
cv2.rectangle(gray, (x, y), (x + w, y + h), (0,0, 255), 2)
cv2.imshow('Face Recognition', gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#time.sleep( 3 )
cap.release()
cv2.destroyAllWindows()

参考资料 https://www.jianshu.com/p/56929416b4a1