【AIMB-2210研华AMD嵌入式主板】AI 视觉识别应用:人脸检测
本帖最后由 eefocus_4062187 于 2025-9-25 14:41 编辑# 【AIMB-2210研华AMD嵌入式主板】AI 视觉识别应用:人脸检测
本文介绍了 AIMB-2210 研华 AMD 嵌入式主板实现 AI 视觉识别类相关应用,包括环境搭建、模型训练、板端推理、摄像头实时检测和推理识别等。
## 项目介绍
- 环境部署:包括 Python 安装、OpenCV 库安装、工具链安装等;
- 模型训练:涉及到训练 ONNX 模型、模型转换等;
- 板端推理:包括人脸检测、物体识别、车牌识别;
- 实时监测:连接 USB 摄像头捕捉实时画面,并实现实时动态监测。
## 环境搭建
包括 Python安装、OpenCV 库安装、工具链安装等。
### Python 安装
- 下载并安装最新版 (https://www.python.org/) 软件,勾选添加路径至系统环境变量选项;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173758g6cmzczmlovdm66r.jpg)
- 安装完成后,Win + R 输入 CMD 回车,进入终端命令行界面;
- 执行 `python --version` 指令,获取当前版本信息,验证安装是否完成;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173809revwmxxmrss4m6te.jpg)
- 终端执行 `pip --version` 获取相应的版本号;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173819gt6tz592be202gm6.jpg)
### OpenCV 部署
- 终端执行 `pip install opencv-python` 安装 OpenCV 库;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173828pmo0o00jvugjmogj.jpg)
## 人脸检测
介绍了基于 OpenCV 的人脸检测项目的实现。
### 方案一
- 调用 OpenCV 自带的本地分类器 XML 级联文件;
- Python 安装路径下找到 `...\sitepackages\cv2\data\haarcascade_frontalface_default.xml` 文件(或使用 Everything 软件搜索获取路径);
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173846ti545x35xe3353be.jpg)
#### 流程图
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173858cigqb08iivqnalal.jpg)
#### 代码
新建 `face_detection.py` 文件,添加如下代码
```python
import cv2
from pathlib import Path
def detect_faces(image_path: str,
max_side: int = 1280,
padding: float = 0.05) -> None:
"""
零切割人脸检测
:param image_path:原图路径
:param max_side: 检测前最长边上限(越大越慢,越小越可能漏)
:param padding: 矩形向外扩的边距比例(0.05 = 5 %)
"""
# 1. 读图
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(image_path)
h0, w0 = img.shape[:2]
# 2. 等比例缩放
scale = min(1.0, max_side / max(h0, w0))
if scale < 1.0:
img_small = cv2.resize(img, (int(w0 * scale), int(h0 * scale)),
interpolation=cv2.INTER_LINEAR)
else:
img_small = img
h1, w1 = img_small.shape[:2]
# 3. 灰度 + 检测
gray = cv2.cvtColor(img_small, cv2.COLOR_BGR2GRAY)
cascade_path = Path(cv2.__file__).parent / "data" / "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(str(cascade_path))
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=7,
minSize=(60, 60)
)
# 4. 映射回原图 + 边缘修正
for (x, y, w, h) in faces:
# 映射回原图坐标
x = int(x / scale)
y = int(y / scale)
w = int(w / scale)
h = int(h / scale)
# 外扩边距
dw = int(w * padding)
dh = int(h * padding)
x = max(0, x - dw)
y = max(0, y - dh)
x2 = min(w0, x + w + 2 * dw)
y2 = min(h0, y + h + 2 * dh)
cv2.rectangle(img, (x, y), (x2, y2), (0, 255, 0), 2)
# 5. 显示
cv2.namedWindow("Face Detection", cv2.WINDOW_NORMAL)
cv2.imshow("Face Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
detect_faces(r".\face_img\friends.jpg")
```
- 右键该文件,选择使用 IDEL 编辑;
- 菜单栏选择 Run - Run Module 选项,运行程序;
#### 效果
运行程序后弹出人脸检测结果,这里举例展示部分效果
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173912qjkk162k6c61s26j.jpg)
- 识别精度与图片质量、模型置信度设置等参数有关;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173923i6nx5luxllng8ljl.jpg)
- 基于 haar 特征的 cascade 分类器实现人脸检测的方案;
- 该方案是一种机器学习方法,通过许多正负样例中训练得到cascade方程,并将其应用于目标图片;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173939v8o42osrovfs728j.jpg)
### 方案二
调用训练好的模型实现人脸检测,并标注相应的置信度。
使用 ONNX 模型,[下载](https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/face_detection_yunet_2023mar.onnx) 并将模型文件置于 model 文件夹路径下;
> YuNet 是 Anchor-Free 人脸检测器。
#### 流程图
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/173952s0srmsgga5r4rh3g.jpg)
#### 代码
新建 `face_detection_confidence.py` 文件,添加如下代码
```python
import cv2
def detect_faces_yunet(image_path: str,
conf_threshold: float = 0.8,
model_path: str = "model/face_detection_yunet_2023mar.onnx") -> None:
img = cv2.imread(image_path)
if img is None:
raise FileNotFoundError(image_path)
h, w = img.shape[:2]
# 初始化 YuNet
detector = cv2.FaceDetectorYN_create(
model=model_path,
config="",
input_size=(w, h),
score_threshold=conf_threshold,
nms_threshold=0.4,
top_k=5000
)
detector.setInputSize((w, h))
faces = detector.detect(img)# shape: (N, 15)x,y,w,h,x_reye,...,score
if faces is None:
faces = []
for face in faces:
x, y, w, h, *_ = face[:4]
score = face[-1]
x, y, w, h = map(int, (x, y, w, h))
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
label = f"{score:.2f}"
label_size, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
cv2.rectangle(img, (x, y - label_size - 4),
(x + label_size, y), (0, 255, 0), -1)
cv2.putText(img, label, (x, y - 2), cv2.FONT_HERSHEY_SIMPLEX,
0.5, (0, 0, 0), 1, cv2.LINE_AA)
cv2.namedWindow("YuNet Face Detection", cv2.WINDOW_NORMAL)
cv2.imshow("YuNet Face Detection", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
detect_faces_yunet(r".\face_img\friends.jpg")
```
- 右键该文件,选择使用 IDEL 编辑;
- 菜单栏选择 Run - Run Module 选项,运行程序;
> 或终端执行指令 `python E:\Code\fd\face_detection_confidence.py` 、双击 `*.py` 文件运行也可;
#### 效果
运行程序后弹出人脸检测结果,并标注人脸置信度
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174006z9xfx9n2n955qb9f.jpg)
- 调用 ONNX 模型实现人脸检测的方案相对于 Haar 特征识别方案具有更高的精度和置信度,同时提供更多可调控的信息;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174019znwewweemlalaxe1.jpg)
- 可见该方案在整体识别效果方面有显著提升;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174032jmbofmiz7qlfcffi.jpg)
- 对于图像分辨率较为一般的场景,也能准确识别人脸;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174043u4tgpeyrygzeggtj.jpg)
## 动态检测
调用本地 USB 摄像头资源,实时跑 **YuNet** 模型;
- 人脸框 + 置信度;
- 按 `q` 键退出;
- 首次运行自动下载 YuNet 权重文件;
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174057mq8xa8yqj5xtxcxz.jpg)
### 流程图
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174116vy8jsdwsqjjjmhh0.jpg)
### 代码
新建 `face_detection_CamUSB.py` 并添加如下代码
```python
import cv2
from pathlib import Path
import urllib.request
import sys
# ---------- 1. 模型路径 & 下载 ----------
MODEL_URL = (
"https://github.com/opencv/opencv_zoo/raw/main/models/face_detection_yunet/"
"face_detection_yunet_2023mar.onnx"
)
MODEL_PATH = Path("face_detection_yunet_2023mar.onnx")
if not MODEL_PATH.exists():
print("首次使用,正在下载 YuNet 权重...")
urllib.request.urlretrieve(MODEL_URL, MODEL_PATH)
print("下载完成.")
# ---------- 2. 初始化摄像头 ----------
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # CAP_DSHOW 仅 Windows 可删
if not cap.isOpened():
sys.exit("无法打开摄像头")
# 读取一帧拿到分辨率
ret, frame = cap.read()
if not ret:
sys.exit("无法读取画面")
h, w = frame.shape[:2]
# ---------- 3. 初始化 YuNet ----------
detector = cv2.FaceDetectorYN_create(
model=str(MODEL_PATH),
config="",
input_size=(w, h),
score_threshold=0.7,
nms_threshold=0.4,
top_k=5000
)
# ---------- 4. 主循环 ----------
print("按 q 退出")
while True:
ret, frame = cap.read()
if not ret:
break
# 检测
detector.setInputSize((w, h))
faces = detector.detect(frame)# shape: (N, 15)
if faces is None:
faces = []
for face in faces:
x, y, w_box, h_box = map(int, face[:4])
score = float(face[-1])
# 画框
cv2.rectangle(frame, (x, y), (x + w_box, y + h_box), (0, 255, 0), 2)
# 写置信度
label = f"{score:.2f}"
cv2.putText(frame, label, (x, y - 5),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2)
# 显示
cv2.imshow("YuNet USB Camera", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# ---------- 5. 清理 ----------
cap.release()
cv2.destroyAllWindows()
```
- 右键该文件,选择使用 IDEL 编辑;
- 菜单栏选择 Run - Run Module 选项,运行程序;
> 或双击 `*.py` 文件运行。
### 效果
运行程序后弹出摄像头实时采集画面,自动标注人脸选框和置信度
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174135nrgvvzglr7iiyqtm.jpg)
动态演示
!(https://www.eefocus.com/forum/data/attachment/forum/202509/21/174149qp4o5p6mgggm5gsr.gif)
## 总结
本文介绍了 AIMB-2210 研华 AMD 嵌入式主板实现 AI 视觉识别类的相关应用,包括环境搭建、模型训练、板端推理、摄像头实时检测和推理识别等,为该产品在 AI 视觉领域的快速开发和应用提供了参考。
<iframe src="//player.bilibili.com/player.html?isOutside=true&aid=115253820068935&bvid=BV16bJ1zfEqj&cid=32619760809&p=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"></iframe>
页:
[1]