import cv2
import os
import numpy as np
def take_faces():
while True:
key = input('请输入文件夹的名字,姓名拼音的缩写,如果输入Q,程序退出!')
if key == 'Q':
break
# 在faces_dynamic下面创建子文件夹
os.makedirs('./faces_dymamic/%s' % (key), exist_ok=True)
take_photo(key)
def load_data():
listdir = os.listdir('./faces_dymamic')
#列表生成式
names = [d for d in listdir if not d.startswith('.')]
faces = []
target = [i for i in range(len(names))]*10
for dir in names:
for i in range(1,11):
gray = cv2.imread('./faces_dymamic/%s/%d.jpg'% (dir,i)) #三维图片
gray_ = gray[:, :, 0] #二维数组
faces.append(gray_)
faces = np.asarray(faces)
target = np.asarray(target)
target.sort() # 排序
return faces,target,names
def dynamic_recognizer_face(face_recognizer,names):
cap = cv2.VideoCapture(0)
#人脸检测
face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
while True:
flag,frame = cap.read()
if not flag:
break
gray = cv2.cvtColor(frame, code=cv2.COLOR_BGR2GRAY)
faces = face_detector.detectMultiScale(gray,minNeighbors=5)
for x,y,w,h in faces:
face = gray[y:y + h, x:x + w]
face = cv2.resize(face, dsize=(64, 64))
y_,confidence = face_recognizer.predict(face)
label = names[y_]
print('这个人是:%s.置信度:%0.1f'%(label,confidence))
cv2.rectangle(frame,pt1=(x,y),pt2=(x+w,y+h),color=[0,0,255],thickness=2)
cv2.putText(frame,text=label,
org=(x,y-10),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1.5,
color=[0,0,255],thickness=2)
cv2.imshow('face',frame)
key = cv2.waitKey(1000//24)
if key == ord('q'):
break
cv2.destroyAllWindows()
cap.release()
if __name__ == '__main__':
#2、加载数据,返回目标值
faces,target,names = load_data()
#print(faces.shape,target.shape)
#3、加载人脸识别算法
#face_recognizer = cv2.face.EigenFaceRecognizer_create()
#face_recognizer = cv2.face.FisherFaceRecognizer_create()
face_recognizer = cv2.face.LBPHFaceRecognizer_create()
#4、算法训练,找到目标值之间的规律
face_recognizer.train(faces,target)
#5、动态加载数据
dynamic_recognizer_face(face_recognizer,names )
opencv动态识别人脸
weixin_462901972024-04-28 14:49
相关推荐
Channing Lewis18 小时前
pyproject.toml测试人社区—667918 小时前
破茧成蝶:DevOps流水线测试环节的效能跃迁之路Lethehong19 小时前
openEuler AI 图像处理:Stable Diffusion CPU 推理性能优化与评测Guheyunyi19 小时前
智慧停车管理系统:以科技重塑交通效率与体验std8602119 小时前
微软将允许用户从Windows 11文件资源管理器中移除“AI 动作”入口为爱停留19 小时前
Spring AI实现MCP(Model Context Protocol)详解与实践秋刀鱼 ..19 小时前
第七届国际科技创新学术交流大会暨机械工程与自动化国际学术会议(MEA 2025)xwill*1 天前
分词器(Tokenizer)-sentencepiece(把训练语料中的字符自动组合成一个最优的子词(subword)集合。)学历真的很重要1 天前
VsCode+Roo Code+Gemini 2.5 Pro+Gemini Balance AI辅助编程环境搭建(理论上通过多个Api Key负载均衡达到无限免费Gemini 2.5 Pro)普通网友1 天前
微服务注册中心与负载均衡实战精要,微软 2025 年 8 月更新:对固态硬盘与电脑功能有哪些潜在的影响。