python 人臉識別(通過攝像頭)


1、人臉檢測

# 打開攝像頭,監測人臉
import cv2 as cv


def face_detect(frame):
    # 圖片轉灰度
    img_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    # 加載人臉分類識別器
    face_detector = cv.CascadeClassifier(r'../haarcascade/haarcascade_frontalface_default.xml')
    faces = face_detector.detectMultiScale(img_gray)
    for x, y, w, h in faces:
        cv.rectangle(frame, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1)
    cv.imshow("detecting", frame)


if __name__ == '__main__':
    # 讀取攝像頭中的圖像,獲取圖像grabbed為true
    cap = cv.VideoCapture(0)
    while True:
        grabbed, img = cap.read()
        if grabbed:
            print("frame:", img.shape)
        else:
            break
        face_detect(img)
        if ord('q') == cv.waitKey(10):
            break
    cv.destroyAllWindows()
    cap.release()

2、人臉采集

# 通過攝像頭識別人臉,采集人臉圖片保存到face_data目錄

import cv2 as cv


def face_collect(face_id, username):
    print('\n 正在初始化臉部識別,請保持在攝像頭前面 ...')
    count = 0
    filename = ""
    # 讀取內置攝像頭中的圖像,獲取圖像grabbed為true
    cap = cv.VideoCapture(0)
    # 加載人臉分類識別器
    face_detector = cv.CascadeClassifier(r'../haarcascade/haarcascade_frontalface_default.xml')

    while True:
        grabbed, img = cap.read()
        if grabbed:
            print("frame:", img.shape)
        else:
            break
        # 圖片轉灰度
        img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(img_gray)
        for x, y, w, h in faces:
            cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1)
            count += 1
            # 保存圖像
            filename = r"../face_data/" + username + "." + str(face_id) + '.' + str(count) + '.jpg'
            print(filename)
            cv.imwrite(filename, img_gray[y: y + h, x: x + w])
        cv.imshow("detecting", img)

        if ord('q') == cv.waitKey(10):
            break
        elif count > 100:
            break

    cv.destroyAllWindows()
    cap.release()


if __name__ == '__main__':
    user_id = input('\n 輸入用戶ID:')
    user_name = input('\n 輸入用戶英文名:')
    face_collect(user_id, user_name)

3、人臉訓練

# 人臉訓練
import numpy as np
from PIL import Image
import os
import cv2 as cv


def face_training():
    print("人臉訓練,請耐心等待 ...")
    # 人臉圖片路徑
    face_path = '../face_data/'
    # opencv-contrib-python包中的函數
    recognizer = cv.face.LBPHFaceRecognizer_create()
    # 載入人臉分類器
    face_detector = cv.CascadeClassifier(r"../haarcascade/haarcascade_frontalface_default.xml")

    image_paths = [os.path.join(face_path, f) for f in os.listdir(face_path)]
    face_samples = []
    ids = []
    for imagePath in image_paths:
        img_gray = Image.open(imagePath).convert('L')
        img_numpy = np.array(img_gray, 'uint8')
        # 圖片的命名方式 xx.id.num.ext(xx為任意英文標識,id是標簽,同類人臉id相同,num一般為該類圖片的計數,ext為圖片后綴)
        # 文件名中關鍵就是id,作為有監督學習,id就是用於分類
        user_id = int(os.path.split(imagePath)[-1].split(".")[1])
        print(user_id, " ", imagePath)
        faces = face_detector.detectMultiScale(img_numpy)
        for x, y, w, h in faces:
            face_samples.append(img_numpy[y:y + h, x:x + w])
            ids.append(user_id)
    recognizer.train(face_samples, np.array(ids))

    # 保存訓練信息
    recognizer.write('../face_trainer/trainer.yml')
    print("{0} faces trained. Exiting Program".format(len(np.unique(ids))))


if __name__ == '__main__':
    face_training()

4、人臉識別

# 從視頻中識別人臉
import cv2 as cv


def face_recognition():
    recognizer = cv.face.LBPHFaceRecognizer_create()
    # 讀取訓練數據
    recognizer.read('../face_trainer/trainer.yml')
    face_detector = cv.CascadeClassifier(r"../haarcascade/haarcascade_frontalface_default.xml")
    font = cv.FONT_HERSHEY_SIMPLEX

    feature_id = None
    # 以訓練的時候,按人臉id進行排序
    names = ['xudemin', 'wanghaojin', 'heyinsong', 'linanan']

    cap = cv.VideoCapture(0)
    # minW = 0.1*cap.get(3)
    # minH = 0.1*cap.get(4)

    while True:
        grabbed, img = cap.read()
        if grabbed:
            print("frame:", img.shape)
        else:
            break
        # 圖片轉灰度
        img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(img_gray)
        for x, y, w, h in faces:
            cv.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=1)
            # 預測
            feature_id, confidence = recognizer.predict(img_gray[y:y + h, x:x + w])
            print(feature_id, " ", confidence)
            if confidence < 100:
                feature_id = names[feature_id]
                confidence = "{0}%".format(round(100 - confidence))
            else:
                feature_id = "unknown"
                confidence = "{0}%".format(round(100 - confidence))

            cv.putText(img, str(feature_id), (x + 5, y - 5), font, 1, (0, 0, 255), 1)
            cv.putText(img, str(confidence), (x + 5, y + h - 5), font, 1, (0, 255, 0), 1)

        cv.imshow("recognizing", img)
        if ord('q') == cv.waitKey(10):
            break

    cv.destroyAllWindows()
    cap.release()


if __name__ == '__main__':
    face_recognition()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM