这是在pycharm成功实现的一个人脸关键点定位的例程,做了算是详细的注释了,函数的解释是参照了其它博客的

'''

argparse是一个Python模块:命令行选项、参数和子命令解析器。

parser = argparse.ArgumentParser(description='Process some integers.')

使用 argparse 的第一步是创建一个 ArgumentParser 对象。
ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息。

添加参数
给一个 ArgumentParser 添加程序参数信息是通过调用 add_argument() 方法完成的。
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')

解析参数
>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
ArgumentParser 通过 parse_args() 方法解析参数。

'''


'''

从这里开始看起   # 加载人脸检测与关键点定位

1.取灰度图的两种方法区别: 清楚自己输入的是单通道图像还是多通道图像
如果是单通道,直接cv2.imread(img, 0) 或 cv2.imread(img, cv2.IMREAD_GRAYSCALE) 以单通道模式读
多通道:   cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)   ( cv2.cvtColor()颜色空间转换函数)

2.cv2.resize(img, dsize, dst=None, fx=None, fy=None, interpolation=None)
img:原图
dsize:输出图像尺寸
fx:沿水平轴的比例因子
fy:沿垂直轴的比例因子
interpolation:插值方法

new_img = cv2.resize(img, (720, 720), interpolation=cv2.INTER_NEAREST)
interpolation - 插值方法。共有5种:
1)INTER_NEAREST - 最近邻插值法
2)INTER_LINEAR - 双线性插值法(默认)
3)INTER_AREA - 基于局部像素的重采样(resampling using pixel area relation)。对于图像抽取(image decimation)来说,这可能是一个更好的方法。但如果是放大图像时,它和最近邻法的效果类似。
4)INTER_CUBIC - 基于4x4像素邻域的3次插值法
5)INTER_LANCZOS4 - 基于8x8像素邻域的Lanczos插值

3.detector = dlib.get_frontal_face_datector(PythonFunction,in Classes)
#功能:人脸检测画框
#参数:无
#返回值:默认的人脸检测器
#in Classes: 采样次数

rects = detector(gray, 1)
功能:对图像画人脸框
参数:gray:输入的图片, 要灰度图
返回值:人脸检测矩形框4点坐标

4.写在图片上的标题
cv2.putText(clone, name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,0.7, (0, 0, 255), 2)
各参数依次是:图片,添加的文字,左上角坐标,字体,字体大小,颜色,字体粗细

cv2.circle(clone, (x, y), 3, (0, 0, 255), -1)
最后一个参数:2代表画圆,3代表画菱形
中间的1代表线的粗细,数字越大,越粗
clone : 传入的图片
(x, y) : 要画的点的坐标
(0, 0, 255) : 要上的颜色

cv2.drawContours(image, contours, contourIdx, color, thickness=None, lineType=None, hierarchy=None, maxLevel=None, offset=None)
cv2.drawContours(overlay, [hull], -1, colors[i], -1)
第一个参数是指明在哪幅图像上绘制轮廓;image为三通道才能显示轮廓
第二个参数是轮廓本身,在Python中是一个list;
第三个参数指定绘制轮廓list中的哪条轮廓,如果是-1,则绘制其中的所有轮廓。
后面的参数很简单。其中thickness表明轮廓线的宽度,如果是-1(cv2.FILLED),则为填充模式。

overlay : 在这幅图像上绘制轮廓
[hull] : 轮廓本身
-1 : 绘制其中的所有轮廓 
colors[i] : 要上的颜色
-1 : 填充模式


'''





# 导入工具包
from collections import OrderedDict   # 导入有顺序的字典包
import numpy as np
import argparse
import dlib
import cv2

# https://ibug.doc.ic.ac.uk/resources/facial-point-annotations/
# http://dlib.net/files/

# 这段不要,是他用的软件才要吧,可能
# 参数
# ap = argparse.ArgumentParser()
# ap.add_argument("-p", "--shape-predictor", required=True,
# 	help="path to facial landmark predictor")
# ap.add_argument("-i", "--image", required=True,
# 	help="path to input image")
# args = vars(ap.parse_args())

# 有顺序的字典
FACIAL_LANDMARKS_68_IDXS = OrderedDict([
    ("mouth", (48, 68)),
    ("right_eyebrow", (17, 22)),
    ("left_eyebrow", (22, 27)),
    ("right_eye", (36, 42)),
    ("left_eye", (42, 48)),
    ("nose", (27, 36)),
    ("jaw", (0, 17))
])

FACIAL_LANDMARKS_5_IDXS = OrderedDict([
    ("right_eye", (2, 3)),
    ("left_eye", (0, 1)),
    ("nose", (4))
])


def shape_to_np(shape, dtype="int"):
    # 创建68*2
    coords = np.zeros((shape.num_parts, 2), dtype=dtype)   #68关键点的二维矩阵,用来储存68个关键点的坐标
    # 遍历每一个关键点
    # 得到坐标
    for i in range(0, shape.num_parts):
        coords[i] = (shape.part(i).x, shape.part(i).y)
    return coords


def visualize_facial_landmarks(image, shape, colors=None, alpha=0.75):
    # 创建两个copy
    # overlay and one for the final output image
    overlay = image.copy()
    output = image.copy()
    # 设置一些颜色区域
    if colors is None:
        colors = [(19, 199, 109), (79, 76, 240), (230, 159, 23),
                  (168, 100, 168), (158, 163, 32),
                  (163, 38, 32), (180, 42, 220)]
    # 遍历每一个区域
    for (i, name) in enumerate(FACIAL_LANDMARKS_68_IDXS):
        # 得到每一个点的坐标
        (j, k) = FACIAL_LANDMARKS_68_IDXS[name]
        pts = shape[j:k]
        # 检查位置  除脸颊都做凸包
        if name == "jaw":
            # 用线条连起来
            for l in range(1, len(pts)):
                ptA = tuple(pts[l - 1])   #元组
                ptB = tuple(pts[l])
                cv2.line(overlay, ptA, ptB, colors[i], 2)
        # 计算凸包
        else:
            hull = cv2.convexHull(pts)   #给该部分的坐标即可算凸包
            cv2.drawContours(overlay, [hull], -1, colors[i], -1)
    # 叠加在原图上,可以指定比例, alpha:权重 ; 0:提亮
    cv2.addWeighted(overlay, alpha, output, 1 - alpha, 0, output)
    return output


# 加载人脸检测与关键点定位
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor(
    "F:\\cv\\cv\\opencv\\face_place\\landmark\\shape_predictor_68_face_landmarks.dat")  ###你导入文件的路径

# 读取输入数据,预处理
image = cv2.imread("F:\\cv\\cv\\opencv\\face_place\\landmark\\images\\liudehua.jpg")  ###你导入图片的路径
(h, w) = image.shape[:2]
width = 500
r = width / float(w)   #根据宽度计算缩放比例
dim = (width, int(h * r))
image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)   #得到灰度图

# 人脸检测
rects = detector(gray, 1)

# 遍历检测到的框
for (i, rect) in enumerate(rects):
    # 对人脸框进行关键点定位
    # 转换成ndarray
    shape = predictor(gray, rect)  # gray当前的输入图像, rect指定好框的位置,得到人脸关键点相对于人脸框的位置
    shape = shape_to_np(shape)  # 转换成坐标

    # 遍历每一个部分, name某一部分, (i, j)某一区域, 比如:("mouth", (48, 68))
    for (name, (i, j)) in FACIAL_LANDMARKS_68_IDXS.items():
        clone = image.copy()  # 复制传入的图片
        cv2.putText(clone, name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,
                    0.7, (0, 0, 255), 2)

        # 根据位置画点
        for (x, y) in shape[i:j]:
            cv2.circle(clone, (x, y), 3, (0, 0, 255), -1)

        # 提取ROI区域, 截取五官某部分的图片
        (x, y, w, h) = cv2.boundingRect(np.array([shape[i:j]]))

        roi = image[y:y + h, x:x + w]
        (h, w) = roi.shape[:2]
        width = 250
        r = width / float(w)
        dim = (width, int(h * r))
        roi = cv2.resize(roi, dim, interpolation=cv2.INTER_AREA)

        # 显示每一部分
        cv2.imshow("ROI", roi)
        cv2.imshow("Image", clone)
        cv2.waitKey(0)

    # 展示所有区域
    output = visualize_facial_landmarks(image, shape)
    cv2.imshow("Image", output)
    cv2.waitKey(0)



Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐