在人工智能训练中,图像情感分析和图像实体分析是两个重要的应用场景。高质量的图像数据标注对于训练情感识别模型和目标检测/语义分割模型至关重要。
本指南将详细介绍:
图像情感分析(Emotion Recognition)是计算机视觉用于识别人脸情绪的任务,例如:
数据标注任务主要包括:
LabelImg 是一种常用于目标检测的标注工具,可以用于标注人脸位置(Bounding Box)。
pip install labelImg
labelImg
如果已经有预训练的人脸检测和情感识别模型,可以自动标注数据。
pip install opencv-python dlib numpy
import cv2
import numpy as np
from deepface import DeepFace
# 加载人脸检测模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
# 读取图像
image = cv2.imread("emotion.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 识别人脸
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 遍历所有检测到的人脸
for (x, y, w, h) in faces:
face = image[y:y+h, x:x+w]
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 进行情感分析
result = DeepFace.analyze(face, actions=["emotion"], enforce_detection=False)
emotion = result[0]["dominant_emotion"]
# 标注情感类别
cv2.putText(image, emotion, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (255, 0, 0), 2)
cv2.imwrite("emotion_labeled.jpg", image)
print("情感标注完成")
输出:
emotion_labeled.jpg
:包含人脸检测框和情感类别的标注图像import json
annotations = {
"image": "emotion.jpg",
"faces": [
{"bbox": [100, 120, 80, 80], "emotion": "happy"},
{"bbox": [200, 150, 90, 90], "emotion": "sad"}
]
}
with open("emotion_annotations.json", "w") as f:
json.dump(annotations, f, indent=4)
print("情感标注数据已保存")
输出格式(JSON):
{
"image": "emotion.jpg",
"faces": [
{"bbox": [100, 120, 80, 80], "emotion": "happy"},
{"bbox": [200, 150, 90, 90], "emotion": "sad"}
]
}
图像实体分析(Entity Recognition)用于定位和识别复杂场景中的多个类别对象,如:
LabelMe 是用于语义分割和目标检测的标注工具。
pip install labelme
labelme
如果有预训练模型,可以自动标注目标物体。
pip install ultralytics segment-anything
from ultralytics import YOLO
import cv2
# 加载 YOLO 预训练模型
model = YOLO("yolov5s.pt")
# 读取图像
image = cv2.imread("entity.jpg")
# 进行目标检测
results = model(image)
# 绘制检测框
for result in results.xyxy[0]:
x1, y1, x2, y2, confidence, class_id = result
label = model.names[int(class_id)]
cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
cv2.putText(image, label, (int(x1), int(y1) - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)
cv2.imwrite("entity_labeled.jpg", image)
print("目标检测标注完成")
输出:
entity_labeled.jpg
:带有目标检测框和类别的图像import json
coco_annotations = {
"images": [{"id": 1, "file_name": "entity.jpg"}],
"annotations": [
{"image_id": 1, "bbox": [50, 50, 100, 200], "category_id": 1},
{"image_i