使用mediapipe和OpenCV 实现简单人脸检测

#人脸检测
# opencv
import cv2
# mediapipe ai工具包
import mediapipe as mp
# 进度条库
from tqdm import tqdm
import time
import matplotlib.pyplot as plt



# 定义一个可视化图像函数
def look_img(img):
    img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.imshow
    plt.show()


# 导入BlazeFace模型
mp_face_detection = mp.solutions.face_detection
model = mp_face_detection.FaceDetection(
    min_detection_confidence=0.5,  # 置信度阈值,过滤掉小于置信度的预测框
    model_selection=1,  # 选择模型,0 适用于人脸离摄像头比较近(2米内),1 适用于比较远(5米以内)
)
# 导入可视化函数以及可视化样式
mp_drawing=mp.solutions.drawing_utils
# 关键点样式
keypoint_style=mp_drawing.DrawingSpec(thickness=5,circle_radius=3,color=(0,255,0))
# 人脸预测框样式
bbox_style=mp_drawing.DrawingSpec(thickness=5,circle_radius=3,color=(255,0,0))



# 读入图像
img = cv2.imread('images/img.png')
# BGR转RGB
img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# 将RGB输入模型预测结果
results=model.process(img_RGB)

# 可视化人脸框和人脸关键点
annotated_image=img.copy()
for detection in results.detections:
    mp_drawing.draw_detection(annotated_image,
                              detection,
                              keypoint_drawing_spec=keypoint_style,
                              bbox_drawing_spec=bbox_style)
look_img(annotated_image)
cv2.imwrite('Test.jpg',annotated_image)

素材

处理效果

posted @ 2022-07-22 15:34  木子欢儿  阅读(41)  评论(0编辑  收藏  举报