yolo v5识别人物情绪

复制代码
# 安装 YOLOv5 依赖
git clone https://github.com/ultralytics/yolov5
cd yolov5
pip install -r requirements.txt
  1. 加载 YOLOv5-face 模型用于五官检测
python 复制代码
from yolov5_face.face_detector import YoloDetector
import cv2

# 初始化模型(下载好模型或替换为你自己的路径)
model_path = "weights/yolov5s-face.pt"
detector = YoloDetector(model_path, device='cuda')  # 或 'cpu'

img = cv2.imread("test.jpg")
bboxes = detector.predict(img)

for box in bboxes:
    x1, y1, x2, y2, conf, landmarks = box
    # landmarks = [left_eye, right_eye, nose, left_mouth, right_mouth]
    cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)
    for (x, y) in landmarks:
        cv2.circle(img, (int(x), int(y)), 2, (0,255,0), -1)
  1. 加载情绪识别模型(CNN)
python 复制代码
import torch
import torch.nn as nn
from torchvision import transforms
from PIL import Image

# 假设我们使用一个训练好的 FER 模型
class EmotionCNN(nn.Module):
    def __init__(self):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(1, 32, 3), nn.ReLU(),
            nn.MaxPool2d(2),
            nn.Conv2d(32, 64, 3), nn.ReLU(),
            nn.AdaptiveAvgPool2d(1),
            nn.Flatten(),
            nn.Linear(64, 7)  # 7类表情
        )

    def forward(self, x):
        return self.net(x)

emotion_model = EmotionCNN()
emotion_model.load_state_dict(torch.load("emotion_model.pth", map_location="cpu"))
emotion_model.eval()

transform = transforms.Compose([
    transforms.Resize((48, 48)),
    transforms.Grayscale(),
    transforms.ToTensor()
])

# 裁剪人脸区域
face_crop = img[y1:y2, x1:x2]
face_pil = Image.fromarray(cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB))
input_tensor = transform(face_pil).unsqueeze(0)

with torch.no_grad():
    output = emotion_model(input_tensor)
    pred = torch.argmax(output, dim=1).item()

emotions = ["愤怒", "厌恶", "恐惧", "高兴", "难过", "惊讶", "平静"]
emotion_label = emotions[pred]
cv2.putText(img, emotion_label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)
  1. 完整流程打包整合
python 复制代码
def detect_face_and_emotion(image_path):
    img = cv2.imread(image_path)
    faces = detector.predict(img)
    
    for box in faces:
        x1, y1, x2, y2, conf, landmarks = box
        face_crop = img[y1:y2, x1:x2]
        face_pil = Image.fromarray(cv2.cvtColor(face_crop, cv2.COLOR_BGR2RGB))
        input_tensor = transform(face_pil).unsqueeze(0)
        output = emotion_model(input_tensor)
        pred = torch.argmax(output, dim=1).item()
        emotion_label = emotions[pred]
        
        # 显示框和文字
        cv2.rectangle(img, (x1, y1), (x2, y2), (255,0,0), 2)
        cv2.putText(img, emotion_label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,255), 2)
    
    cv2.imshow("Result", img)
    cv2.waitKey(0)
相关推荐
向哆哆5 天前
高精度织物缺陷检测数据集(适用YOLO系列/1000+标注)(已标注+划分/可直接训练)
yolo·目标检测
前网易架构师-高司机5 天前
带标注的驾驶员安全带识别数据集,识别率99.5%,可识别有无系安全带,支持yolo,coco json,pascal voc xml格式
xml·yolo·数据集·交通·安全带
向哆哆6 天前
粉尘环境分类检测千张图数据集(适用YOLO系列)(已标注+划分/可直接训练)
yolo·分类·数据挖掘
琅琊榜首20206 天前
移动端AI挂机新范式:YOLOv8+NCNN实现无Root视觉自动化
人工智能·yolo·自动化
智驱力人工智能6 天前
地铁隧道轨道障碍物实时检测方案 守护城市地下动脉的工程实践 轨道障碍物检测 高铁站区轨道障碍物AI预警 铁路轨道异物识别系统价格
人工智能·算法·yolo·目标检测·计算机视觉·边缘计算
智驱力人工智能6 天前
机场鸟类活动智能监测 守护航空安全的精准工程实践 飞鸟检测 机场鸟击预防AI预警系统方案 机场停机坪鸟类干扰实时监测机场航站楼鸟击预警
人工智能·opencv·算法·安全·yolo·目标检测·边缘计算
前端摸鱼匠7 天前
YOLOv8使用 Ultralytics 内置功能简化格式转换:介绍如何使用 yolo mode=data 等相关功能或辅助工具来加速和简化数据格式的准备工作
人工智能·yolo·目标检测·机器学习·目标跟踪·视觉检测
hans汉斯7 天前
《数据挖掘》期刊推介&征稿指南
图像处理·人工智能·算法·yolo·数据挖掘·超分辨率重建·汉斯出版社
卓越软件开发7 天前
毕设全栈开发一条龙:Java/SpringBoot/Vue/ 小程序 / Python / 安卓 / AI 图像识别 人脸检测 车牌识别 YOLO
开发语言·spring boot·python·yolo·小程序·毕业设计·课程设计
向哆哆7 天前
单车/共享单车目标检测数据集(适用YOLO系列)(已标注+划分/可直接训练)
人工智能·yolo·目标检测