老年人情绪标注实践:构建七种情绪数据集

课程目标

  • 掌握图像分类标注的实践方法,聚焦老年人七种情绪(愤怒、厌恶、害怕、开心、伤心、惊讶、中性)

  • 使用Python和标注工具完成老年人情绪图片标注

  • 构建结构化的情绪数据集,适合机器学习使用

  • 理解情绪标注的挑战和质量控制


第31学时:情绪标注基础与准备

1. 老年人情绪标注简介

1.1 情绪标注的背景

  • 定义:为面部图片分配情绪标签,用于训练情绪识别模型。

  • 七种情绪:愤怒(angry)、厌恶(disgust)、害怕(fear)、开心(happy)、伤心(sad)、惊讶(surprise)、中性(neutral)。

  • 应用

    • 老年护理:监测情绪,辅助心理健康。

    • 人机交互:开发情绪敏感的智能系统。

1.2 老年人情绪标注的特点

  • 表情微妙:皱纹、皮肤松弛可能掩盖情绪。

  • 数据稀缺:公开的老年人情绪数据集较少(如FER-2013老年样本有限)。

  • 文化差异:不同文化背景的老年人表情表达不同。

  • 伦理问题:需确保图片来源合法,遵守隐私和知情同意原则。

1.3 挑战与解决方案

  • 主观性:情绪判断因人而异。

    • 解决:制定详细的标注指南。

  • 一致性:多人标注可能不一致。

    • 解决:多轮审查,使用一致性指标。

  • 数据获取:老年图片难收集。

    • 解决:使用公开数据集、模拟数据或志愿者图片。


2. 数据准备与标注指南

2.1 数据准备

  • 图片来源

    • 公开数据集:FER-2013、CK+(筛选老年样本)。

    • 模拟数据:从视频或公开图片截取老年面部图像。

    • 志愿者:需获得知情同意。

  • 文件夹结构

    • 创建 elderly_emotion_images/,存放10-15张老年人面部图片。

    • 命名建议:happy_001.jpg, sad_002.jpg

  • 要求

    • 图片清晰,面部占主要区域。

    • 涵盖多种情绪、性别、年龄段。

2.2 标注指南

  • 情绪定义

    • 愤怒:眉毛下压、嘴角向下、瞪眼。

    • 厌恶:鼻子皱起、嘴角扭曲。

    • 害怕:眼睛睁大、眉毛上扬。

    • 开心:嘴角上扬、眼角有鱼尾纹。

    • 伤心:嘴角下垂、眉毛内侧上扬。

    • 惊讶:眼睛睁大、嘴巴张开。

    • 中性:面部放松,无明显表情。

  • 注意事项

    • 优先考虑面部特征,避免受背景或姿势干扰。

    • 对于模糊表情,参考上下文或标记为“中性”。

2.3 输出格式

  • CSV:记录文件名和情绪标签。

    • 示例:

      filename,emotion
      happy_001.jpg,happy
      sad_002.jpg,sad

  • JSON(最终数据集):包含文件名、标签、路径。


3. Python预标注实践

3.1 任务:生成初始情绪标签

  • 目标:为图片文件夹中的图像生成预标注CSV。

  • 准备

    • 安装pandas:pip install pandas

    • 确保 elderly_emotion_images/ 包含图片。

  • 代码:扫描图片,输入情绪标签。

    import os
    import pandas as pd
    
    # 情绪类别
    emotions = ["angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"]
    
    # 图片文件夹
    image_dir = "elderly_emotion_images/"
    image_files = [f for f in os.listdir(image_dir) if f.endswith((".jpg", ".png"))]
    
    # 预标注
    data = {"filename": [], "emotion": []}
    for img in image_files:
        print(f"\n图片:{img}")
        print("可选情绪:", ", ".join(emotions))
        label = input("请输入情绪标签(或留空跳过):").lower()
        if label in emotions:
            data["filename"].append(img)
            data["emotion"].append(label)
        else:
            print("无效标签,跳过此图片")
    
    # 保存CSV
    df = pd.DataFrame(data)
    df.to_csv("emotion_labels.csv", index=False)
    print("\n预标注完成,保存到 emotion_labels.csv")
    print(df)

3.2 操作步骤

  1. 将图片放入 elderly_emotion_images/

  2. 运行代码,逐张输入情绪标签。

  3. 检查 emotion_labels.csv,确保格式正确。

3.3 注意事项

  • 标签输入保持一致(全小写)。

  • 图片文件名避免特殊字符。

  • 若无真实图片,可用占位符文件名模拟。


4. 练习与讨论

4.1 练习

  • 任务1:添加3张新图片,更新 emotion_labels.csv

  • 任务2:编写函数统计情绪分布。

    def count_emotions(df):
        counts = df["emotion"].value_counts()
        print("情绪统计:")
        for emotion, count in counts.items():
            print(f"{emotion}: {count} 张")
    count_emotions(df)

4.2 讨论

  • 老年人情绪标注的难点是什么?(如微妙表情)

  • 如何设计指南以减少主观性?

  • 收集老年人图片的伦理注意事项?


第32学时:标注实践与数据集构建

1. LabelImg情绪标注实践

1.1 任务:验证与修正情绪标签

  • 目标:使用LabelImg为图片标注情绪,验证CSV标签。

  • 准备

    • 安装LabelImg:pip install labelImg

    • 使用 elderly_emotion_images/emotion_labels.csv

    • 创建 emotion_classes.txt

      angry
      disgust
      fear
      happy
      sad
      surprise
      neutral

1.2 操作步骤

  1. 启动LabelImg:labelimg

  2. 打开 elderly_emotion_images/

  3. 加载 emotion_classes.txt

  4. 标注:

    • 选择图片,点击“Create RectBox”(框选面部,仅为记录情绪)。

    • 选择情绪类别,保存XML。

  5. 对比XML与CSV标签,修正不一致处。

1.3 Python代码:更新CSV

import os
import xml.etree.ElementTree as ET
import pandas as pd

# 加载现有CSV
csv_file = "emotion_labels.csv"
df = pd.read_csv(csv_file) if os.path.exists(csv_file) else pd.DataFrame({"filename": [], "emotion": []})

# 解析XML
image_dir = "elderly_emotion_images/"
xml_files = [f for f in os.listdir(image_dir) if f.endswith(".xml")]
for xml_file in xml_files:
    tree = ET.parse(os.path.join(image_dir, xml_file))
    root = tree.getroot()
    filename = root.find("filename").text
    label = root.find("object/name").text
    if filename in df["filename"].values:
        df.loc[df["filename"] == filename, "emotion"] = label
    else:
        df = pd.concat([df, pd.DataFrame({"filename": [filename], "emotion": [label]})], ignore_index=True)

# 保存更新
df.to_csv("emotion_labels_updated.csv", index=False)
print("更新完成,保存到 emotion_labels_updated.csv")
print(df)

2. 数据集整合与验证

2.1 任务:构建标准情绪数据集

  • 目标:生成JSON格式数据集,验证完整性。

  • 代码:整合CSV,输出JSON。

    import pandas as pd
    import json
    import os
    
    # 加载CSV
    df = pd.read_csv("emotion_labels_updated.csv")
    
    # 验证
    emotions = ["angry", "disgust", "fear", "happy", "sad", "surprise", "neutral"]
    image_dir = "elderly_emotion_images/"
    invalid_rows = []
    for idx, row in df.iterrows():
        if row["emotion"] not in emotions:
            invalid_rows.append((row["filename"], "无效标签"))
        if not os.path.exists(os.path.join(image_dir, row["filename"])):
            invalid_rows.append((row["filename"], "图片不存在"))
    
    if invalid_rows:
        print("发现问题:")
        for filename, issue in invalid_rows:
            print(f"{filename}: {issue}")
    else:
        print("数据验证通过!")
    
    # 整合为JSON
    data = {
        "dataset": "elderly_emotion",
        "images": [
            {
                "filename": row["filename"],
                "emotion": row["emotion"],
                "path": os.path.join(image_dir, row["filename"])
            }
            for _, row in df.iterrows()
        ]
    }
    
    # 保存
    with open("emotion_dataset.json", "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=2)
    
    print("\n数据集保存到 emotion_dataset.json")

2.2 输出示例

  • emotion_dataset.json

    {
      "dataset": "elderly_emotion",
      "images": [
        {
          "filename": "happy_001.jpg",
          "emotion": "happy",
          "path": "elderly_emotion_images/happy_001.jpg"
        },
        ...
      ]
    }

2.3 验证

  • 检查JSON是否包含所有图片。

  • 确保标签在七种情绪范围内。


3. 综合练习

3.1 任务:扩展数据集

  • 添加5张新图片,重复标注流程。

  • 更新CSV和JSON。

  • 统计情绪分布:

    def count_emotions(df):
        counts = df["emotion"].value_counts()
        print("情绪分布:")
        for emotion, count in counts.items():
            print(f"{emotion}: {count} 张")
    count_emotions(df)

3.2 任务:模拟多人标注

  • 两人独立标注3张图片,比较结果,计算一致率。

  • 若有分歧,讨论并统一标签。


4. 总结与课后任务

4.1 总结

  • 老年人情绪标注为健康监测提供数据支持。

  • 结合Python和LabelImg可高效完成分类标注。

  • 数据集构建需注重验证和一致性。

  • 下一步:学习自动化预标注或情绪识别模型训练。

4.2 课后任务

  1. 实践:收集10张老年人面部图片,完成情绪标注,生成JSON。

  2. 实践:使用Roboflow上传数据集,尝试在线标注。

  3. 探索:研究FER-2013数据集,分析老年样本特点。

  4. 思考:如何优化情绪标注流程以提高效率?


参考资源

作者:信息技术教研室  创建时间:2025-06-20 01:08
最后编辑:信息技术教研室  更新时间:2025-08-13 10:53