编程实现人脸特征点标定(python3+opencv3.4+dlib库)

本文介绍了如何使用dlib库和opencv进行人脸检测和特征点定位,并展示了如何通过这些技术在人脸上虚拟添加墨镜。首先,详细说明了dlib和opencv的安装步骤,接着展示了代码实现,包括绘制脸部特征点和添加墨镜的功能。最后,对实验进行了总结,并分享了参考资料。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、准备工作

1.1、dlib库的安装

  • 下载dlib库的whl文件
    dlib库(cp37,cp38 提取码:svub)
    可以先在命令行查看电脑的版本,然后适配版本对应的dlib库。本文用的是python3.8
  • 将安装的whl文件放到适合的路径,并将该路径添加到环境变量的path中
    在这里插入图片描述
    这里因为我的Python3.8是在安装的Anaconda3中,所以我将dlib库的文件也放在了里面
  • 进入上述路径安装dlib库
pip install dlib-19.19.0-cp38-cp38-win_amd64.whl

后面的名字根据文件更改
在这里插入图片描述

1.2、opencv的安装

  • opencv没那么麻烦,可以直接在命令行用pip命令安装
pip install opencv_python==3.4.11.45

这里的版本号依旧需要适配python的版本,这个是python3.8的,其他版本可以自行查阅

二、绘制脸部特征点

这里用的脸部特征点数据集是提前训练好的
脸部特征点数据集(提取码:whc5).

  • 代码实现并保存
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 27 03:15:10 2021

@author: GT72VR
"""
#导入库
import numpy as np#数据处理库
import cv2#图像处理库
import dlib#人脸识别的库
import os
import sys
import random
# 存储位置
output_dir = 'D/faces'
size = 64
 
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
# 改变图片的亮度与对比度
 
def relight(img, light=1, bias=0):
    w = img.shape[1]
    h = img.shape[0]
    #image = []
    for i in range(0,w):
        for j in range(0,h):
            for c in range(3):
                tmp = int(img[j,i,c]*light + bias)
                if tmp > 255:
                    tmp = 255
                elif tmp < 0:
                    tmp = 0
                img[j,i,c] = tmp
    return img
 
#使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0)
#camera = cv2.VideoCapture('C:/Users/CUNGU/Videos/Captures/wang.mp4')
ok = True

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')


while ok:
    # 读取摄像头中的图像,ok为是否读取成功的判断参数
    ok, img = camera.read()
    
    # 转换成灰度图像
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    rects = detector(img_gray, 0)
    
    for i in range(len(rects)):
        landmarks = np.matrix([[p.x, p.y] for p in predictor(img,rects[i]).parts()])
        for idx, point in enumerate(landmarks):
            # 68点的坐标
            pos = (point[0, 0], point[0, 1])
            print(idx,pos)
    
            # 利用cv2.circle给每个特征点画一个圈,共68个
            cv2.circle(img, pos, 2, color=(0, 255, 0))
            # 利用cv2.putText输出1-68
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(img, str(idx+1), pos, font, 0.2, (0, 0, 255), 1,cv2.LINE_AA)
    cv2.imshow('video', img)
    k = cv2.waitKey(1)
    if k == 27:    # press 'ESC' to quit
        break
    
camera.release()
cv2.destroyAllWindows()

结果:
在这里插入图片描述
摄像头角度太死亡,所以用的漂亮小朋友的照片,冒犯到的话会删除!!!

三、给人脸虚拟P上墨镜

  • 导入包
# 导入包
import numpy as np
import cv2
import dlib
import os
import sys
import random
  • 添加函数,获得默认的人脸检测器和训练好的人脸68特征点检测器
def get_detector_and_predicyor():
    #使用dlib自带的frontal_face_detector作为我们的特征提取器
    detector = dlib.get_frontal_face_detector()
    """
    功能:人脸检测画框
    参数:PythonFunction和in Classes
    in classes表示采样次数,次数越多获取的人脸的次数越多,但更容易框错
    返回值是矩形的坐标,每个矩形为一个人脸(默认的人脸检测器)
    """
    #返回训练好的人脸68特征点检测器
    predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
    return detector,predictor
  • 获取检测器
#获取检测器
detector,predictor=get_detector_and_predicyor()

  • 给人脸添加墨镜函数
def painting_sunglasses(img,detector,predictor):   
    #给人脸带上墨镜
    rects = detector(img_gray, 0)  
    for i in range(len(rects)):
        landmarks = np.matrix([[p.x, p.y] for p in predictor(img,rects[i]).parts()])
        right_eye_x=0
        right_eye_y=0
        left_eye_x=0
        left_eye_y=0
        for i in range(36,42):#右眼范围
            #将坐标相加
            right_eye_x+=landmarks[i][0,0]
            right_eye_y+=landmarks[i][0,1]
        #取眼睛的中点坐标
        pos_right=(int(right_eye_x/6),int(right_eye_y/6))
        """
        利用circle函数画圆
        函数原型      
        cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]])
        img:输入的图片data
        center:圆心位置
        radius:圆的半径
        color:圆的颜色
        thickness:圆形轮廓的粗细(如果为正)。负厚度表示要绘制实心圆。
        lineType: 圆边界的类型。
        shift:中心坐标和半径值中的小数位数。
        """
        cv2.circle(img=img, center=pos_right, radius=30, color=(0,0,255),thickness=1)#红色边框
        cv2.circle(img=img, center=pos_right, radius=30, color=(0,0,0),thickness=-1)#黑色
        for i in range(42,48):#左眼范围
           #将坐标相加
            left_eye_x+=landmarks[i][0,0]
            left_eye_y+=landmarks[i][0,1]
        #取眼睛的中点坐标
        pos_left=(int(left_eye_x/6),int(left_eye_y/6))
        cv2.circle(img=img, center=pos_left, radius=30, color=(0,0,255),thickness=1)#红色边框
        cv2.circle(img=img, center=pos_left, radius=30, color=(0,0,0),thickness=-1)#黑色

  • 调用函数查看效果
camera = cv2.VideoCapture(0)#打开摄像头
ok=True
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
while ok:
    ok,img = camera.read()
     # 转换成灰度图像
    img_gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    #display_feature_point(img,detector,predictor)
    painting_sunglasses(img,detector,predictor)#调用画墨镜函数
    cv2.imshow('video', img)
    k = cv2.waitKey(1)
    if k == 27:    # press 'ESC' to quit
        break
camera.release()
cv2.destroyAllWindows()

结果:
在这里插入图片描述
摄像头角度太死亡,所以用的漂亮小朋友的照片,冒犯到的话会删除!!!

四、总结

这次实验因为有dlib库和opencv的帮助,过程不算难,但是趣味性十足。只是安装dlib库的时候出了一些问题,不过最后得到了解决。安装软件的时候一定千万不要急于更新,第一个吃螃蟹的人总是会遇到很多难题!!!!

五、参考资料

python3+opencv3.4+dlib库编程实现人脸特征点标定.
人脸特征提取(dlib+opencv3.4+python3.8).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值