|
10、OpenCV + Dlib人脸检测与对人脸位置进行校准与裁剪
人脸校准:使用 Dlib 的实时姿势估计与 OpenCV 的仿射变换来尝试使眼睛和下唇在每个图像上出现在相同位置
- # -*- coding: utf-8 -*-
- __author__ = u'东方耀 微信:dfy_88888'
- __date__ = '2020/2/24 上午9:34'
- __product__ = 'PyCharm'
- __filename__ = 'dfy_demo01'
- import numpy as np
- import os
- import cv2
- import dlib
- # current word dict
- print(os.getcwd())
- # 定义人脸检测器
- detector = dlib.get_frontal_face_detector()
- predictor_path = 'models/shape_predictor_5_face_landmarks.dat'
- # 定义人脸关键点检测器
- sp = dlib.shape_predictor(predictor_path)
- # OpenCV + Dlib对人脸位置进行校准 查找脸部位置
- fo = dlib.full_object_detections()
- # img_path = '/home/dfy888/DataSets/CelebA/img_align_celeba/100205.jpg'
- img_path = './testimgs/img01.png'
- # img_path = '/home/dfy888/DataSets/VOCdevkit_widerface_dfy/VOC2020/JPEGImages/9--Press_Conference_9_Press_Conference_Press_Conference_9_91.jpg'
- img_data = cv2.imread(img_path)
- print(img_data.shape)
- img = img_data[:, :, ::-1]
- # 1、人脸检测:使用 Dlib 中预先训练的模型检测面部
- # 这里 0 或 1的区别是? 0是只检测一个人脸 1是所有的
- dets = detector(img, 1)
- num_faces = len(dets)
- print('检测出%d个人脸' % num_faces)
- if num_faces > 0:
- for i in range(num_faces):
- # 获取人脸的坐标 注意img与img_data的区别
- x1 = dets[i].left()
- y1 = dets[i].top()
- x2 = dets[i].right()
- y2 = dets[i].bottom()
- cv2.rectangle(img_data, (x1, y1), (x2, y2), (0, 0, 255), 2)
- landmarks = np.matrix([[p.x, p.y] for p in sp(img, dets[i]).parts()])
- print('每个人脸的关键点个数:', len(landmarks))
- for point in landmarks:
- pos = (point[0, 0], point[0, 1])
- # print('pos-', pos)
- cv2.circle(img_data, pos, 1, color=(0, 255, 255), thickness=3)
- # 下面开始clip 查找脸部位置
- fo.append(sp(img, dets[i]))
- image = dlib.get_face_chip(img, fo[i], size=139)
- image = image[:, :, ::-1]
- cv2.imshow('chip shape:%s' % str(image.shape), image)
- cv2.waitKey(0)
- pass
- cv2.imshow('origianl+face', img_data)
- cv2.waitKey(0)
复制代码
|
|