OpenCV/Dlib/face_recognition 人脸检测及人脸对齐

  • 一、结果展示

OpenCV

 

Dlib+face_recognition

Dlib 

  • 二、过程实现

  • 安装opencv

在终端直接安装,清华源更快点,pip install opencv-python也行

pip install -i https://pypi.tuna.tsinghua.edu.cn/simple opencv-python
  • opencv人脸检测

确定python路径(终端输入where python3.9)

/Users/yangqianyi/Documents/Anaconda3/anaconda3/bin/python3.9

我习惯了所以用notebook写的。不过不建议用notebook,mac会出现无法关闭弹出框的现象,调试也很麻烦。

import cv2
#根据自己的python路径修改
def detect(filename):
    face_cascade=cv2.CascadeClassifier('/Users/yangqianyi/Documents/Anaconda3/anaconda3/lib/python3.9/site-packages/cv2/data/haarcascade_frontalface_default.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('/Users/yangqianyi/Downloads/test.jpg')
  •  dlib+face_recognization人脸检测

face_recognization是世界上最简洁的人脸识别库,github上最主流的人脸识别工具包之一,基于dlib中的深度学习模型,比opencv准确性更高。

pip安装的时候很慢,不过就等着吧,如果掉了重安一下就行了

pip install cmake
pip install dlib
pip install face_recognition
import face_recognition
import cv2
image = face_recognition.load_image_file("/Users/yangqianyi/Downloads/test.jpg")
face_locations_noCNN=face_recognition.face_locations(image)

face_recognition.face_locations(image,model='cnn')
print("face_location_noCNN:")
print(face_locations_noCNN)
face_num2=len(face_locations_noCNN)
print(face_num2)

org = cv2.imread("/Users/yangqianyi/Downloads/test.jpg")
img = cv2.imread("/Users/yangqianyi/Downloads/test.jpg")
cv2.imshow("/Users/yangqianyi/Downloads/test.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()

  • dlib人脸对齐 

需要先下载预训练模型:

shape_predictor_68_face_landmarks.dat

shape_predictor_5_face_landmarks.dat

链接: https://pan.baidu.com/s/1b1mXrx4T2649styO2KTVbQ 提取码: 3dar 
--来自百度网盘超级会员v6的分享

 放在python路径下的site-packages⾥

(/Users/yangqianyi/Documents/Anaconda3/anaconda3/bin/python3.9/site-packages)

import cv2
import dlib
path = "/Users/yangqianyi/Downloads/test.jpg"
#读取图⽚
img = cv2.imread(path)
#灰度化处理
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#获得脸部位置检测器
detector = dlib.get_frontal_face_detector()
# 初步⼈脸检测,框出矩形。返回值是<class 'dlib.dlib.rectangle'>,即⼀个矩形,表示 为能够唯⼀表示这个⼈脸矩形框两个点坐标:左上⻆(x1,y1)、右下⻆(x2,y2
dets = detector(gray, 1)
# 使⽤模型构建特征提取器,返回5/68个特征点的位置 #此处路径是⾃⼰的python路径下site-packages位置
predictor =dlib.shape_predictor(r"/Users/yangqianyi/Documents/Anaconda3/anaconda3/lib/python3.9/site-packages/shape_predictor_68_face_landmarks.dat")
for face in dets:
    shape = predictor(img, face)
    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
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
人脸比对是指将两张人脸图像进行比较,判断它们是否是同一个人。利用dlibopencvfacenet可以实现人脸比对的功能。 首先,需要用dlib进行人脸检测对齐,再利用opencv人脸图像转换为facenet所需的格式,最后使用facenet进行人脸特征提取和比对。 以下是一个简单的c++程序,实现了两张人脸图像的比对: ```c++ #include <iostream> #include <dlib/opencv.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "dlib/image_processing/frontal_face_detector.h" #include "dlib/image_processing.h" #include "dlib/dnn.h" using namespace std; using namespace dlib; // 人脸对齐 void align_face(cv::Mat& img, full_object_detection& shape) { // 人脸对齐点 const int left_eye_points[6] = {36, 37, 38, 39, 40, 41}; const int right_eye_points[6] = {42, 43, 44, 45, 46, 47}; // 获取左右眼平均坐标 cv::Point2d left_eye(0, 0); cv::Point2d right_eye(0, 0); for (int i = 0; i < 6; i++) { left_eye.x += shape.part(left_eye_points[i]).x(); left_eye.y += shape.part(left_eye_points[i]).y(); right_eye.x += shape.part(right_eye_points[i]).x(); right_eye.y += shape.part(right_eye_points[i]).y(); } left_eye.x /= 6; left_eye.y /= 6; right_eye.x /= 6; right_eye.y /= 6; // 计算旋转角度 double angle = atan2(right_eye.y - left_eye.y, right_eye.x - left_eye.x) * 180 / M_PI; // 计算缩放比例 double scale = 1.0 / (right_eye.x - left_eye.x); // 构造仿射变换矩阵 cv::Mat rot_mat = cv::getRotationMatrix2D(left_eye, angle, scale); cv::Mat warp_dst; cv::warpAffine(img, warp_dst, rot_mat, img.size()); // 截取对齐后的人脸 int x = left_eye.x - (right_eye.x - left_eye.x); int y = left_eye.y - (right_eye.y - left_eye.y) / 2; int w = right_eye.x - left_eye.x + (right_eye.x - left_eye.x); int h = right_eye.y - left_eye.y + (right_eye.y - left_eye.y) / 2; cv::Mat aligned_face = warp_dst(cv::Rect(x, y, w, h)); img = aligned_face.clone(); } // 人脸比对 double face_compare(cv::Mat& img1, cv::Mat& img2) { // 加载人脸检测器和关键点检测器 frontal_face_detector detector = get_frontal_face_detector(); shape_predictor sp; deserialize("shape_predictor_68_face_landmarks.dat") >> sp; // 检测人脸对齐 std::vector<rectangle> faces1 = detector(img1); std::vector<rectangle> faces2 = detector(img2); if (faces1.empty() || faces2.empty()) { return -1.0; } full_object_detection shape1 = sp(img1, faces1[0]); full_object_detection shape2 = sp(img2, faces2[0]); align_face(img1, shape1); align_face(img2, shape2); // 转换图像格式 matrix<rgb_pixel> face1; matrix<rgb_pixel> face2; assign_image(face1, cv_image<rgb_pixel>(img1)); assign_image(face2, cv_image<rgb_pixel>(img2)); // 加载facenet模型 anet_type net; deserialize("dlib_face_recognition_resnet_model_v1.dat") >> net; // 提取人脸特征向量 std::vector<matrix<float,0,1>> face1_feats = net(face1); std::vector<matrix<float,0,1>> face2_feats = net(face2); // 计算欧氏距离 double distance = length(face1_feats[0] - face2_feats[0]); return distance; } int main() { // 加载图片 cv::Mat img1 = cv::imread("face1.jpg"); cv::Mat img2 = cv::imread("face2.jpg"); // 人脸比对 double distance = face_compare(img1, img2); // 输出结果 if (distance >= 0) { cout << "distance: " << distance << endl; } else { cout << "no face detected" << endl; } return 0; } ``` 其中,`align_face`函数用于人脸对齐,`face_compare`函数用于人脸比对。两个函数都使用了dlibopencv库。 在这个程序中,我们使用了预训练好的人脸检测器、关键点检测器和facenet模型,它们都可以在dlib官网上下载。如果你想实现更高效的人脸比对,可以考虑使用GPU加速。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值