源碼閱讀-face_detector

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)
  1. imutils庫
    imutils來resize()
    face_utils.shape_to_np(shape)轉換座標矩陣
  2. 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)

在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章