黑人人臉檢測

g13013610560發表於2020-12-23

黑人人臉檢測

由於黑人膚色偏深,往往無法直接被檢測到人臉,我將處理黑人人臉的問題轉化為不均勻光照下人臉檢測的問題,通過邊緣增強和明暗均衡的兩個濾波器實現黑人人臉檢測

import cv2
import dlib
import numpy as np
from PIL import Image,ImageFilter

path = "C:/Users/gufei/Desktop/black/black1.jpg"
path = "black.png"

img = Image.open(path)
org= cv2.imread(path)

def face_enhance(img):
    enhance = img.filter(ImageFilter.EDGE_ENHANCE_MORE)#大閾值邊緣增強
    result = cv2.cvtColor(np.asarray(enhance), cv2.COLOR_RGB2BGR)
    gamma=0.2
    scale = float(np.iinfo(result.dtype).max - np.iinfo(result.dtype).min)
    result = ((result.astype(np.float32) / scale) ** gamma) * scale#自適應gamma增強
    result = np.clip(result, 0, 255).astype(np.uint8)
    return result

def show_recognition(img,org):
    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(org, pt_pos, 2, (0, 0, 255), 1)  # img, center, radius, color, thickness

    for i, d in enumerate(dets):
        print("第", i + 1, "個人臉的矩形框座標:",
              "left:", d.left(), "right:", d.right(), "top:", d.top(), "bottom:", d.bottom())
        cv2.rectangle(org, tuple([d.left(), d.top()]), tuple([d.right(), d.bottom()]), (0, 0, 255), 2)

img=face_enhance(img)
show_recognition(img,org)
cv2.imshow("image", org)
cv2.waitKey(0)#等待鍵盤輸入
cv2.destroyAllWindows()

執行結果如下:
在這裡插入圖片描述

相關文章