調用外部攝像頭,對圖像進行人臉識別,對比素材庫裡面部特征,找到相似度高的,如果小於30就將數據存到素材庫
import cv2
import numpy as np
import os
import time
class Face_comparison():
def __init__(self,img,model,file_name):
# 人臉識別
self.faceCascade = cv2.CascadeClassifier("./venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml")
self.faceCascade_eye = cv2.CascadeClassifier("./venv/Lib/site-packages/cv2/data/haarcascade_eye.xml")
self.img = img
self.shape = img.shape
self.model = model
self.file_name = file_name
# 時間計算
def get_current_time(self):
ct = time.time()
local_time = time.localtime(ct)
data_head = time.strftime("%Y%m%d%H%M%S", local_time)
data_secs = abs(ct - round(ct)) * 1000
time_stamp = "%s%03d" % (data_head, data_secs)
return time_stamp
def Similarity(self):
# 截取圖片面部區域,作為一個獨立圖片,用於保存或其他判斷
cropped = self.img[self.y:self.y + self.w, self.x:self.x + self.h]
#圖片灰度化
cropped = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)
#圖片像素擴充與素材一致
cropped = cv2.resize(cropped, (400, 400))
#相似度比對
label, confidence = self.model.predict(cropped)
#如果相似度小於30,就將素材圖片保存,擴充人像庫
if round(int(confidence), 4) <= 30:
print('相似度比對', str(label) + '_' + self.file_name[str(label)],round(int(confidence), 4))
in_time = self.get_current_time()
#隨著素材庫填充,分值會越來越低,繼續擴充存儲過多
cv2.imwrite('./image/face_catalogue/'+str(label)+'_'+self.file_name[str(label)]+'/'+in_time+'.jpeg', cropped)
#print(str((self.x, self.y, self.w, self.h)), str(label), self.file_name[str(label)], round(int(confidence), 4))
#字體樣式
font = cv2.FONT_HERSHEY_TRIPLEX
#字體系數
self.font_xs = round(self.shape[0] / 768, 2)
#文字標記
cv2.putText(self.img, self.file_name[str(label)] +'_'+str(round(int(confidence),4)) , (self.x, self.y-5), font, round(0.6*self.font_xs,1), (0, 0, 255))
def face_sign(self):
faces = self.faceCascade.detectMultiScale(self.img, 1.15,5)
print(faces)
if len(faces)>0:
for (self.x, self.y, self.w, self.h) in faces:
#圖像中面部識別相似度
self.Similarity()
# # 加入眼睛識別,如果存在眼睛在保存
# eye = self.faceCascade_eye.detectMultiScale(cropped, 1.15)
# if len(eye) > 0:
cv2.rectangle(self.img, (self.x, self.y), (self.x + self.w, self.y + self.h), (0, 0, 200), 2)
return self.img
else:
return self.img
def face_catalogue(catalogue):
#面部目錄加載,每次讀取圖片加載一次太浪費效率
photos = list()
lables = list()
file_name = {}
# 遍歷上層目錄
for root, dirs, files in os.walk(catalogue):
# 查看存在多少個子目錄
if files == []:
#print(‘root’, root, ‘dirs’, dirs, ‘files’, files)
for dir in dirs:
for root_son, dirs_son, files_son in os.walk(catalogue + “/%s” % dir):
#print(‘dir’, dir, ‘files’, files_son)
dir_id = dir[0:7]
dir_name = dir[8:]
#print(‘dir_id’, dir_id, ‘dir_name’, dir_name)
#增加字典
file_name[dir_id]=dir_name
#附件計數
file_num = 0
for file_son in files_son:
#print(‘file’, catalogue + “/%s/%s” % (dir, file_son))
img = cv2.imread(catalogue + “/%s/%s” % (dir, file_son), 0)
imga = cv2.resize(img, (400, 400))
photos.append(imga)
lables.append(int(dir_id))
file_num += 1
#print(‘序列號’,dir,‘素材數量:’,file_num)
#print(‘文件數’,set(lables),file_name)
model = cv2.face.LBPHFaceRecognizer_create()
model.train(photos, np.array(lables))
return model,file_name
if name == ‘main’:
#面部素材庫加載
model,file_name = face_catalogue(‘./image/face_catalogue’)
#測試圖片
#img = cv2.imread(“ceshi10.jpeg”)
capture = cv2.VideoCapture(1, cv2.CAP_DSHOW)
print(‘capture111’)
while (capture.isOpened()):
print(‘capture222’)
retval, image = capture.read()
#生成類
face_sign_user = Face_comparison(image,model,file_name)
#調用函數
img = face_sign_user.face_sign()
cv2.imshow(‘img’, img)
key = cv2.waitKey(1)
cv2.waitKey()
cv2.destroyAllWindows()