找回密码
 立即注册
首页 业界区 安全 高通手机跑AI系列之——468个面部关键点提取 ...

高通手机跑AI系列之——468个面部关键点提取

镝赋洧 2025-7-14 13:21:52
(原创作者@CSDN_伊利丹~怒风)
环境准备

手机
测试手机型号:Redmi K60 Pro
处理器:第二代骁龙8移动--8gen2
运行内存:8.0GB ,LPDDR5X-8400,67.0 GB/s
摄像头:前置16MP+后置50MP+8MP+2MP
AI算力:NPU 48Tops INT8 && GPU 1536ALU x 2 x 680MHz = 2.089 TFLOPS
提示:任意手机均可以,性能越好的手机速度越快
软件
APP:AidLux 2.0
系统环境:Ubuntu 20.04.3 LTS
提示:AidLux登录后代码运行更流畅,在代码运行时保持AidLux APP在前台运行,避免代码运行过程中被系统回收进程,另外屏幕保持常亮,一般息屏后一段时间,手机系统会进入休眠状态,如需长驻后台需要给APP权限。
算法Demo

Demo代码介绍

下面的代码Demo实现了一个基于深度学习的实时人脸检测与面部关键点识别,468个人脸部关键点精准定位并支持多个人同时检测,支持关键点3D坐标,主要功能包括:
1. 摄像头初始化:代码会自动检测可用的 USB 摄像头,如果没有找到,则使用默认的前置摄像头。
2. 双模型架构:

  • 使用 BlazeFace 模型进行人脸检测,该模型可以快速定位图像中的人脸位置
  • 使用面部关键点识别模型识别 468 个面部关键点,包括眼睛、眉毛、嘴巴等特征点
3. 图像预处理:

  • 将图像填充为正方形,确保在不改变宽高比的情况下调整大小
  • 转换颜色空间(BGR 到 RGB)
  • 归一化像素值到 [-1, 1] 范围
  • 调整图像大小以适应模型输入要求
4. 实时处理:

  • 系统采用了优化策略,只在未检测到人脸时执行人脸检测
  • 人脸检测成功后,仅对检测到的人脸区域执行关键点识别
  • 计算帧率以监控系统性能
5. 结果可视化:

  • 在图像上绘制面部关键点
  • 连接特定关键点形成面部特征线,如眼睛轮廓、眉毛、嘴巴等
  • 提供直观的视觉反馈
6. 硬件加速:

  • 人脸检测模型使用 CPU 加速
  • 面部关键点识别模型使用 GPU 加速,提高处理速度
7. 人脸跟踪:

  • 通过比较连续帧的人脸特征值来跟踪人脸
  • 当特征值变化过大时,重新执行人脸检测
这个应用程序在实时视频流中能够准确地检测人脸并识别面部关键点,可用于表情分析、人脸动画、增强现实等多种应用场景。
Demo中算法模型特点分析

这段代码使用了两个深度学习模型通过AidLite框架来实现人脸检测和面部关键点识别功能:
1. 人脸检测模型 (face_detection_front.tflite)

  • 模型路径: models/face_detection_front.tflite
  • 输入尺寸: 128x128
  • 硬件加速: CPU (配置为TYPE_CPU)
  • 作用:

    • 负责在视频帧中快速定位人脸位置
    • 输出人脸的边界框坐标(归一化值)
    • 使用BlazeFace 算法实现轻量级高效检测
    • 输出 896 个预测框(每个框包含边界坐标和置信度)

2. 面部关键点识别模型 (face_landmark.tflite)

  • 模型路径: models/face_landmark.tflite
  • 输入尺寸: 192x192
  • 硬件加速: GPU (配置为TYPE_GPU)
  • 作用:

    • 在检测到的人脸区域内精确定位 468 个面部关键点
    • 关键点覆盖眼睛、眉毛、鼻子、嘴巴、耳朵等部位
    • 输出包含 3D 坐标(x,y,z)的面部网格
    • 用于绘制详细的面部特征线和轮廓

模型协同工作流程

  • 人脸检测

    • 使用preprocess_img_pad将输入图像填充为正方形并缩放到 128x128
    • 通过blazeface算法处理检测结果,获取人脸边界框
    • 只有在未检测到人脸时才执行此步骤,提高效率

  • 关键点识别

    • 从检测到的人脸区域中裁剪出 ROI(感兴趣区域)
    • 将 ROI 调整为 192x192 输入到关键点模型
    • 输出 468 个关键点的 3D 坐标
    • 通过draw_landmarks函数在原图上绘制关键点和连线

技术特点

  • 双阶段处理:先检测人脸再识别关键点,减少计算量
  • 硬件优化:CPU 用于轻量级人脸检测,GPU 用于复杂的关键点识别
  • 实时性:通过 Aidlux 平台的加速配置实现手机端上的实时视频处理
  • 鲁棒性

    • 使用stride8输出值监控人脸稳定性
    • 当人脸特征变化过大时(阈值 0.5)重新执行人脸检测
    • 前置摄像头自动翻转图像以适应镜像场景

这两个模型组合使用,可以在移动设备上实现高效的实时人脸分析,广泛应用于表情识别、AR 滤镜、人机交互等场景。
  1. import time
  2. from time import sleep
  3. import math
  4. import sys
  5. import numpy as np
  6. from blazeface import *
  7. import aidlite
  8. import os
  9. import subprocess
  10. import aidcv as cv2
  11. # 摄像头设备目录
  12. root_dir = "/sys/class/video4linux/"
复制代码
   继续展开代码
  1. # 图像预处理函数,用于TFLite模型输入
  2. def preprocess_image_for_tflite32(image, model_image_size=192):
  3.    """
  4.    对图像进行预处理,使其适合TFLite模型输入
  5.    1. 将BGR格式转换为RGB格式
  6.    2. 调整图像大小为模型输入尺寸
  7.    3. 添加批次维度
  8.    4. 归一化像素值到[-1, 1]范围
  9.    5. 转换为float32类型
  10.    """
  11.    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
  12.    image = cv2.resize(image, (model_image_size, model_image_size))
  13.    image = np.expand_dims(image, axis=0)
  14.    image = (2.0 / 255.0) * image - 1.0
  15.    image = image.astype('float32')
  16.    return image
  17. # 图像填充和预处理函数
  18. def preprocess_img_pad(img, image_size=128):
  19.    """
  20.    对图像进行填充和预处理
  21.    1. 将图像填充为正方形
  22.    2. 保存原始填充图像用于后续显示
  23.    3. 调整填充后图像大小为模型输入尺寸
  24.    4. 归一化并添加批次维度
  25.    """
  26.    # fit the image into a 128x128 square
  27.    shape = np.r_[img.shape]
  28.    pad_all = (shape.max() - shape[:2]).astype('uint32')
  29.    pad = pad_all // 2
  30.    img_pad_ori = np.pad(
  31.        img,
  32.        ((pad[0], pad_all[0] - pad[0]), (pad[1], pad_all[1] - pad[1]), (0, 0)),
  33.        mode='constant')
  34.    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
  35.    img_pad = np.pad(
  36.        img,
  37.        ((pad[0], pad_all[0] - pad[0]), (pad[1], pad_all[1] - pad[1]), (0, 0)),
  38.        mode='constant')
  39.    img_small = cv2.resize(img_pad, (image_size, image_size))
  40.    img_small = np.expand_dims(img_small, axis=0)
  41.    img_small = (2.0 / 255.0) * img_small - 1.0
  42.    img_small = img_small.astype('float32')
  43.    return img_pad_ori, img_small, pad
  44. # 在图像上绘制检测框
  45. def plot_detections(img, detections, with_keypoints=True):
  46.    """
  47.    在图像上绘制人脸检测框
  48.    1. 根据检测结果计算人脸区域
  49.    2. 调整区域大小,确保包含完整人脸
  50.    3. 在图像上绘制矩形框
  51.    """
  52.    output_img = img
  53.    print(img.shape)
  54.    x_min = 0
  55.    x_max = 0
  56.    y_min = 0
  57.    y_max = 0
  58.    print("Found %d faces" % len(detections))
  59.    for i in range(len(detections)):
  60.        ymin = detections[i][0] * img.shape[0]
  61.        xmin = detections[i][1] * img.shape[1]
  62.        ymax = detections[i][2] * img.shape[0]
  63.        xmax = detections[i][3] * img.shape[1]
  64.        w = int(xmax - xmin)
  65.        h = int(ymax - ymin)
  66.        h = max(w, h)
  67.        h = h * 1.5
  68.        x = (xmin + xmax) / 2.
  69.        y = (ymin + ymax) / 2.
  70.        xmin = x - h / 2.
  71.        xmax = x + h / 2.
  72.        ymin = y - h / 2. - 0.08 * h
  73.        ymax = y + h / 2. - 0.08 * h
  74.        x_min = int(xmin)
  75.        y_min = int(ymin)
  76.        x_max = int(xmax)
  77.        y_max = int(ymax)
  78.        p1 = (int(xmin), int(ymin))
  79.        p2 = (int(xmax), int(ymax))
  80.        cv2.rectangle(output_img, p1, p2, (0, 255, 255), 2, 1)
  81.    return x_min, y_min, x_max, y_max
  82. # 在图像上绘制面部网格
  83. def draw_mesh(image, mesh, mark_size=2, line_width=1):
  84.    """
  85.    在图像上绘制面部网格
  86.    1. 将归一化的关键点坐标转换为图像坐标
  87.    2. 在每个关键点位置绘制圆点
  88.    3. 连接关键点形成面部轮廓(眼睛等)
  89.    """
  90.    # The mesh are normalized which means we need to convert it back to fit
  91.    # the image size.
  92.    image_size = image.shape[0]
  93.    mesh = mesh * image_size
  94.    for point in mesh:
  95.        cv2.circle(image, (point[0], point[1]),
  96.                   mark_size, (0, 255, 128), -1)
  97.    # Draw the contours.
  98.    # Eyes
  99.    left_eye_contour = np.array([mesh[33][0:2],
  100.                                 mesh[7][0:2],
  101.                                 mesh[163][0:2],
  102.                                 mesh[144][0:2],
  103.                                 mesh[145][0:2],
  104.                                 mesh[153][0:2],
  105.                                 mesh[154][0:2],
  106.                                 mesh[155][0:2],
  107.                                 mesh[133][0:2],
  108.                                 mesh[173][0:2],
  109.                                 mesh[157][0:2],
  110.                                 mesh[158][0:2],
  111.                                 mesh[159][0:2],
  112.                                 mesh[160][0:2],
  113.                                 mesh[161][0:2],
  114.                                 mesh[246][0:2], ]).astype(np.int32)
  115.    right_eye_contour = np.array([mesh[263][0:2],
  116.                                  mesh[249][0:2],
  117.                                  mesh[390][0:2],
  118.                                  mesh[373][0:2],
  119.                                  mesh[374][0:2],
  120.                                  mesh[380][0:2],
  121.                                  mesh[381][0:2],
  122.                                  mesh[382][0:2],
  123.                                  mesh[362][0:2],
  124.                                  mesh[398][0:2],
  125.                                  mesh[384][0:2],
  126.                                  mesh[385][0:2],
  127.                                  mesh[386][0:2],
  128.                                  mesh[387][0:2],
  129.                                  mesh[388][0:2],
  130.                                  mesh[466][0:2]]).astype(np.int32)
  131.    # Lips
  132.    cv2.polylines(image, [left_eye_contour, right_eye_contour], False,
  133.                  (255, 255, 255), line_width, cv2.LINE_AA)
  134. # 在图像上绘制面部关键点
  135. def draw_landmarks(image, mesh):
  136.    """
  137.    在图像上绘制面部关键点和连接线
  138.    1. 将归一化的关键点坐标转换为图像坐标
  139.    2. 在每个关键点位置绘制圆点
  140.    3. 连接特定关键点形成面部特征线(眉毛、眼睛、嘴巴等)
  141.    """
  142.    image_size = image.shape[0]
  143.    mesh = mesh * image_size
  144.    landmark_point = []
  145.    for point in mesh:
  146.        landmark_point.append((int(point[0]), int(point[1])))
  147.        cv2.circle(image, (int(point[0]), int(point[1])), 2, (255, 255, 0), -1)
  148.    if len(landmark_point) > 0:
  149.        # 左眉毛(55:内側、46:外側)
  150.        cv2.line(image, landmark_point[55], landmark_point[65], (0, 0, 255), 2, -3)
  151.        cv2.line(image, landmark_point[65], landmark_point[52], (0, 0, 255), 2, -3)
  152.        cv2.line(image, landmark_point[52], landmark_point[53], (0, 0, 255), 2, -3)
  153.        cv2.line(image, landmark_point[53], landmark_point[46], (0, 0, 255), 2, -3)
  154.        # 右眉毛(285:内側、276:外側)
  155.        cv2.line(image, landmark_point[285], landmark_point[295], (0, 0, 255),
  156.                 2)
  157.        cv2.line(image, landmark_point[295], landmark_point[282], (0, 0, 255),
  158.                 2)
  159.        cv2.line(image, landmark_point[282], landmark_point[283], (0, 0, 255),
  160.                 2)
  161.        cv2.line(image, landmark_point[283], landmark_point[276], (0, 0, 255),
  162.                 2)
  163.        # 左目 (133:目頭、246:目尻)
  164.        cv2.line(image, landmark_point[133], landmark_point[173], (0, 0, 255),
  165.                 2)
  166.        cv2.line(image, landmark_point[173], landmark_point[157], (0, 0, 255),
  167.                 2)
  168.        cv2.line(image, landmark_point[157], landmark_point[158], (0, 0, 255),
  169.                 2)
  170.        cv2.line(image, landmark_point[158], landmark_point[159], (0, 0, 255),
  171.                 2)
  172.        cv2.line(image, landmark_point[159], landmark_point[160], (0, 0, 255),
  173.                 2)
  174.        cv2.line(image, landmark_point[160], landmark_point[161], (0, 0, 255),
  175.                 2)
  176.        cv2.line(image, landmark_point[161], landmark_point[246], (0, 0, 255),
  177.                 2)
  178.        cv2.line(image, landmark_point[246], landmark_point[163], (0, 0, 255),
  179.                 2)
  180.        cv2.line(image, landmark_point[163], landmark_point[144], (0, 0, 255),
  181.                 2)
  182.        cv2.line(image, landmark_point[144], landmark_point[145], (0, 0, 255),
  183.                 2)
  184.        cv2.line(image, landmark_point[145], landmark_point[153], (0, 0, 255),
  185.                 2)
  186.        cv2.line(image, landmark_point[153], landmark_point[154], (0, 0, 255),
  187.                 2)
  188.        cv2.line(image, landmark_point[154], landmark_point[155], (0, 0, 255),
  189.                 2)
  190.        cv2.line(image, landmark_point[155], landmark_point[133], (0, 0, 255),
  191.                 2)
  192.        # 右目 (362:目頭、466:目尻)
  193.        cv2.line(image, landmark_point[362], landmark_point[398], (0, 0, 255),
  194.                 2)
  195.        cv2.line(image, landmark_point[398], landmark_point[384], (0, 0, 255),
  196.                 2)
  197.        cv2.line(image, landmark_point[384], landmark_point[385], (0, 0, 255),
  198.                 2)
  199.        cv2.line(image, landmark_point[385], landmark_point[386], (0, 0, 255),
  200.                 2)
  201.        cv2.line(image, landmark_point[386], landmark_point[387], (0, 0, 255),
  202.                 2)
  203.        cv2.line(image, landmark_point[387], landmark_point[388], (0, 0, 255),
  204.                 2)
  205.        cv2.line(image, landmark_point[388], landmark_point[466], (0, 0, 255),
  206.                 2)
  207.        cv2.line(image, landmark_point[466], landmark_point[390], (0, 0, 255),
  208.                 2)
  209.        cv2.line(image, landmark_point[390], landmark_point[373], (0, 0, 255),
  210.                 2)
  211.        cv2.line(image, landmark_point[373], landmark_point[374], (0, 0, 255),
  212.                 2)
  213.        cv2.line(image, landmark_point[374], landmark_point[380], (0, 0, 255),
  214.                 2)
  215.        cv2.line(image, landmark_point[380], landmark_point[381], (0, 0, 255),
  216.                 2)
  217.        cv2.line(image, landmark_point[381], landmark_point[382], (0, 0, 255),
  218.                 2)
  219.        cv2.line(image, landmark_point[382], landmark_point[362], (0, 0, 255),
  220.                 2)
  221.        # 口 (308:右端、78:左端)
  222.        cv2.line(image, landmark_point[308], landmark_point[415], (0, 0, 255),
  223.                 2)
  224.        cv2.line(image, landmark_point[415], landmark_point[310], (0, 0, 255),
  225.                 2)
  226.        cv2.line(image, landmark_point[310], landmark_point[311], (0, 0, 255),
  227.                 2)
  228.        cv2.line(image, landmark_point[311], landmark_point[312], (0, 0, 255),
  229.                 2)
  230.        cv2.line(image, landmark_point[312], landmark_point[13], (0, 0, 255), 2)
  231.        cv2.line(image, landmark_point[13], landmark_point[82], (0, 0, 255), 2)
  232.        cv2.line(image, landmark_point[82], landmark_point[81], (0, 0, 255), 2)
  233.        cv2.line(image, landmark_point[81], landmark_point[80], (0, 0, 255), 2)
  234.        cv2.line(image, landmark_point[80], landmark_point[191], (0, 0, 255), 2)
  235.        cv2.line(image, landmark_point[191], landmark_point[78], (0, 0, 255), 2)
  236.        cv2.line(image, landmark_point[78], landmark_point[95], (0, 0, 255), 2)
  237.        cv2.line(image, landmark_point[95], landmark_point[88], (0, 0, 255), 2)
  238.        cv2.line(image, landmark_point[88], landmark_point[178], (0, 0, 255), 2)
  239.        cv2.line(image, landmark_point[178], landmark_point[87], (0, 0, 255), 2)
  240.        cv2.line(image, landmark_point[87], landmark_point[14], (0, 0, 255), 2)
  241.        cv2.line(image, landmark_point[14], landmark_point[317], (0, 0, 255), 2)
  242.        cv2.line(image, landmark_point[317], landmark_point[402], (0, 0, 255),
  243.                 2)
  244.        cv2.line(image, landmark_point[402], landmark_point[318], (0, 0, 255),
  245.                 2)
  246.        cv2.line(image, landmark_point[318], landmark_point[324], (0, 0, 255),
  247.                 2)
  248.        cv2.line(image, landmark_point[324], landmark_point[308], (0, 0, 255),
  249.                 2)
  250.    return image
  251. # 获取摄像头ID
  252. def get_cap_id():
  253.    """
  254.    获取可用的USB摄像头ID
  255.    1. 通过系统命令查询视频设备
  256.    2. 筛选出USB摄像头
  257.    3. 返回最小的可用摄像头ID
  258.    """
  259.    try:
  260.        # 构造命令,使用awk处理输出
  261.        cmd = "ls -l /sys/class/video4linux | awk -F ' -> ' '/usb/{sub(/.*video/, "", $2); print $2}'"
  262.        result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
  263.        output = result.stdout.strip().split()
  264.        # 转换所有捕获的编号为整数,找出最小值
  265.        video_numbers = list(map(int, output))
  266.        if video_numbers:
  267.            return min(video_numbers)
  268.        else:
  269.            return None
  270.    except Exception as e:
  271.        print(f"An error occurred: {e}")
  272.        return None
  273. # 初始化人脸检测模型参数
  274. inShape =[[1 , 128 , 128 ,3]]  # 输入张量形状
  275. outShape= [[1 , 896,16],[1,896,1]]  # 输出张量形状
  276. model_path="models/face_detection_front.tflite"  # 人脸检测模型路径
  277. model_path2="models/face_landmark.tflite"  # 面部关键点识别模型路径
  278. inShape2 =[[1 , 192 , 192 ,3]]  # 第二个模型的输入张量形状
  279. outShape2= [[1,1404],[1]]  # 第二个模型的输出张量形状
  280. # 初始化人脸检测模型
  281. # 创建Model实例对象,并设置模型相关参数
  282. model = aidlite.Model.create_instance(model_path)
  283. if model is None:
  284.    print("Create face_detection_front model failed !")
  285. # 设置模型属性
  286. model.set_model_properties(inShape, aidlite.DataType.TYPE_FLOAT32, outShape,aidlite.DataType.TYPE_FLOAT32)
  287. # 创建Config实例对象,并设置配置信息
  288. config = aidlite.Config.create_instance()
  289. config.implement_type = aidlite.ImplementType.TYPE_FAST
  290. config.framework_type = aidlite.FrameworkType.TYPE_TFLITE
  291. config.accelerate_type = aidlite.AccelerateType.TYPE_CPU  # 使用CPU加速
  292. config.number_of_threads = 4  # 使用4个线程
  293. # 创建推理解释器对象
  294. fast_interpreter = aidlite.InterpreterBuilder.build_interpretper_from_model_and_config(model, config)
  295. if fast_interpreter is None:
  296.    print("face_detection_front model build_interpretper_from_model_and_config failed !")
  297. # 完成解释器初始化
  298. result = fast_interpreter.init()
  299. if result != 0:
  300.    print("face_detection_front model interpreter init failed !")
  301. # 加载模型
  302. result = fast_interpreter.load_model()
  303. if result != 0:
  304.    print("face_detection_front model interpreter load face_detection_front model failed !")
  305. print("face_detection_front model model load success!")
  306. # 初始化面部关键点识别模型
  307. # 创建Model实例对象,并设置模型相关参数
  308. model2 = aidlite.Model.create_instance(model_path2)
  309. if model2 is None:
  310.    print("Create face_landmark model failed !")
  311. # 设置模型参数
  312. model2.set_model_properties(inShape2, aidlite.DataType.TYPE_FLOAT32, outShape2,aidlite.DataType.TYPE_FLOAT32)
  313. # 创建Config实例对象,并设置配置信息
  314. config2 = aidlite.Config.create_instance()
  315. config2.implement_type = aidlite.ImplementType.TYPE_FAST
  316. config2.framework_type = aidlite.FrameworkType.TYPE_TFLITE
  317. config2.accelerate_type = aidlite.AccelerateType.TYPE_GPU  # 使用GPU加速
  318. config2.number_of_threads = 4  # 使用4个线程
  319. # 创建推理解释器对象
  320. fast_interpreter2 = aidlite.InterpreterBuilder.build_interpretper_from_model_and_config(model2, config2)
  321. if fast_interpreter2 is None:
  322.    print("face_landmark model build_interpretper_from_model_and_config failed !")
  323. # 完成解释器初始化
  324. result = fast_interpreter2.init()
  325. if result != 0:
  326.    print("face_landmark model interpreter init failed !")
  327. # 加载模型
  328. result = fast_interpreter2.load_model()
  329. if result != 0:
  330.    print("face_landmark model interpreter load model failed !")
  331. print("face_landmark model load success!")
  332. # 加载人脸检测模型的锚点数据
  333. anchors = np.load('models/anchors.npy').astype(np.float32)
  334. aidlux_type="root"  # Aidlux平台类型
  335. # 0-后置,1-前置
  336. camId = 1  # 默认使用前置摄像头
  337. opened = False
  338. # 打开摄像头
  339. while not opened:
  340.    if aidlux_type == "basic":
  341.        cap=cv2.VideoCapture(camId, device='mipi')
  342.    else:
  343.        capId = get_cap_id()
  344.        print("usb camera id: ", capId)
  345.        if capId is None:
  346.           print ("no found usb camera")
  347.           # 默认用1-前置摄像头打开相机,若打开失败,请尝试修改为0-后置
  348.           cap=cv2.VideoCapture(1, device='mipi')
  349.        else:
  350.            camId = capId
  351.            cap = cv2.VideoCapture(camId)
  352.            cap.set(6, cv2.VideoWriter.fourcc('M','J','P','G'))  # 设置视频编码格式
  353.    if cap.isOpened():
  354.        opened = True
  355.    else:
  356.        print("open camera failed")
  357.        cap.release()
  358.        time.sleep(0.5)
  359. # 初始化人脸检测标志和位置变量
  360. bFace = False
  361. x_min, y_min, x_max, y_max = (0, 0, 0, 0)
  362. fface = 0.0
  363. # 主循环:实时处理视频流
  364. while True:
  365.    ret, frame=cap.read()
  366.    if not ret:
  367.        continue
  368.    if frame is None:
  369.        continue
  370.    if camId == 1:  # 如果是前置摄像头,水平翻转图像以获得镜像效果
  371.        frame = cv2.flip(frame, 1)
  372.    start_time = time.time()  # 记录开始时间用于计算帧率
  373.    # 预处理图像,添加填充
  374.    img_pad, img, pad = preprocess_img_pad(frame, 128)
  375.    # 如果没有检测到人脸,执行人脸检测
  376.    if bFace == False:
  377.        # 设置输入数据
  378.        result = fast_interpreter.set_input_tensor(0, img.data)
  379.        if result != 0:
  380.            print("face_detection_front model interpreter set_input_tensor() failed")
  381.        # 执行推理
  382.        result = fast_interpreter.invoke()
  383.        if result != 0:
  384.            print("face_detection_front model interpreter invoke() failed")
  385.        # 获取输出数据
  386.        raw_boxes = fast_interpreter.get_output_tensor(0)
  387.        if raw_boxes is None:
  388.            print("sample : face_detection_front model interpreter->get_output_tensor(0) failed !")
  389.        classificators = fast_interpreter.get_output_tensor(1)
  390.        if classificators is None:
  391.            print("sample : face_detection_front model interpreter->get_output_tensor(1) failed !")
  392.        # 使用blazeface算法处理检测结果
  393.        detections = blazeface(raw_boxes, classificators, anchors)[0]
  394.        if len(detections) > 0:
  395.            bFace = True  # 检测到人脸,设置标志为True
  396.    # 如果已检测到人脸,执行面部关键点识别
  397.    if bFace:
  398.        for i in range(len(detections)):
  399.            # 计算人脸区域
  400.            ymin = detections[i][0] * img_pad.shape[0]
  401.            xmin = detections[i][1] * img_pad.shape[1]
  402.            ymax = detections[i][2] * img_pad.shape[0]
  403.            xmax = detections[i][3] * img_pad.shape[1]
  404.            w = int(xmax - xmin)
  405.            h = int(ymax - ymin)
  406.            h = max(w, h)
  407.            h = h * 1.5  # 扩大人脸区域
  408.            x = (xmin + xmax) / 2.
  409.            y = (ymin + ymax) / 2.
  410.            # 调整人脸区域位置和大小
  411.            xmin = x - h / 2.
  412.            xmax = x + h / 2.
  413.            ymin = y - h / 2.
  414.            ymin = y - h / 2. - 0.08 * h
  415.            ymax = y + h / 2. - 0.08 * h
  416.            x_min = int(xmin)
  417.            y_min = int(ymin)
  418.            x_max = int(xmax)
  419.            y_max = int(ymax)
  420.            # 确保区域在图像范围内
  421.            x_min = max(0, x_min)
  422.            y_min = max(0, y_min)
  423.            x_max = min(img_pad.shape[1], x_max)
  424.            y_max = min(img_pad.shape[0], y_max)
  425.            
  426.            # 提取人脸区域
  427.            roi_ori = img_pad[y_min:y_max, x_min:x_max]
  428.            # 预处理人脸区域用于关键点识别
  429.            roi = preprocess_image_for_tflite32(roi_ori, 192)
  430.            # 设置面部关键点识别模型的输入
  431.            result = fast_interpreter2.set_input_tensor(0, roi.data)
  432.            if result != 0:
  433.                print("face_landmark model interpreter set_input_tensor() failed")
  434.            # 执行面部关键点识别
  435.            result = fast_interpreter2.invoke()
  436.            if result != 0:
  437.                print("face_landmark model interpreter set_input_tensor() failed")
  438.            # 获取识别结果
  439.            mesh = fast_interpreter2.get_output_tensor(0)
  440.            if mesh is None:
  441.                print("sample : face_landmark model interpreter->get_output_tensor(0) failed !")
  442.            stride8 = fast_interpreter2.get_output_tensor(1)
  443.            if stride8 is None:
  444.                print("sample : face_landmark model interpreter->get_output_tensor(1) failed !")
  445.            print(f"stride8.shape: {stride8.shape}")
  446.            ffacetmp = stride8[0]
  447.            print('fface:', abs(fface - ffacetmp))
  448.            
  449.            # 人脸跟踪稳定性检测
  450.            if abs(fface - ffacetmp) > 0.5:
  451.                bFace = False  # 如果变化过大,重置人脸检测标志
  452.            fface = ffacetmp
  453.            # 处理面部关键点数据
  454.            mesh = mesh.reshape(468, 3) / 192
  455.            # 在人脸区域上绘制关键点
  456.            draw_landmarks(roi_ori, mesh)
  457.            # 调整图像大小以适应显示
  458.            shape = frame.shape
  459.            x, y = img_pad.shape[0] / 2, img_pad.shape[1] / 2
  460.            frame = img_pad[int(y - shape[0] / 2):int(y + shape[0] / 2), int(x - shape[1] / 2):int(x + shape[1] / 2)]
  461.    # 显示处理后的图像
  462.    cv2.imshow("", frame)
  463.    
  464.    # 按ESC键退出
  465.    if cv2.waitKey(1) == 27:
  466.        break
  467. # 释放资源
  468. cap.release()
  469. cv2.destroyAllWindows()
复制代码
模型位置
  1. cd /opt/aidlux/app/aid-examples/face_det
复制代码
Demo效果

1.gif


来源:豆瓜网用户自行投稿发布,如果侵权,请联系站长删除

相关推荐

您需要登录后才可以回帖 登录 | 立即注册