当前位置:网站首页>Face detection, training and recognition based on OpenCV
Face detection, training and recognition based on OpenCV
2022-06-09 03:53:00 【Mike Zhou, exclusive musician of Netease】
be based on OpenCV Face detection 、 Training 、 distinguish
The system uses Harr Cascade detection and LPBH Face detection and training 、 distinguish
import cv2
#import time
cam = cv2.VideoCapture(0)
classifier = cv2.CascadeClassifier('./cascade/haarcascade_frontalface_alt2.xml')
# For each person, enter one numeric face id
face_input_id = input('\n enter user id end press <return> ==> ')
while(True):
img = cv2.flip(cam.read()[1],1)
# img = cv2.flip(img, -1) # flip video image vertically
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(32, 32))
if len(faces):
x,y,w,h = faces[0]
cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
# if time.time()-save_time > 0.2:
# cv2.imwrite("dataset/" + str(face_input_id) +"."+str(count)+ ".jpg", gray[y:y+h,x:x+w])
# count += 1
# save_time = time.time()
cv2.imshow('image', img)
if cv2.waitKey(10) == 27: # adopt esc Press the key to exit the camera
if len(faces):
cv2.imwrite("dataset/" + str(face_input_id) + ".jpg", gray[y:y+h,x:x+w])
else:
print(" Failed to intercept face ")
break
# elif count >= 50: # Take 30 face sample and stop video
# break
cam.release()
cv2.destroyAllWindows()
import cv2
import numpy as np
from PIL import Image
import os
# Path for face image database
path = 'dataset'
recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("./cascade/haarcascade_frontalface_alt2.xml")
# function to get the images and label data
def getImagesAndLabels(path):
imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
faceSamples=[]
ids = []
if len(imagePaths):
for imagePath in imagePaths:
PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
img_numpy = np.array(PIL_img,'uint8')
face_training_id = int(os.path.split(imagePath)[-1].split(".")[0])
faceSamples.append(img_numpy)
ids.append(face_training_id)
return faceSamples,ids
print (" Training ")
faces,ids = getImagesAndLabels(path)
if faces == [] or ids == []:
print("None")
else:
recognizer.train(faces, np.array(ids))
# Save the model into trainer/trainer.yml
recognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
# Print the numer of faces trained and end program
print(" common "+str(len(np.unique(ids)))+" Data ")
import cv2
import time
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "./cascade/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
font = cv2.FONT_HERSHEY_SIMPLEX
face_output_id = 0
face_1st_flag=0
# names related to ids: example ==> Marcelo: id=1, etc
names = ['None', 'yangxu', 'zhoulaoshi', 'liuqian', 'hekun', ]
# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)
while True:
img = cv2.flip(cam.read()[1],1)
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(32, 32))
if len(faces):
for(x,y,w,h) in faces:
cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
face_output_id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
real_confidence = int(100-confidence)
if (real_confidence > 50):
face_name = str(names[face_output_id])
face_confidence = str(real_confidence)+"%"
if face_1st_flag == 0:
face_1st_flag = 1
face_1st_id = face_output_id
face_1st_time = time.time()
else:
if 2.1 > time.time() - face_1st_time > 2.0 :
if face_output_id == face_1st_id:
print(" Recognition success : "+str(face_output_id)+" "+face_name)
face_1st_flag = 0
if time.time() - face_1st_time > 2.1:
print(" Please keep stable ")
face_1st_flag = 0
else:
face_name = "Unknown"
face_confidence = str(real_confidence)+"%"
cv2.putText(img, str(face_name), (x+5,y-5), font, 1, (255,255,255), 2)
cv2.putText(img, str(face_confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)
cv2.imshow('camera',img)
if cv2.waitKey(10) == 27:
break
cam.release()
cv2.destroyAllWindows()
边栏推荐
- Error 1130- host XXX is not allowed to connect to this MariaDB server
- ArcGIS Runtime 离线gdb数据缺失问题处理
- Six C language final assignments KTV song selection, personal revenue and expenditure management, staff resource management, class student file management, product information management, library mana
- 丰富的色彩变化
- 华为云服务器装数据库远程连接被拒绝
- MySQL 开源许可研究
- 控制台输入命令 net start mysql 控制台输出系统发生错误 5。 拒绝访问。MySQL 服务正在启动.MySQL 服务无法启动。服务没有报告任何错误。请键入 NET HELPMSG 353
- SQL审核 | 这里有 MySQL/Oracle 最常用的 SQL 开发规则
- MongoDB搭建副本集集群
- Erreur! Il n'y a pas de texte de style spécifié dans le document. (1)
猜你喜欢

CPU飙升问题定位

在线摩斯密码在线翻译转换工具

On June 12, MSG enterprise bank focused on Langfang AI enterprises to promote the integrated development of "double chain"

Experts, how to quickly transform managers?

丰富的色彩变化

基於FPGA的VGA顯示彩條、字符、圖片

85. (leaflet house) leaflet military plotting - line arrow drawing

Noc-sla acquisition C-side business monitoring practice

接口性能测试:web service接口测试

C language interview tube: talk about the functions of various string functions. I: I don't know. Interviewer: come back for an interview when the young man has learned how to do it.
随机推荐
Don't hand in the paper in advance!!! Someone got 13 points in the last 35 seconds!!! (best wishes to all candidates)
月薪近万,3年销售助理转行测试,0经验的我如何拿到多份offer?
故障分析 | MySQL 中新建用户无法登陆的一种特殊场景
JVM内存查看及设置思路
目标检测模型mAP计算方法与对比步骤——对比原模型与量化模型之间的mAP
Controversial Xu Beihong's paintings and the copyright dispute of Digital Collections
Solve the problem that the MySQL library or table is stuck during deletion and other operations
It becomes obsolete when you use it ~websecurityconfigureradapter
[examination in May] Oracle OCP 19C passed
OnlineJudge instructions
汇编:Debug的常用命令
GC log analysis
Assembly: CPU structure - flag register and related instructions
PHP deserialization recurrence - no response to the bugku login
Five highlights of wwdc2022 lock screen, weather kit, swiftui, collaboration function, apple payment
Kotlin基础从入门到进阶系列讲解(入门篇) 文件存储的基本使用
unity第一人称射击游戏,枪击游戏,功能完整可以当大作业或者毕设
word+正则表达式==快速批量添加图注题注(保姆级图文)
大厂外包or自研公司?测试人找工作怎么选?
(三)VGG复现