首页 > 编程问答 >Deepface - 仅以超过阈值的置信度显示面部的情绪

Deepface - 仅以超过阈值的置信度显示面部的情绪

时间:2024-08-06 03:48:04浏览次数:7  
标签:python opencv machine-learning computer-vision deepface

我有这段代码可以检测面部表情,但它会在没有面部表情的地方找到面部表情。所以我想知道是否可以放心地做到这一点。

我尝试在谷歌上搜索如何做到这一点,但没有找到任何有用的东西。

import cv2
from deepface import DeepFace

# Load face cascade classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Start capturing video
cap = cv2.VideoCapture('ap.mp4')

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Convert frame to grayscale
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Convert grayscale frame to RGB format
    rgb_frame = cv2.cvtColor(gray_frame, cv2.COLOR_GRAY2RGB)

    # Detect faces in the frame
    faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    for (x, y, w, h) in faces:
        # Extract the face ROI (Region of Interest)
        face_roi = rgb_frame[y:y + h, x:x + w]

        # Perform emotion analysis on the face ROI
        result = DeepFace.analyze(face_roi, actions=['emotion'], enforce_detection=False)

        # Determine the dominant emotion
        print(result[0]['emotion'])
        emotion = result[0]['dominant_emotion']

        # Draw rectangle around face and label with predicted emotion
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
        cv2.putText(frame, emotion, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)

    # Display the resulting frame
    cv2.imshow('Real-time Emotion Detection', frame)

    # Press 'q' to exit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the capture and close all windows
cap.release()
cv2.destroyAllWindows()

可以通过过滤掉置信度低于特定阈值的情绪来增加对 DeepFace 结果的置信度。以下是更新后的代码,其中包含一个添加的阈值:

import cv2
from deepface import DeepFace

# Load face cascade classifier
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Start capturing video
cap = cv2.VideoCapture('ap.mp4')

# 设置置信度阈值
confidence_threshold = 0.6  # 例如 60% 的置信度

while True:
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Convert frame to grayscale
    gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Convert grayscale frame to RGB format
    rgb_frame = cv2.cvtColor(gray_frame, cv2.COLOR_GRAY2RGB)

    # Detect faces in the frame
    faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
    for (x, y, w, h) in faces:
        # Extract the face ROI (Region of Interest)
        face_roi = rgb_frame[y:y + h, x:x + w]

        # Perform emotion analysis on the face ROI
        result = DeepFace.analyze(face_roi, actions=['emotion'], enforce_detection=False)

        # Get the dominant emotion and its confidence
        dominant_emotion = result[0]['dominant_emotion']
        confidence = result[0]['emotion'][dominant_emotion]

        # Only display the emotion if confidence is above the threshold
        if confidence > confidence_threshold:
            # Draw rectangle around face and label with predicted emotion
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)
            cv2.putText(frame, dominant_emotion, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)

    # Display the resulting frame
    cv2.imshow('Real-time Emotion Detection', frame)

    # Press 'q' to exit
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the capture and close all windows
cap.release()
cv2.destroyAllWindows()

在此代码中:

  1. 我们设置了一个 confidence_threshold 来定义显示情绪所需的最小置信度级别。
  2. 我们从 DeepFace.analyze() 的结果中提取了 dominant_emotion 和它的 confidence
  3. 我们仅在 confidence 高于 confidence_threshold 时才显示检测到的情绪。

通过调整 confidence_threshold ,可以控制在图像上绘制情绪标签之前的置信度级别。更高的阈值(例如,0.8 或 0.9)将导致更少但可能更准确的情绪检测,而较低的阈值将显示更多检测结果,但可能包括更多误报。

标签:python,opencv,machine-learning,computer-vision,deepface
From: 78834690

相关文章

  • 【香橙派系列教程】(七)香橙派下的Python3安装
    【七】香橙派下的Python3安装为接下来的Linux图像识别智能垃圾桶做准备。图像处理使用京东SDK只支持pyhton和Java接口,目的是引入C语言的Python调用,感受大厂做的算法bug此接口是人工智能接口,京东识别模型是通过训练后的模型,精准度取决于训练程度,人工智能范畴在常规嵌入式......
  • vnpy,一个不可思议的Python库!
    vn.py是一个开源的Python交易编程框架,旨在帮助程序员快速搭建属于自己的量化交易平台。该框架支持股票、期货、外汇等多种金融产品的交易,提供了从数据获取、策略开发到交易执行的全流程支持。如何安装vnpy首先,要使用vnpy,您需要通过Python的包管理工具pip来安装它。以下......
  • Python回溯算法
    回溯算法回溯算法是一种系统的搜索算法,用于解决诸如排列组合、子集生成、图的路径、棋盘问题等问题。其核心思想是通过递归尝试各种可能的解决方案,遇到不满足条件的解时则回退(回溯),继续尝试其他可能性,直到找到所有的解决方案或确认无解。主要步骤:选择路径:在当前步骤选择一个可......
  • [python]使用gunivorn部署fastapi服务
    前言Gunicorn是一种流行的WSGIHTTP服务器,常用于部署Django和Flask等PythonWeb框架程序。Gunicorn具有轻量级、高稳定性和高性能等特性,可以轻易提高PythonWSGIApp运行时的性能。基本原理Gunicorn采用了pre-fork模型,也就是一个工作进程和多个worker进程的工作模式。在这个模......
  • python十六进制编辑器
    源代码:importtkinterastkfromtkinterimportfiledialogimportstructimportbinasciiimportosclassHexEditor:def__init__(self,master):self.master=masterself.master.title("十六进制编辑器")self.master.configure(bg......
  • python项目学习 mediapipe手势识别 opencv可视化显示
    importcv2importmediapipeimportnumpydefget_angle(vector1,vector2):#角度计算angle=numpy.dot(vector1,vector2)/(numpy.sqrt(numpy.sum(vector1*vector1))*numpy.sqrt(numpy.sum(vector2*vector2)))#cos(angle)=向量的点乘/向量的模angle=nump......
  • 【优秀python大屏】基于python flask的广州历史天气数据应用与可视化大屏
    摘要气象数据分析在各行各业中扮演着重要的角色,尤其对于农业、航空、海洋、军事、资源环境等领域。在这些领域中,准确的气象数据可以对预测未来的自然环境变化和采取行动来减轻负面影响的决策起到至关重要的作用。本系统基于PythonFlask框架,通过对气象数据的分析和处理来提供......
  • Python-MNE全套教程(官网翻译)-入门01:概述篇
    目的以牺牲深度为代价进行入门学习,简易学习基本方法开始导入相关库:#License:BSD-3-Clause#CopyrighttheMNE-Pythoncontributors.importnumpyasnpimportmne加载数据MNE-Python数据结构式基于fif格式的,但是对于其他格式也有阅读方法,如https://mne.tools/s......
  • Python-MNE全套教程(官网翻译)-入门05:关于传感器位置
    本教程描述了如何读取和绘制传感器位置,以及MNE-Python如何处理传感器的物理位置。像往常一样,我们将从导入我们需要的模块开始:frompathlibimportPathimportmatplotlib.pyplotaspltimportnumpyasnpimportmne关于montage和layout(蒙太奇和传感器布局)montage......
  • Codeforces Round 963 (Div. 2) A - C 详细题解(思路加代码,C++,Python) -- 来自灰名
    比赛链接:Dashboard-CodeforcesRound963(Div.2)-Codeforces之后有实力了再试试后面的题目,现在要做那些题,起码要理解一个多小时题目A:链接:Problem-A-Codeforces题目大意理解:        极少数不考翻译能读懂的cf题目(bushi)每个测试用例第一行一个n,......