pip install torch torchvision opencv-python pillow numpy ultralytics
下载人脸检测权重(例如 YOLOv5 人脸模型):
mkdir weights
curl -L -o weights/yolov5n-face.pt https://github.com/deepcam-cn/yolov5-face/releases/download/v0.0/yolov5n-face.pt
代码:
import torch
import cv2
import numpy as np
from pathlib import Path
from PIL import Image
# 初始化 YOLOv5 人脸检测模型
model = torch.hub.load('ultralytics/yolov5', 'custom', path='weights/yolov5n-face.pt', source='github')
# 发型分类(简单规则版)
def analyze_hairstyle(face_img):
"""
这里是一个示例函数:
- 可以用亮度、面积比例等简单规则来判断发型是否正常
- 实际项目中可以换成一个分类模型(ResNet / MobileNet)
"""
gray = cv2.cvtColor(face_img, cv2.COLOR_BGR2GRAY)
mean_brightness = np.mean(gray)
h, w = gray.shape
hair_region = gray[0:int(h*0.3), :] # 取上部分区域代表头发区域
hair_darkness = np.mean(hair_region)
# 简单规则判定(可替换为CNN模型预测)
if hair_darkness < mean_brightness * 0.8:
return "发型正常"
else:
return "发型异常"
# 检测函数
def detect_and_analyze(image_path):
img = Image.open(image_path)
results = model(img, size=640)
detections = results.pandas().xyxy[0]
img_cv = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
for _, row in detections.iterrows():
x1, y1, x2, y2, conf, cls = map(int, [row['xmin'], row['ymin'], row['xmax'], row['ymax'], row['class']])
face = img_cv[y1:y2, x1:x2]
if face.size == 0:
continue
status = analyze_hairstyle(face)
color = (0, 255, 0) if status == "发型正常" else (0, 0, 255)
# 绘制检测框
cv2.rectangle(img_cv, (x1, y1), (x2, y2), color, 2)
cv2.putText(img_cv, f"{status}", (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, color, 2)
cv2.imshow("Hair Detection", img_cv)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 示例运行
if __name__ == "__main__":
detect_and_analyze("test.jpg") # 你的人脸测试图片路径
7632

被折叠的 条评论
为什么被折叠?



