树莓派配置摄像头
sudo apt-get install python-opencv
sudo apt-get install fswebcam
配置摄像头
sudo nano /etc/modules
查看树莓派CPU型号
cat /proc/cpuinfo
cpu型号为bcm2711
添加
bcm2711-v4l2
vcgencmd get_camera
配置展示窗口
export DISPLAY=:0.0
实时人脸检测代码
#coding=utf-8
#face-detection-camera.py
import cv2 as cv
import numpy as np
print('开始人脸摄像头实时监测')
print('press "q" to exit ')
#载入模型文件和权重文件
net = cv.dnn.readNet('face-detection-adas-0001.xml','face-detection-adas-0001.bin')
#specify target device
net.setPreferableTarget(cv.dnn.DNN_TARGET_MYRIAD)
#从摄像头中读取图像帧
cap = cv.VideoCapture(0)
while(1):
#获取一帧图像
ret,frame=cap.read()
#prepare input blob and perform an inference
frame = cv.resize(frame,(480,320),interpolation=cv.INTER_CUBIC)
blob = cv.dnn.blobFromImage(frame,size=(672,384),ddepth=cv.CV_8U)
net.setInput(blob)
out=net.forward()
#绘制人脸框
for detection in out.reshape(-1,7):
confidence = float(detection[2])
#获取左上角图片的坐标
xmin=int(detection[3]*frame.shape[1])
ymin=int(detection[4]*frame.shape[0])
#获取右下角图片的坐标
xmax=int(detection[5]*frame.shape[1])
ymax=int(detection[6]*frame.shape[0])
if confidence>0.5:
cv.rectangle(frame,(xmin,ymin),(xmax,ymax),color=(0,255,0))
#展示图像
cv.imshow("capture",frame)
if cv.waitKey(1)&0xFF==ord('q'):
#每一毫秒监听一次键盘的动作,按q键结束,并保存图片
cv.imwrite('out_cam.png',frame)
print("save one image done!")
break
#关闭摄像头及显示窗口
cap.release()
cv.destoryAllWindows()