opencv实现级联分类器检测人脸
·
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
本文使用opencv和级联分类器简单实现人脸检测
一、去github下载级联分类器文件(.xml)
github链接: 级联分类器
如下面是github对应界面,里面其实有很多检测文件,包括检测猫脸,人眼,人身体等等,大家可自行尝试。点击你需要下载的文档,进入后右上角有下载按钮,当然,你也可以新建一个txt文档,复制内容,再修改后缀为.xml。
二、使用步骤
代码如下(示例):
import cv2
import numpy as np
def load_image(image_path):
"""
读取图像文件。
参数:
- image_path: 图像文件的路径。
返回:
- img: 读取的图像,失败时返回None。
"""
try:
img = cv2.imread(image_path)
if img is None:
print("Error: 图像文件读取失败,请检查路径是否正确。")
return None
return img
except Exception as e:
print(f"图像文件读取时发生异常: {str(e)}")
return None
def draw_heart_shape(image, center, size, color, thickness):
"""
在图像上绘制爱心形状。
参数:
- image: 输入图像。
- center: 爱心中心点坐标 (x, y)。
- size: 爱心的大小 (宽度, 高度)。
- color: 爱心的颜色 (B, G, R)。
- thickness: 填充厚度,-1 表示填充整个形状。
"""
# 定义爱心的轮廓点
points = np.array([
[center[0] - size[0], center[1] - size[1]],
[center[0] - size[0] * 0.7, center[1] - size[1] * 0.5],
[center[0] - size[0] * 0.3, center[1] - size[1] * 0.5],
[center[0], center[1]],
[center[0] + size[0] * 0.3, center[1] - size[1] * 0.5],
[center[0] + size[0] * 0.7, center[1] - size[1] * 0.5],
[center[0] + size[0], center[1] - size[1]],
[center[0] + size[0] * 0.7, center[1] - size[1] * 0.3],
[center[0] + size[0] * 0.3, center[1] - size[1] * 0.3],
[center[0], center[1]],
[center[0] - size[0] * 0.3, center[1] - size[1] * 0.3],
[center[0] - size[0] * 0.7, center[1] - size[1] * 0.3]
], dtype=np.int32)
# 使用cv2.fillPoly填充爱心形状
cv2.fillPoly(image, [points], color=color, lineType=cv2.LINE_AA)
def detect_and_draw_faces(image_path, cascade_path):
"""
检测并绘制人脸爱心框。
参数:
- image_path: 图像文件的路径。
- cascade_path: 级联分类器文件的路径。
"""
# 加载图像
img = load_image(image_path)
if img is None:
return
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 加载预训练的分类器
face_cascade = cv2.CascadeClassifier(cascade_path)
if face_cascade.empty():
print("Error: 无法加载级联分类器。")
return
# 检测人脸
# 调整参数以提高检测精度
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(30, 30))
# 如果未检测到人脸,则输出提示信息
if len(faces) == 0:
print("Info: 未检测到人脸。")
else:
# 绘制人脸爱心框
for (x, y, w, h) in faces:
# 计算爱心中心点
center_x = x + w // 2
center_y = y + h // 2
# 计算爱心大小
heart_size = (w // 2, h // 2)
# 绘制爱心
draw_heart_shape(img, (center_x, center_y), heart_size, (255, 192, 203), -1)
# 显示结果
# 调整结果大小再显示
cv2.imshow("Face Detection", cv2.resize(img, (800, 600)))
cv2.waitKey(0)
cv2.destroyAllWindows()
# 定义变量存储路径和参数
image_path = r"C:\Users\86188\Pictures\Screenshots\man.png"
cascade_path = r"C:\Users\86188\Downloads\haarcascade_frontalface_alt2.xml"
# 调用函数进行人脸检测和绘制
detect_and_draw_faces(image_path, cascade_path)
总结
代码注意修改为自己保存的.xml,文件路径和图片路径,这里我使用的绝对路径。我的运行效果如下,本来是画爱心,但成了抽象的眉毛。

更多推荐

所有评论(0)