三种算法实现深度学习python人脸检测代码
时间: 2023-07-13 08:28:41 浏览: 68
以下是三种深度学习算法实现人脸检测的Python代码示例:
1. 基于SSD算法的人脸检测代码:
```python
import cv2
# 加载模型
net = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'res10_300x300_ssd_iter_140000.caffemodel')
# 加载图像
img = cv2.imread('test.jpg')
# 进行预处理
blob = cv2.dnn.blobFromImage(cv2.resize(img, (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]
if confidence > 0.5:
box = detections[0, 0, i, 3:7] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
(startX, startY, endX, endY) = box.astype("int")
cv2.rectangle(img, (startX, startY), (endX, endY), (0, 0, 255), 2)
# 显示图像
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
2. 基于YOLO算法的人脸检测代码:
```python
import cv2
# 加载模型
net = cv2.dnn.readNet('yolov3-tiny.weights', 'yolov3-tiny.cfg')
# 加载标签
with open('coco.names', 'r') as f:
labels = [line.strip() for line in f.readlines()]
# 加载图像
img = cv2.imread('test.jpg')
# 进行预处理
blob = cv2.dnn.blobFromImage(img, 1/255.0, (416, 416), swapRB=True, crop=False)
# 进行预测
net.setInput(blob)
outputs = net.forward()
# 绘制矩形框
for output in outputs:
for detection in output:
scores = detection[5:]
classId = np.argmax(scores)
confidence = scores[classId]
if confidence > 0.5 and classId == 0:
box = detection[0:4] * np.array([img.shape[1], img.shape[0], img.shape[1], img.shape[0]])
(centerX, centerY, width, height) = box.astype("int")
startX = int(centerX - (width / 2))
startY = int(centerY - (height / 2))
endX = int(centerX + (width / 2))
endY = int(centerY + (height / 2))
cv2.rectangle(img, (startX, startY), (endX, endY), (0, 0, 255), 2)
# 显示图像
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
3. 基于MTCNN算法的人脸检测代码:
```python
import cv2
from mtcnn import MTCNN
# 加载模型
detector = MTCNN()
# 加载图像
img = cv2.imread('test.jpg')
# 进行预测
results = detector.detect_faces(img)
# 绘制矩形框
for result in results:
x, y, w, h = result['box']
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
# 显示图像
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
```
以上代码中,分别使用了基于SSD、YOLO和MTCNN算法进行人脸检测。其中,SSD和YOLO都是基于深度学习的目标检测算法,MTCNN则是专门为人脸检测设计的算法。在使用前需要加载对应的模型和标签,并且进行图像预处理和后处理。在预测完成后,可以通过绘制矩形框来标记检测到的人脸。