OpenCV+Dlib+FR人脸识别和对齐内容整理

OpenCV+Dlib+FR人脸识别和对齐内容整理

环境配置

环境要求:python+opencv+face_recognition
环境配置时遇到的问题:安装dlib时失败
解决方案:

  1. 使用pip install Cmake命令安装Cmake库
  2. 使用pip install boost命令安装boost库
  3. 此时使用pip install dlib命令安装dlib库,安装成功

实例代码

1.人脸定位(仅opencv)
import cv2

def detect(filename):
    face_cascade = cv2.CascadeClassifier('/Users/wangzeyu/anaconda3/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml')
    #使用不同的xml文件,可以进行不同部位的检测,如眼睛检测、微笑检测等
    img = cv2.imread(filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
    cv2.imshow('Person Detected!', img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__ == '__main__':
    detect('test00.jpg')
2.人脸定位(face_recognition)
import face_recognition
import cv2

image = face_recognition.load_image_file("test00.jpg")
face_locations_noCNN=face_recognition.face_locations(image)
# A list of tuples of found face locations in css (top, right, bottom, left) order
# 因为返回值的顺序是这样子的,因此在后面的for循环里面赋值要注意按这个顺序来
print("face_location_noCNN:")
print(face_locations_noCNN)
face_num2=len(face_locations_noCNN)
print(face_num2)       # The number of faces
# 到这里为止,可以观察两种情况的坐标和人脸数,一般来说,坐标会不一样,但是检测出来的人脸数应该是一样的
# 也就是说face_num1 = face_num2; face_locations_useCNN 和 face_locations_noCNN 不一样
org = cv2.imread("test00.jpg")
img = cv2.imread("test00.jpg")
cv2.imshow("test00.jpg",img)  # 原始图片

for i in range(0,face_num2):
    top = face_locations_noCNN[i][0]
    right = face_locations_noCNN[i][1]
    bottom = face_locations_noCNN[i][2]
    left = face_locations_noCNN[i][3]

    start = (left, top)
    end = (right, bottom)

    color = (0,255,255)
    thickness = 2
    cv2.rectangle(org, start, end, color, thickness)
cv2.imshow("no cnn ",org)
cv2.waitKey(0)
cv2.destroyAllWindows()
3.特征点检测

需要先下载包shape_predictor_68_face_landmarks.dat

import cv2
import dlib

path = "test00.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#人脸分类器
detector = dlib.get_frontal_face_detector()
# 获取人脸检测器
predictor = dlib.shape_predictor(r"/Users/wangzeyu/anaconda3/lib/python3.6/site-packages/shape_predictor_68_face_landmarks.dat")
dets = detector(gray, 1)
for face in dets:
    shape = predictor(img, face)  # 寻找人脸的68个标定点
    # 遍历所有点,打印出其坐标,并圈出来
    for pt in shape.parts():
        pt_pos = (pt.x, pt.y)
        cv2.circle(img, pt_pos, 2, (0, 255, 0), 1)
    cv2.imshow("image", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

运行结果

1.人脸定位(仅opencv)

在这里插入图片描述

2.人脸定位(face_recognition)

在这里插入图片描述

3.特征点检测

在这里插入图片描述

相关学习资料

《OpenCV官方教程中文版(For Python)》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值