1.dlib库
提供大量图像处理、机器学习算法
-
get_frontal_face_detector()
获取人脸框,可在一张图片中识别多个人脸 -
dets = detector(gray_img, 1)
获取人脸,可获取多个
import cv2
import dlib
img = cv2.imread("xxx.jpg")
detector = dlib.get_frontal_face_detector()
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
dets = detector(gray_img, 1)
for i, d in enumerate(dets):
print(type(d))
y1 = d.top() if d.top() > 0 else 0
y2 = d.bottom() if d.bottom() > 0 else 0
x1 = d.left() if d.left() > 0 else 0
x2 = d.right() if d.right() > 0 else 0
print(y1)
print(y2)
print(x1)
print(x2)
- imutils库
imutils来resize()
face_utils.shape_to_np(shape)转换坐标矩阵 - cv2库
- cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)画矩形
- cv2.cvtColor(input_img, flag)
input_img,输入图像
flag,如转换类型为COLOR_BGR2GRAY
cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
from imutils import face_utils
import dlib
import imutils
import cv2
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
filename = "ji1.jpg"
image = cv2.imread(filename)
image = imutils.resize(image, width=500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
rects = detector(gray, 1)
for(i, rect) in enumerate(rects):
shape = predictor(gray, rect) # 标记人脸中的68个landmark点
shape = face_utils.shape_to_np(shape) # shape转换成68个坐标点矩阵
(x, y, w, h) = face_utils.rect_to_bb(rect) # 返回人脸框的左上角坐标和矩形框的尺寸
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
landmarksNum = 0
for (x, y) in shape:
cv2.circle(image, (x, y), 2, (0, 0, 255), -1)
cv2.putText(image, "{}".format(landmarksNum), (x, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.2, (255, 0, 0), 1)
landmarksNum = landmarksNum + 1
landmarksNum = 0
cv2.imshow("Output", image)
cv2.imwrite("easy%s"%(filename), image)
cv2.waitKey(0)