Heyuxuan 2 years ago
parent c48f2f2976
commit 4ebe46cb56

@ -5,8 +5,8 @@ def face_detect_demo(img):
#将图片转换为灰度图片 #将图片转换为灰度图片
gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY) gary = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
#自带的分类器 #自带的分类器
face_detect = cv.CascadeClassifier('D:/PyCharm 2024.1.1/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml') face_detect = cv.CascadeClassifier('D:/PyCharm 2024.1.1/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
face = face_detect.detectMultiScale(gary) face = face_detect.detectMultiScale(gary,1.1,5,0,(50,50),(300,300))
for (x,y,w,h) in face: for (x,y,w,h) in face:
cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2) cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
# 显示图像 # 显示图像
@ -14,7 +14,7 @@ def face_detect_demo(img):
#读取摄像头 #读取摄像头
#cap = cv.VideoCapture(0) #cap = cv.VideoCapture(0)
cap = cv.VideoCapture("output/1.mp4") cap = cv.VideoCapture("pic/1.mp4")
#循环 #循环
#等待 #等待
@ -23,7 +23,7 @@ while True:
if not flag: if not flag:
break break
face_detect_demo(frame) face_detect_demo(frame)
if ord('q') == cv.waitKey(0): if ord('q') == cv.waitKey(10):
break break
#>0 等待delay毫秒 =0 无限等待 <0 等待键盘单击 #>0 等待delay毫秒 =0 无限等待 <0 等待键盘单击
#释放内存 #释放内存

@ -0,0 +1,44 @@
import os
import cv2
from PIL import Image
import numpy as np
def getImageAndLabels(path):
#存储人脸数据
facesSamples=[]
#储存姓名数据
ids=[]
#存储图片信息
imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
#加载分类器
face_detector = cv2.CascadeClassifier('D:/PyCharm 2024.1.1/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
#遍历列表的图片
for imagePath in imagePaths:
#打开图片灰度化PIL有九种不同模式1,L,P,PGB,RGBA,CMYK,YcbCr,I,F.
PIL_img = Image.open(imagePath).convert('L') #1代表黑白打开L代表灰度图像
#将图像转换为数组,以黑白深浅
img_numpy = np.array(PIL_img, 'uint8')
#获取图片人脸特征
faces = face_detector.detectMultiScale(img_numpy)
#获取每张图片的id和姓名
id = int(os.path.split(imagePath)[1].split('.')[0])
#预防无面容图片
for (x,y,w,h) in faces:
ids.append(id)
facesSamples.append(img_numpy[y:y+h,x:x+w])
#打印脸部特征和id
print('id:',id)
print('fs:',facesSamples)
return facesSamples,ids
if __name__ == '__main__':
#图片路径
path='./output/'
#获取图像数组和id标签数组和姓名
face,ids=getImageAndLabels(path)
#加载识别器
recognizer=cv2.face.LBPHFaceRecognizer_create()
#训练
recognizer.train(face,np.array(ids))
#保存文件
recognizer.write('trainer/trainer.yml')

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

File diff suppressed because it is too large Load Diff
Loading…
Cancel
Save