自选一幅图像,使用基于深度学习的TensorFlow模型检测其中的人脸,用cv2.dnn.readNetFromTensorflow('opencv_face_detector.pbtxt','opencv_face_detector_uint8.pb')来实现
时间: 2024-02-20 10:57:22 浏览: 244
好的,我知道了。首先,我需要导入必要的模块和库:
```python
import cv2
import numpy as np
```
然后,我需要加载模型和图像,使用模型来检测人脸并在图像上绘制矩形框。
```python
# Load the model
model = cv2.dnn.readNetFromTensorflow('opencv_face_detector_uint8.pb', 'opencv_face_detector.pbtxt')
# Load the image
image = cv2.imread('image.jpg')
# Get the image dimensions
(h, w) = image.shape[:2]
# Create a blob from the image
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
# Pass the blob through the network and get the detections
model.setInput(blob)
detections = model.forward()
# Loop over the detections
for i in range(0, detections.shape[2]):
# Get the confidence (i.e., probability) associated with the detection
confidence = detections[0, 0, i, 2]
# Filter out weak detections by ensuring the confidence is greater than the minimum confidence
if confidence > 0.5:
# Compute the (x, y)-coordinates of the bounding box for the object
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
# Draw the bounding box of the face along with the associated probability
text = "{:.2f}%".format(confidence * 100)
y = startY - 10 if startY - 10 > 10 else startY + 10
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 0, 255), 2)
cv2.putText(image, text, (startX, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
# Display the output image
cv2.imshow("Output", image)
cv2.waitKey(0)
```
这段代码会打开名为"image.jpg"的图像,并在其中检测人脸,最后在图像上绘制矩形框。请记得将图片名字替换成你自己的图片。
阅读全文