图44.3.2.1 人脸68关键点检测实验流程图
44.3.3 main.py代码
main.py中的脚本代码如下所示:
import lcd
import sensor
import gc
from maix import KPU
lcd.init()
sensor.reset()
sensor.set_framesize(sensor.QVGA)
sensor.set_pixformat(sensor.RGB565)
sensor.set_hmirror(False)
anchor = (0.1075, 0.126875, 0.126875, 0.175, 0.1465625, 0.2246875, 0.1953125, 0.25375, 0.2440625, 0.351875, 0.341875, 0.4721875, 0.5078125, 0.6696875, 0.8984375, 1.099687, 2.129062, 2.425937)
names = ['face']
# 构造并初始化人脸检测KPU对象
face_detecter = KPU()
face_detecter.load_kmodel("/sd/KPU/face_detect_320x240.kmodel")
face_detecter.init_yolo2(anchor, anchor_num=len(anchor) // 2, img_w=320, img_h=240, net_w=320, net_h=240, layer_w=10, layer_h=8, threshold=0.5, nms_value=0.2, classes=len(names))
# 构造并初始化人脸68关键点检测KPU对象
lm68_kpu = KPU()
lm68_kpu.load_kmodel("/sd/KPU/landmark68.kmodel")
# 按指定比例扩展矩形框
def extend_box(x, y, w, h, scale):
x1 = int(x - scale * w)
x2 = int(x + w - 1 + scale * w)
y1 = int(y - scale * h)
y2 = int(y + h - 1 + scale * h)
x1 = x1 if x1 > 0 else 0
x2 = x2 if x2 < (320 - 1) else (320 - 1)
y1 = y1 if y1 > 0 else 0
y2 = y2 if y2 < (240 - 1) else (240 - 1)
return x1, y1, x2 - x1 + 1, y2 - y1 + 1
while True:
img = sensor.snapshot()
face_detecter.run_with_output(img)
faces = face_detecter.regionlayer_yolo2()
for face in faces:
# 框出人脸位置
x, y, w, h = extend_box(face[0], face[1], face[2], face[3], 0.08)
img.draw_rectangle(x, y, w, h, color=(0, 255, 0))
# 计算人脸68关键点
face_img = img.cut(x, y, w, h)
resize_img = face_img.resize(128, 128)
resize_img.pix_to_ai()
output = lm68_kpu.run_with_output(resize_img, getlist=True)
for i in range(len(output) // 2):
point_x = int(KPU.sigmoid(output[2 * i]) * w + x)
point_y = int(KPU.sigmoid(output[2 * i + 1]) * h + y)
img.draw_cross(point_x, point_y, size=5, color=(0, 0, 255))
del face_img
del resize_img
lcd.display(img)
gc.collect()
可以看到一开始是先初始化了LCD和摄像头,并分别构造并初始化了用于人脸检测和人脸68关键点检测的KPU对象。
然后便是在一个循环中不断地获取摄像头输出的图像,首先将图像进行人脸检测,检测图像中存在的人脸,接着对人脸图像进行68关键点检测,分析出人脸68关键点的位置,最后将以上所有的分析检测结果在图像上进行绘制,然后在LCD上显示图像。
44.4 运行验证
将DNK210开发板连接CanMV IDE,点击CanMV IDE上的“开始(运行脚本)”按钮后,将摄像头对准人脸,让其采集到人脸图像,随后便能在LCD上看到摄像头输出的图像,同时能看到图像上标注了人脸位置和人脸68关键点位置等信息,如下图所示:
图44.4.1 LCD显示人脸68关键点检测实验结果