树莓派之人脸识别与智能家居

访问【WRITE-BUG数字空间】_[内附完整源码和文档]

树莓派加上摄像头之后就可以拍照、录视频等各种功能了,这样做一个树莓派相机已经是非常简单的事情了。我们在这里做一个简单的人脸区域检测的功能实验,然后我们在下一个实验让树莓派来控制风扇转动。发现有人脸了,就开始转动风扇。这也是生活中的一个场景,当然加入实验3的温度检测根据温度和人脸一起决定是否吹风扇会更加精确化。

raspberry4
树莓派之人脸识别与智能家居

树莓派加上摄像头之后就可以拍照、录视频等各种功能了,这样做一个树莓派相机已经是非常简单的事情了。我们在这里做一个简单的人脸区域检测的功能实验,然后我们在下一个实验让树莓派来控制风扇转动。发现有人脸了,就开始转动风扇。这也是生活中的一个场景,当然加入实验 3 的温度检测根据温度和人脸一起决定是否吹风扇会更加精确化。

实验材料准备:原装树莓派 800 万像素 CSI 摄像头。

软件:rasbian 系统、opencv

安装必要的依赖库:

安装 OpenCV

sudo apt-get update

sudo apt-get upgrade

sudo apt-get install libopencv-dev

sudo apt-get install python-opencv

安装 PiCamera 库:

sudo apt-get install python-pip

sudo apt-get install python-dev

sudo pip install picamera

测试人脸识别代码
import io
import picamera
import cv2
import numpy

Create a memory stream so photos doesn’t need to be saved in a file

stream = io.BytesIO()

Get the picture (low resolution, so it should be quite fast)

Here you can also specify other parameters (e.g.:rotate the image)

with picamera.PiCamera() as camera:
camera.resolution = (320, 240)
camera.capture(stream, format=‘jpeg’)

Convert the picture into a numpy array

buff = numpy.fromstring(stream.getvalue(), dtype=numpy.uint8)

Now creates an OpenCV image

image = cv2.imdecode(buff, 1)

Load a cascade file for detecting faces

face_cascade = cv2.CascadeClassifier(‘/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml’)

Convert to grayscale

gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

Look for faces in the image using the loaded cascade file

faces = face_cascade.detectMultiScale(gray, 1.1, 5)
print “Found “+str(len(faces))+” face(s)”

Draw a rectangle around every found face

for (x,y,w,h) in faces:
cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,0),2)

Save the result image

cv2.imwrite(‘result.jpg’,image)
cv2.imshow(‘face_detect’, image)
c = cv2.waitKey(0)
cv2.destroyAllWindows()树莓派之人脸识别与智能家居_第1张图片
树莓派之人脸识别与智能家居_第2张图片
树莓派之人脸识别与智能家居_第3张图片
树莓派之人脸识别与智能家居_第4张图片

你可能感兴趣的:(智能家居,opencv,python)