亲宝软件园·资讯

展开

python利用dlib获取人脸的68个landmark

人气:0

(1) 单人脸情况

import cv2
import dlib

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

#人脸检测画框
detector = dlib.get_frontal_face_detector()
# 获取人脸关键点检测器
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
#获取人脸框位置信息
dets = detector(gray, 1)#1表示采样(upsample)次数 0识别的人脸少点,1识别的多点,2识别的更多,小脸也可以识别
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, 0, 255), 1)#img, center, radius, color, thickness

  cv2.imshow("image", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

(2) 多人脸情况

import cv2
import dlib

path1 = "zxc.jpg"
img = cv2.imread(path1)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#人脸检测画框
detector = dlib.get_frontal_face_detector()
# 获取人脸关键点检测器
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
#获取人脸框位置信息
dets = detector(gray, 1)#1表示采样(upsample)次数 0识别的人脸少点,1识别的多点,2识别的更多,小脸也可以识别

for i in range(len(dets)):
  shape = predictor(img, dets[i]) # 寻找人脸的68个标定点
  # 遍历所有点,打印出其坐标,并圈出来
  for pt in shape.parts():
    pt_pos = (pt.x, pt.y)
    cv2.circle(img, pt_pos, 2, (0, 0, 255), 1)#img, center, radius, color, thickness

cv2.imshow("image", img)

cv2.waitKey(0)#等待键盘输入
cv2.destroyAllWindows()

(3) 获取电脑摄像头实时识别标定

import cv2
import dlib
import numpy as np

cap = cv2.VideoCapture(0)#打开笔记本的内置摄像头,若参数是视频文件路径则打开视频
cap.isOpened()

def key_points(img):
  points_keys = []
  PREDICTOR_PATH = "shape_predictor_68_face_landmarks.dat"
  detector = dlib.get_frontal_face_detector()
  predictor = dlib.shape_predictor(PREDICTOR_PATH)
  rects = detector(img,1)

  for i in range(len(rects)):
    landmarks = np.matrix([[p.x,p.y] for p in predictor(img,rects[i]).parts()])
    for point in landmarks:
      pos = (point[0,0],point[0,1])
      points_keys.append(pos)
      cv2.circle(img,pos,2,(255,0,0),-1)
  return img

while(True):
  ret, frame = cap.read()#按帧读取视频,ret,frame是cap.read()方法的两个返回值。其中ret是布尔值,如果读取帧是正确的则返回True,如果文件读取到结尾,它的返回值就为False。frame就是每一帧的图像,是个三维矩阵。
  # gray = cv2.cvtColor(frame)
  face_key = key_points(frame)
  cv2.imshow('frame',face_key)
  if cv2.waitKey(1) & 0xFF == ord('q'):
    break

cap.release()#释放摄像头
cv2.destroyAllWindows()#关闭所有图像窗口
您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论