利用opencv 做一個簡單的人臉識別

專注的阿熊發表於2022-07-28

# %%

import cv2 as cv

import numpy as np

import imutils

import os

from PIL import Image

# %%

face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')

VIDEO_PATH = 'video/hero2.mp4'

face_id = 2

#sampleNum 用來計數樣本數目

count = 0

SAVE_PATH = 'data/'

cap = cv.VideoCapture(VIDEO_PATH)

count = 0

while cap.isOpened():

     ret, img = cap.read()

     if ret is not None:

         if img is None:

             continue

         img = imutils.resize(img, width=600)

         gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

         face = face_cascade.detectMultiScale(gray, 1.3, 5)

         for (x, y, w, h) in face:

             cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))

             count += 1

             if not os.path.exists(SAVE_PATH + 'user.' + str(face_id)):

                 os.mkdir(SAVE_PATH + 'user.' + str(face_id))

             cv.imwrite(SAVE_PATH + 'user.' + str(face_id) + "/count_" + str(count) + ".jpg", gray[y: y + h, x: x + w])

         if count >= 800:

             break   

         cv.imshow('h', img)

         key = cv.waitKey(1)

         if key == 27:

             break

     else:

         break

cap.release()

cv.destroyAllWindows()

# %%

import tensorflow.keras as keras

from keras.preprocessing.image import ImageDataGenerator

train_gen = ImageDataGenerator(rescale= 1./255)

train_img_gen = train_gen.flow_from_directory('./data/')

# %%

# 人臉識別器

import time

recog = cv.face.LBPHFaceRecognizer_create()

recog.read('trainner/face.yaml')

# 建立一個函式,用於從資料集資料夾中獲取訓練圖片 , 並獲取 id

time_start = time.process_time()

def get_imgs_labels():

     face_id = 0

     face_arr = []

     face_ids = []

     for user_id in os.listdir(SAVE_PATH):

         face_id = user_id.split('.')[1]

         user_path = SAVE_PATH + user_id

         image_paths = [os.path.join(user_path, key) for key in os.listdir(user_path)]

         for path in image_paths:

             face_ids.append(int(face_id))

             img = cv.imread(path, 0)

             # img_arr = np.array(img, dtype="uint8")

             face_arr.append(img)

     return face_arr, face_ids

face_arr, face_ids = get_imgs_labels()

time_end =外匯跟單gendan5.com time.process_time ()

print('runTime' + str((time_end - time_start)))

recog.train(train_img_gen)

print('train' + str((time.process_time () - time_end)))

recog.save('trainner/face.yaml')

# %%

VIDEO_PATH = 'video/hero2.mp4'

font = cv.FONT_HERSHEY_SIMPLEX

idNum = 0

names = ['unknow', 'cc', 'dm']

cap = cv.VideoCapture(VIDEO_PATH)

while cap.isOpened():

     ret, img = cap.read()

     img = imutils.resize(img, width=600)

     if ret is not None:

         gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

         face = face_cascade.detectMultiScale(gray, 1.3, 5)

         for (x, y, w, h) in face:

             cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))

             id, conf = recog.predict(gray[y: y+h, x: x+w])

             user = ''

             if conf < 100:

                 user = names[id]

                 conf = "{0}%".format(round(100-conf))

             else:

                 user = "unknown"

                 conf = "{0}%".format(round(100-conf))

             cv.putText(img, user, (x + 5, y - 5), font, 1, (0,255, 0), 1)

             cv.putText(img, str(conf), (x + 50, y - 5), font, 1, (0,255, 0), 1)

         cv.imshow('face', img)

         key = cv.waitKey(1)

         if key == 27:

             break

cap.release()

cv.destroyAllWindows()

# %%

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2908067/,如需轉載,請註明出處,否則將追究法律責任。

相關文章