在Python中,识别图片中的人脸并获取人脸区域的坐标,通常可以使用OpenCV库结合Haar特征分类器或更先进的DNN(深度神经网络)模型来实现。
安装OpenCV依赖
pip install opencv-python
Haar特征分类器
使用OpenCV和预训练的Haar级联分类器来识别图片中人脸并获取其坐标:
import cv2
def detect_faces(image_path):
# 加载预训练的Haar级联分类器
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
# 读取图片
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 检测图片中的人脸
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
# 遍历检测到的所有人脸
for (x, y, w, h) in faces:
# 在原图上绘制矩形框
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
# 显示结果图片
cv2.imshow('img', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 打印人脸区域的坐标
for (x, y, w, h) in faces:
print(f"Face found at: Left: {x} Top: {y} Right: {x+w} Bottom: {y+h}")
# 调用函数,传入图片路径
detect_faces('path_to_your_image.jpg')
上述代码中,detect_faces
函数接受一个图片路径作为参数,并使用OpenCV的CascadeClassifier
来加载一个预训练的Haar级联分类器,该分类器用于检测图片中的人脸。然后,它读取图片,将其转换为灰度图,并使用detectMultiScale
方法检测人脸。检测到的每个人脸都会以矩形框的形式在原图上绘制出来,并打印出其坐标。
DNN(深度神经网络)模型
OpenCV提供了几个预训练的人脸检测模型,其中一个常用的模型是基于Caffe框架的resnet10_300x300_ssd_iter_140000.caffemodel和对应的配置文件deploy.prototxt。
下载模型:
https://github.com/opencv/opencv/tree/4.1.2/samples/dnn/face_detector
使用OpenCV和DNN模型来识别图片中人脸:
import cv2
import numpy as np
def detect_faces(image_path):
# 加载预训练模型
net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000_fp16.caffemodel')
# 读取图像
image = cv2.imread(image_path)
(h, w) = image.shape[:2]
# 图像预处理
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
(300, 300), (104.0, 177.0, 123.0))
# 设置网络输入
net.setInput(blob)
# 进行检测
detections = net.forward()
# 绘制检测框
for i in range(0, detections.shape[2]):
confidence = detections[0, 0, i, 2]
print("confidence: {:.3f}".format(confidence))
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Face Detection', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 调用函数,传入图片路径
detect_faces('path_to_your_image.jpg')