一、在树莓派中安装opencv库
首先安装依赖,在安装过程中可能会遇到诸多“俄罗斯套娃”的依赖项,就不停地耐心安装。
pip3 install --upgrade setuptools
pip3 install numpy Matplotlib
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev
sudo apt-get install libgtk2.0-dev libgtk-3-dev
sudo apt-get install libatlas-base-dev
sudo apt install libqt4-test
sudo apt install libqtgui4
然后pip3安装opencv以及opencv,这样默认安装最新版
pip3 install opencv-python
pip3 install opencv-contrib-python
安装完毕,导入成功!
二、使用opencv和python控制树莓派的摄像头
示例代码
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
rawCapture = PiRGBArray(camera)
# allow the camera to warmup
time.sleep(2)
# grab an image from the camera
camera.capture(rawCapture, format="bgr")
image = rawCapture.array
# display the image on screen and wait for a keypress
cv2.imshow("Image", image)
cv2.waitKey(0)
通过摄像头实时拍摄查看视频
import cv2
cap = cv2.VideoCapture(0)
while(1):
ret, frame = cap.read()
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
三、利用树莓派的摄像头实现人脸识别
1.facerec_on_raspberry_pi.py
facerec_on_raspberry_pi.py
# This is a demo of running face recognition on a Raspberry Pi.
# This program will print out the names of anyone it recognizes to the console.
# To run this, you need a Raspberry Pi 2 (or greater) with face_recognition and
# the picamera[array] module installed.
# You can follow this installation instructions to get your RPi set up:
# https://gist.github.com/ageitgey/1ac8dbe8572f3f533df6269dab35df65
import face_recognition
import picamera
import numpy as np
# Get a reference to the Raspberry Pi camera.
# If this fails, make sure you have a camera connected to the RPi and that you
# enabled your camera in raspi-config and rebooted first.
camera = picamera.PiCamera()
camera.resolution = (320, 240)
output = np.empty((240, 320, 3), dtype=np.uint8)
# Load a sample picture and learn how to recognize it.
print("Loading known face image(s)")
obama_image = face_recognition.load_image_file("Biden.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
# Initialize some variables
face_locations = []
face_encodings = []
while True:
print("Capturing image.")
# Grab a single frame of video from the RPi camera as a numpy array
camera.capture(output, format="rgb")
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(output)
print("Found {} faces in image.".format(len(face_locations)))
face_encodings = face_recognition.face_encodings(output, face_locations)
# Loop over each face found in the frame to see if it's someone we know.
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
name = "<Unknown Person>"
if match[0]:
name = "Biden"
print("I see someone named {}!".format(name))
代码所在目录下应放一张用于比对的照片,文件名Biden.jpg
2.facerec_from_webcam_faster.py
facerec_from_webcam_faster.py
import face_recognition
import cv2
import numpy as np
# This is a demo of running face recognition on live video from your webcam. It's a little more complicated than the
# other example, but it includes some basic performance tweaks to make things run a lot faster:
# 1. Process each video frame at 1/4 resolution (though still display it at full resolution)
# 2. Only detect faces in every other frame of video.
# PLEASE NOTE: This example requires OpenCV (the `cv2` library) to be installed only to read from your webcam.
# OpenCV is *not* required to use the face_recognition library. It's only required if you want to run this
# specific demo. If you have trouble installing it, try any of the other demos that don't require it instead.
# Get a reference to webcam #0 (the default one)
video_capture = cv2.VideoCapture(0)
# Load a sample picture and learn how to recognize it.
obama_image = face_recognition.load_image_file("Obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
# Load a second sample picture and learn how to recognize it.
biden_image = face_recognition.load_image_file("Biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
# Create arrays of known face encodings and their names
known_face_encodings = [
obama_face_encoding,
biden_face_encoding
]
known_face_names = [
"Barack Obama",
"Joe Biden"
]
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
# Grab a single frame of video
ret, frame = video_capture.read()
# Resize frame of video to 1/4 size for faster face recognition processing
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_small_frame = small_frame[:, :, ::-1]
# Only process every other frame of video to save time
if process_this_frame:
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# # If a match was found in known_face_encodings, just use the first one.
# if True in matches:
# first_match_index = matches.index(True)
# name = known_face_names[first_match_index]
# Or instead, use the known face with the smallest distance to the new face
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
face_names.append(name)
process_this_frame = not process_this_frame
# Display the results
for (top, right, bottom, left), name in zip(face_locations, face_names):
# Scale back up face locations since the frame we detected in was scaled to 1/4 size
top *= 4
right *= 4
bottom *= 4
left *= 4
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
# Draw a label with a name below the face
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)
# Display the resulting image
cv2.imshow('Video', frame)
# Hit 'q' on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()
已经学习过本地的图片
未学习过的人脸图片
四、结合微服务的进阶任务
(1).安装Docker
下载安装脚本
curl -fsSL https://get.docker.com -o get-docker.sh
执行安装脚本(使用阿里云镜像)
sh get-docker.sh --mirror Aliyun
将当前用户加入docker用户组
sudo usermod -aG docker $USER
尝试下查看docker版本
(2).配置docker的镜像加速
请参考第一次实验博客
编辑完成后,restart一下docker
service docker restart
(3).定制自己的opencv镜像
首先拉取镜像
docker pull sixsq/opencv-python
运行这个镜像
docker run -it sixsq/opencv-python /bin/bash
在容器中,安装 "picamera[array]" dlib face_recognition
pip在线安装延迟严重,采用离线安装
安装成功,退出容器
然后commit
编写Dockerfile
FROM wjx_opencv
MAINTAINER 555
RUN mkdir /myapp
WORKDIR /myapp
COPY myapp .
build
docker build -t myopencv .
(4).运行容器执行facerec_on_raspberry_pi.py
docker run -it --device=/dev/vchiq --device=/dev/video0 --name facerec myopencv
python3 facerec_on_raspberry_pi.py
如果不加--device=/dev/vchiq
参数
则会出现以下报错
* failed to open vchiq instance
(5).附加选做:opencv的docker容器中运行facerec_from_webcam_faster.py
在Windows系统中安装Xming
安装过程一路默认即可(https://sourceforge.net/projects/xming/)
检查树莓派的ssh配置中的X11是否开启
cat /etc/ssh/sshd_config
然后编写run.sh
#sudo apt-get install x11-xserver-utils
xhost +
docker run -it \
--net=host \
-v $HOME/.Xauthority:/root/.Xauthority \
-e DISPLAY=:10.0 \
-e QT_X11_NO_MITSHM=1 \
--device=/dev/vchiq \
--device=/dev/video0 \
--name facerecgui \
myopencv \
python3 facerec_from_webcam_faster.py
sh run.sh
五、遇到的问题
(1)关于安装OpenCV的依赖
安装OpenCV,安装了一天。还是比较繁琐的。安装OpenCV的依赖,从最基础的依赖安装。
其中有依赖是套中套,在安装的过程中需要彼此依赖,比如安装gtk2与gtk3,所以我们是采用
sudo aptitude install libgtk2.0-dev libgtk-3-dev
他在遇到相互依赖时会给出解决方式,我们采取第二种方式,降低部分依赖的版本就行了(忘了截图)
(2)import cv2出现的问题
在import cv2时会出现依赖公共的库没有添加,这些就直接百度搜索,然后apt-get install 即可,可参考安装libImath-2_2.so.23 公共库
(3)undefined symbol: __atomic_fetch_add_8
在import cv2的最后一个问题
vim ~/.bashrc注意是pi用户下的bashrc,不是root下的bashrc
然后在末尾加上这段话,再source ~/.bashrc
export LD_PRELOAD=/usr/lib/arm-linux-gnueabihf/libatomic.so.1
(4)关于摄像头人脸识别
在本地放需要学习的图片,然后再通过利用树莓派摄像头进行其他图片的识别,即可。
(5)关于pip3 install安装时超时的问题(如face_recognition)
可以先再外面下载好相应的包之后,再通过winscp导入到树莓派,再离线安装
(6)在镜像里面安装"picamera[array]" dlib face_recognition时,在线安装比较延迟。
同样可以采用离线安装。通过本地下载文件,把文件复制进容器里面(docker cp file id:path),然后采用pip3离线安装方法。
六、在线协作
学号 | 姓名 | 工作 |
---|---|---|
031702539 | 李清宇 | OpenCV安装,硬件的操作,资料收集 |
031702547 | 汪佳祥 | OpenCV安装,人脸识别,结合微服务,修改博客 |
031702521 | 杨忠燎 | OpenCV安装,提供错误解决方案,撰写博客 |
通过视频,屏幕分享进行交流。成员通过TeamViewer进行远程操作,参与实验的各个步骤。
实验总共花费了整整三天,关于OpenCV的安装比较繁琐。反反复复弄了一天完成,人脸识别和结合微服务进展比较顺利。