实验环境

(1)硬件环境

机械臂一台:具备视觉识别与定位功能的机械臂设备
摄像头:用于采集图像并进行人脸识别的视觉设备
测试人员:提供人脸样本用于识别测试

(2)软件环境

Vmware虚拟环境:运行Ubuntu系统的虚拟化平台
Python 3.x 环境:支持OpenCV和人脸识别库运行
OpenCV库:用于图像处理和人脸检测的计算机视觉库
Jupyter Notebook:用于运行和调试人脸识别代码的交互式环境
Haar级联分类器:用于人脸检测的预训练模型(haarcascade_frontalface_default.xml)

实验步骤

注意:请确保摄像头视觉范围内出现人脸用于检测。
  1. 启动虚拟机,在Windows电脑中,使用Vmware运行Ubuntu系统。
  2. 找到路径 /Home/Dofbot/6.AI_Visual/6.Face recognition.ipynb,右击选择用Jupyter Notebook启动,输入密码 shujia
  3. 按照代码单元顺序执行程序,启动人脸识别功能。
  4. 将人脸置于摄像头前方,观察识别效果,系统会在人脸区域绘制绿色方框。
  5. 实验结束后,点击"Exit"按钮退出程序。

实验结果

人脸识别结果

主要代码

代码路径:
/Home/Dofbot/6.AI_Visual/6.Face recognition.ipynb
/Home/Dofbot/6.AI_Visual/facefollow.py

1. 人脸识别核心类(facefollow.py):

#!/usr/bin/env python
# coding: utf-8
import cv2 as cv

class face_follow:
    def __init__(self):
        # 导入Haar级联分类器xml文件
        self.faceDetect = cv.CascadeClassifier("haarcascade_frontalface_default.xml")

    def face_filter(self, faces):
        '''
        对人脸进行过滤
        '''
        if len(faces) == 0: return None
        # 选择画面中面积最大的人脸
        max_face = max(faces, key=lambda face: face[2] * face[3])
        (x, y, w, h) = max_face
        # 设置人脸检测最小阈值
        if w < 10 or h < 10: return None
        return max_face

    def follow_function(self, img):
        img = cv.resize(img, (640, 480))
        # 将图像转为灰度图(便于检测)
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        # 检测人脸
        faces = self.faceDetect.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)
        
        if len(faces) != 0:
            # 人脸过滤
            face = self.face_filter(faces)
            (x, y, w, h) = face
            # 在原彩图上绘制矩形框
            cv.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 4)
            # 添加标签
            cv.putText(img, 'Person', (280, 30), cv.FONT_HERSHEY_SIMPLEX, 0.8, (105, 105, 105), 2)
           
        return img
函数说明:
1. face_filter()函数:对检测到的人脸进行过滤,选择面积最大的有效人脸(排除过小的误检测区域)。
2. follow_function()函数:实现核心人脸识别功能,将图像转为灰度图后进行人脸检测,对检测到的人脸绘制绿色方框并标记。

2. 主线程(Face recognition.ipynb):

import cv2 as cv
import threading
from time import sleep
import ipywidgets.widgets as widgets
from IPython.display import display
from face_follow import face_follow

follow = face_follow()
model = 'General'

# 创建交互控件
button_layout = widgets.Layout(width='250px', height='50px', align_self='center')
output = widgets.Output()

# 退出控件
exit_button = widgets.Button(description='Exit', button_style='danger', layout=button_layout)

# 图像控件
imgbox = widgets.Image(format='jpg', height=480, width=640, layout=widgets.Layout(align_self='center'))

# 空间布局
controls_box = widgets.VBox([imgbox, exit_button], layout=widgets.Layout(align_self='center'))

# 退出按钮回调函数
def exit_button_Callback(value):
    global model
    model = 'Exit'
exit_button.on_click(exit_button_Callback)

# 摄像头处理函数
def camera():
    global model
    # 打开摄像头
    capture = cv.VideoCapture(0)
    while capture.isOpened():
        try:
            _, img = capture.read()
            img = cv.resize(img, (640, 480))
            # 调用人脸识别函数
            img = follow.follow_function(img)
            
            if model == 'Exit':
                cv.destroyAllWindows()
                capture.release()
                break
                
            # 更新图像显示
            imgbox.value = cv.imencode('.jpg', img)[1].tobytes()
        except KeyboardInterrupt:
            capture.release()

# 显示控件并启动线程
display(controls_box, output)
threading.Thread(target=camera, ).start()
代码说明:本实验采用Haar级联分类器实现人脸识别功能,通过OpenCV的CascadeClassifier加载预训练模型文件。程序首先将彩色图像转为灰度图以减少计算量,然后使用detectMultiScale函数检测人脸区域。通过face_filter函数过滤出最主要的人脸目标,并在原始图像上绘制绿色矩形框进行标记。主线程负责摄像头数据采集、UI控件交互和线程管理,实现了实时人脸检测与显示功能,为机械臂的人脸跟踪应用提供基础定位能力。