前段时间室友要做课程设计,用树莓派做人脸识别,就帮忙做了一下。
用的是普通的USB摄像头,罗技的C270(树莓派官方摄像头有点贵)
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install python-opencv
安装opencv的方法有很多,具体一点可以参考https://blog.csdn.net/kyokozan/article/details/79192646这一篇博客
# -*- coding: utf-8 -*-
__author__ = "kyoRan"
import cv2
cap = cv2.VideoCapture(0) # 打开摄像头
print("VideoCapture is opened?", cap.isOpened())
while(True):
ret, frame = cap.read() # 读取摄像头图像
center = (frame.shape[1]//2, frame.shape[0]//2) # 图像中心点位置
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 转灰度
cv2.circle(gray, center=center, radius=100, color=(0,0,255)) # 画圆
cv2.imshow("frame", gray) # 显示图片
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release() # 释放摄像头
cv2.destroyAllWindows() # 关闭所有窗口
如果正常使用,说明opencv安装完毕
### Imports ###################################################################
import time
import cv2
import os
### Setup #####################################################################
# Center coordinates
cx = 160
cy = 120
os.system( "echo 0=150 > /dev/servoblaster" )
os.system( "echo 1=150 > /dev/servoblaster" )
xdeg = 150
ydeg = 150
cap = cv2.VideoCapture(0)
# Load a cascade file for detecting faces
face_cascade = cv2.CascadeClassifier( '/home/pi/opencv/data/lbpcascades/lbpcascade_frontalface.xml' )
t_start = time.time()
fps = 0
### Main ######################################################################
# the times of running
for i in range(500):
ret,image=cap.read()
# image = frame.array
# Use the cascade file we loaded to detect faces
gray = cv2.cvtColor( image, cv2.COLOR_BGR2GRAY )
faces = face_cascade.detectMultiScale( gray )
print ("Found " + str( len( faces ) ) + " face(s)")
# Draw a rectangle around every face and move the motor towards the face
for ( x, y, w, h ) in faces:
cv2.rectangle( image, ( x, y ), ( x + w, y + h ), ( 100, 255, 100 ), 2 )
cv2.putText( image, "Face No." + str( len( faces ) ), ( x, y ), cv2.FONT_HERSHEY_SIMPLEX, 0.5, ( 0, 0, 255 ), 2 )
tx = x + w/2
ty = y + h/2
if ( cx - tx > 10 and xdeg <= 190 ): xdeg += 3*os.system( "echo 0=" + str( xdeg ) + " > /dev/servoblaster" )
elif ( cx - tx < -10 and xdeg >= 110 ):
xdeg -= 3
os.system( "echo 0=" + str( xdeg ) + " > /dev/servoblaster" )
if ( cy - ty > 10 and ydeg >= 110 ):
ydeg -= 3
os.system( "echo 1=" + str( ydeg ) + " > /dev/servoblaster" )
elif ( cy - ty < -10 and ydeg <= 190 ): ydeg += 3 os.system( "echo 1=" + str( ydeg ) + " > /dev/servoblaster" )
# Calculate and show the FPS
fps = fps + 1
sfps = fps / ( time.time() - t_start )
cv2.putText( image, "FPS : " + str( int( sfps ) ), ( 10, 10 ), cv2.FONT_HERSHEY_SIMPLEX, 0.5, ( 0, 0, 255 ), 2 )
# Show the frame
cv2.imshow( "Frame", image )
cv2.waitKey( 1 )
# Clear the stream in preparation for the next frame
rawCapture.truncate( 0 )
由于没有做任何的算法优化,因此FPS只能到达2、3帧,可以使用插帧算法和多线程的方式来提高帧率。
用的是opencv自带的XML文件,也可以引用别的更好的XML文件
注意:
# Load a cascade file for detecting faces
face_cascade = cv2.CascadeClassifier( '你的XML文件路径' )
一定要设置对文件路径