dlib庫的安裝以及人臉特征點的識別分布分別在前兩篇博文里面
Dlib Python 檢測人臉特征點 Face Landmark Detection
Mac OSX下安裝dlib (Python)
這篇主要涉及 cv2.ellipse 和 cv2.fitEllipse 的用法
import cv2
import dlib
import numpy as np
detector = dlib.get_frontal_face_detector()
landmark_predictor = dlib.shape_predictor('/Users/apple/Downloads/shape_predictor_68_face_landmarks.dat')
img = cv2.imread('/Users/apple/Downloads/3-1.jpg')
faces = detector(img,1)
left_eye = []
right_eye = []
if ( len(faces) > 0):
for k,d in enumerate(faces):
shape = landmark_predictor(img,d)
for i in range(36,42):
right_eye.append([shape.part(i).x,shape.part(i).y])
for i in range(42,48):
left_eye.append([shape.part(i).x,shape.part(i).y])
ellipse_left = cv2.fitEllipse(np.array(left_eye))
ellipse_right = cv2.fitEllipse(np.array(right_eye))
cv2.ellipse(img, ellipse_left, (0,255,0), 1)
cv2.ellipse(img, ellipse_right, (0,255,0), 1)
cv2.fitEllipse(points)
里面的points類型要求是numpy.array([[x,y],[x1,y1]...]) 並不是把所有點都包括在橢圓里面,而是擬合出一個橢圓盡量使得點都在圓上
cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color[, thickness[, lineType[, shift]]])
其中每個參數的意義如下:
· img 圖像
· center 中心坐標
· axes 橢圓的尺寸(長短軸)
· angle 旋轉角度
· startAngle 起始角度
· endAngle 終止角度
· 后面參數都是跟線條有關的
ellipse_left
((275.1310119628906, 197.24081420898438),
(13.491097450256348, 47.203433990478516),
84.19256591796875)
這個時候返回的分別是橢圓的中心坐標,短軸長軸(也就是2b,2a),旋轉角度.
center = ellipse_left[0]
size = ellipse_left[1]
angle = ellispe_left[2]
cv2.imshow('PIC',img)
cv2.waitKey(0)