第7次实践作业 25组

(1)在树莓派中安装opencv库

安装依赖

# 更新软件源,更新软件
sudo apt-get update && sudo apt-get upgrade

# Cmake等开发者工具
sudo apt-get install build-essential cmake pkg-config

# 图片I/O包
sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev

# 视频I/O包
sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
sudo apt-get install libxvidcore-dev libx264-dev

# OpenCV用于显示图片的子模块需要GTK
sudo apt-get install libgtk2.0-dev libgtk-3-dev

# 性能优化包
sudo apt-get install libatlas-base-dev gfortran

# 安装 Python2.7 & Python3
sudo apt-get install python2.7-dev python3-dev

下载OpenCV源代码

从官方的OpenCV仓库中获取OpenCV 的 4.1.2归档。

cd ~
wget -O opencv.zip https://github.com/Itseez/opencv/archive/4.1.2.zip
unzip opencv.zip

获取opencv_contrib存储库

wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/4.1.2.zip
unzip opencv_contrib.zip

注意:确保 opencv和 opencv_contrib版本相同。

准备编译环境

# 安装pip
wget https://bootstrap.pypa.io/get-pip.py
sudo python get-pip.py
sudo python3 get-pip.py
# 安装虚拟环境,防止依赖冲突
sudo pip install virtualenv virtualenvwrapper
sudo rm -rf ~/.cache/pip

# > 重定向输出流 >> 表示追加
echo -e "\n# virtualenv and virtualenvwrapper" >> ~/.profile
echo "export WORKON_HOME=$HOME/.virtualenvs" >> ~/.profile
echo "export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3" >> ~/.profile
echo "source /usr/local/bin/virtualenvwrapper.sh" >> ~/.profile

# 每次新开终端,需要虚拟环境时都要运行
source ~/.profile

# 创建虚拟环境cv
mkvirtualenv cv -p python3

# 进入虚拟环境
workon cv
# 安装numpy,较耗时
pip install numpy

编译opencv

要确保已经进入了cv虚拟环境,命令提示符开头有(cv)。

# 这里我们用的是3.3.0版本
cd ~/opencv-3.3.0/
mkdir build
cd build
# 设置CMake构建选项
cmake -D CMAKE_BUILD_TYPE=RELEASE \
    -D CMAKE_INSTALL_PREFIX=/usr/local \
    -D INSTALL_PYTHON_EXAMPLES=ON \
    -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.3.0/modules \
    -D BUILD_EXAMPLES=ON ..

为了避免编译时内存不足导致的CPU挂起,调整swap交换文件大小:

# CONF_SWAPSIZE由100改为1024,编译完成后改回来
sudo nano /etc/dphys-swapfile
# 重启swap服务
sudo /etc/init.d/dphys-swapfile stop
sudo /etc/init.d/dphys-swapfile start

到这里就完成了大部分准备工作,开始编译:

# 开始编译,很耗时
make -j4

安装opencv

sudo make install
sudo ldconfig

检查OpenCV的安装位置

ls -l /usr/local/lib/python3.7/site-packages/
cd ~/.virtualenvs/cv/lib/python3.7/site-packages/
ln -s /usr/local/lib/python3.7/site-packages/cv2 cv2

测试opencv

source ~/.profile
workon cv
python
import cv2
cv2.__version__

(2)使用opencv和python控制树莓派的摄像头

安装picreame

source ~/.profile 
workon cv 
pip install "picamera[array]"

拍照测试

# 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(5)
 
# 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)

(3)利用树莓派的摄像头实现人脸识别

安装依赖库dlib,face_recognition

source ~/.profile 
workon cv 
pip install dlib
pip install face_recognition

切换到放有要加载图片和python代码的目录下

1.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)")
image = face_recognition.load_image_file("Einstein_origin.jpg")
face_encoding = face_recognition.face_encodings(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([face_encoding], face_encoding)
        name = "<Unknown Person>"

        if match[0]:
            name = "Einstein"
        print("I see someone named {}!".format(name))

2.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.
Einstein_image = face_recognition.load_image_file("Einstein.jpg")
Einstein_face_encoding = face_recognition.face_encodings(Einstein_image)[0]

# Load a second sample picture and learn how to recognize it.
Planck_image = face_recognition.load_image_file("Planck.jpg")
Planck_face_encoding = face_recognition.face_encodings(Planck_image)[0]

# Create arrays of known face encodings and their names
known_face_encodings = [
    Einstein_face_encoding,
    Planck_face_encoding
]

known_face_names = [
    "Einstein",
    "Planck"
]



# 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()

(4)结合微服务的进阶任务

安装Docker

下载安装脚本

curl -fsSL https://get.docker.com -o get-docker.sh
image-20200603113918613

运行安装脚本(阿里云镜像)

sh get-docker.sh --mirror Aliyun

查看docker版本,验证是否安装成功

sudo docker --version

添加用户到docker组

sudo usermod -aG docker pi 

重新登陆让用户组生效

exit 
ssh pi@raspiberry

重启之后,docker指令之前就不需要加sudo了

定制opencv镜像

拉取镜像

docker pull sixsq/opencv-python

创建并运行容器

docker run -it sixsq/opencv-python /bin/bash

在容器中,用pip3安装 "picamera[array]",dlib和face_recognition

pip3 install "picamera[array]" 
pip3 install dlib 
pip3 install face_recognition
exit

commit镜像

自定义镜像

Dockerfile

FROM opencv1
RUN mkdir /myapp
WORKDIR /myapp
COPY myapp .

构建镜像

docker build -t opencv2 .

查看镜像

运行容器执行facerec_on_raspberry_pi.py

docker run -it --device=/dev/vchiq --device=/dev/video0 --name myopencv opencv2
python3 facerec_on_raspberry_pi.py

选做:在opencv的docker容器中跑通步骤(3)的示例代码facerec_from_webcam_faster.py

在Windows系统中安装Xming

开启树莓派的ssh配置中的X11

查看DISPLAY环境变量值

printenv

编写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 \
        opencv2 \
	python3 facerec_from_webcam_faster.py

打开终端,运行run.sh

sh run.sh

可以看到在windows的Xvideo可以正确识别人脸。

(5)以小组为单位,发表一篇博客,记录遇到的问题和解决方法,提供小组成员名单、分工、各自贡献以及在线协作的图片

posted @ 2020-06-06 20:40  annahme  阅读(232)  评论(0编辑  收藏  举报