《计算机视觉》—— 表情识别

  • 根据计算眼睛、嘴巴的变化,判断是什么表情

  • 结合以下两篇文章来理解表情识别的实现方法

  • 完整代码如下:

    python 复制代码
    import numpy as np
    import dlib
    import cv2
    from sklearn.metrics.pairwise import euclidean_distances
    from PIL import Image, ImageDraw, ImageFont
    
    # 计算眼睛的宽高比
    def eye_aspect_ratio(eye):
        A = euclidean_distances(eye[1].reshape(1, 2), eye[5].reshape(1, 2))
        B = euclidean_distances(eye[2].reshape(1, 2), eye[4].reshape(1, 2))
        C = euclidean_distances(eye[0].reshape(1, 2), eye[3].reshape(1, 2))
        ear = ((A + B) / 2.0) / C
        return ear
    
    
    # 计算嘴的宽高比
    def MAR(shape):
        x = shape[50]
        y = shape[50].reshape(1, 2)
    
        A = euclidean_distances(shape[50].reshape(1, 2), shape[58].reshape(1, 2))
        B = euclidean_distances(shape[51].reshape(1, 2), shape[57].reshape(1, 2))
        C = euclidean_distances(shape[52].reshape(1, 2), shape[56].reshape(1, 2))
        D = euclidean_distances(shape[48].reshape(1, 2), shape[54].reshape(1, 2))
        return ((A + B + C) / 3) / D
    
    
    # 计算嘴宽度与脸颊宽度的比值
    def MJR(shape):
        M = euclidean_distances(shape[48].reshape(1, 2), shape[54].reshape(1, 2))  # 嘴宽度
        J = euclidean_distances(shape[3].reshape(1, 2), shape[13].reshape(1, 2))  # 下颌的宽度
        return M / J
    
    """ 向图片中添加中文 """
    def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
        if (isinstance(img, np.ndarray)):  # 判断是否是OpenCV图片类型
            img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))  # 实现 array 到 image 的转换
        draw = ImageDraw.Draw(img)  # 在img图片上创建一个绘图的对象
        # 字体的格式                       C 盘中的 Windows/Fonts 中,复制到此文件夹下可看到文件名
        fontStyle = ImageFont.truetype("simsun.ttc", textSize, encoding="utf-8")
        draw.text(position, text, textColor, font=fontStyle)  # 绘制文本
        return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)  # 转换回 OpenCV 格式
    
    
    # 构建脸部位置检测器
    detector = dlib.get_frontal_face_detector()
    
    # 读取人脸关键点定位模型
    predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
    
    # 打开摄像头或视频
    cap = cv2.VideoCapture(0)
    
    while True:
        ret, frame = cap.read()
        frame = cv2.flip(frame, 1)
    
        faces = detector(frame, 0)  # 获取图片中全部人脸位置
    
        for face in faces:
            shape = predictor(frame, face)  # 获取关键点
            # 将关键点转换为坐标(x,y)的形式
            shape = np.array([[p.x, p.y] for p in shape.parts()])
            # 计算嘴部的高宽比
            mar = MAR(shape)
            # 计算 "最宽/脸颊宽"
            mjr = MJR(shape)
    
            rightEye = shape[36:42]  # 右眼,关键点索引从36到41(不包含42)
            leftEye = shape[42:48]  # 左眼,关键点索引从42到47(不包含48)
            rightEAR = eye_aspect_ratio(rightEye)  # 计算右眼纵横比
            leftEAR = eye_aspect_ratio(leftEye)  # 计算左眼纵横比
    
            ear = (rightEAR + leftEAR) / 2.0  # 均值处理
    
            result = "正常"  # 默认是正常表情
    
            # 打印出实际值,可以根据该值更改阈值
            print("mar", mar, "\tmjr", mjr, "\tear", ear)
    
            if mar > 0.5 and ear < 0.28:
                result = "大笑"
    
            elif mar > 0.5 and ear > 0.28:
                result = "愤怒"
    
            elif mjr > 0.45:
                result = "微笑"
            # 输出中文
            # frame = cv2AddChineseText(frame, result, (50, 100))
    
            # cv2.putText()#输出英文
    
            mouthHull = cv2.convexHull(shape[48:61])  # 嘴型构造凸包
    
            frame = cv2AddChineseText(frame, result, mouthHull[0, 0])  # 多人脸
    
            cv2.drawContours(frame, [mouthHull], -1, (0, 255, 0), 1)  # 画出凸包
    
        cv2.imshow("Frame", frame)
        if cv2.waitKey(1) == 27:
            break
    
    cv2.destroyAllWindows()
    cap.release()
相关推荐
Lee川42 分钟前
Milvus 实战:当 RAG 遇上向量数据库,从"玩具 Demo"到"生产可用的"那一步
前端·数据库·人工智能
晚烛1 小时前
CANN 调试工具与性能剖析:从日志分析到 NPU 行为追踪的完整调试体系
开发语言·windows·python·深度学习·缓存
小a彤2 小时前
elec-ops-inspection:电力巡检缺陷检测,NPU推理速度提升3倍
人工智能·cann
ZhengEnCi3 小时前
09aaa-LayerNorm是什么?
人工智能
这是谁的博客?3 小时前
AI Agent 安全架构设计:漏洞分析与防护策略深度解析
人工智能·安全·网络安全·ai·agent·安全架构·架构设计
人月神话-Lee3 小时前
【图像处理】Sobel 边缘检测——让机器“看见“轮廓
图像处理·人工智能·计算机视觉·ios·ai编程·swift
冬奇Lab3 小时前
Agent系列(四):工具调用深度解析——Agent 的手和眼
人工智能·llm
Black蜡笔小新3 小时前
自动化AI算法训练服务器DLTM助力医学影像分析进入AI智能分析新时代
人工智能·算法·自动化
隔壁大炮3 小时前
MNE-Python 第9天学习笔记:源定位基础
python·eeg·mne·脑电数据处理
冬奇Lab4 小时前
一天一个开源项目(第111篇):Understand Anything - 把代码库变成可探索知识图谱的 AI 引擎
人工智能·开源·llm