# sampleCollect.py
import cv2
cap = cv2.VideoCapture(0) # 打开摄像头0 / 若为“xxxx.mp4”则为视频文件
isOpened = cap.isOpened() # 判断是否打开/ 为后续提供条件语句
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
print(fps, width, height)
i = 0 # 第二个人脸收集 i = 1001 i==2001 :break
while isOpened:
if i == 1001:
break
else:
i += 1
(flag, frame) = cap.read() # flag是否读取成功, frame为图片内容
fileName = "image" + str(i) + ".jpg"
if flag:
cv2.imwrite(f"dataset\{fileName}", frame, [cv2.IMWRITE_JPEG_QUALITY, 100])
cv2.imshow("Hello!", frame)
if cv2.waitKey(1) == ord("q"):
break
print("END")
# train.py
import cv2
import numpy as np
face_xml = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def samples_and_labels():
faceData = []
ids = []
for i in range(1, 2001):
path = "dataset/image" + str(i) + ".jpg"
img = cv2.imread(path)
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_xml.detectMultiScale(imgGray)
for (x, y, w, h) in faces:
if i <= 1000:
ids.append(1)
else:
ids.append(2)
faceData.append(imgGray[y:y+h, x:x+w])
return faceData, ids
(faces, ids) = samples_and_labels()
print(faces, ids)
print("Training...")
jackData = cv2.face.LBPHFaceRecognizer_create() # 创建LBPH
jackData.train(faces, np.array(ids)) # 参数1 为人脸像素数据 参数2 为对应人脸标签
jackData.save("wjhlxq.yml")
print("Finish")
# main.py
import cv2
import numpy as np
cap = cv2.VideoCapture(0) # 摄像头
success, img = cap.read() # 从摄像头读取照片
recog = cv2.face.LBPHFaceRecognizer_create()
recog.read("wjhlxq.yml")
face_xml = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
names = ["wjh", "lxq"]
isOpened = cap.isOpened()
while(isOpened):
(success, frame) = cap.read()
frameGray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
face = face_xml.detectMultiScale(frameGray, 1.4, 3)
for(x, y, w, h) in face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 255, 1), 2, cv2.LINE_AA)
ids, confidence = recog.predict(frameGray[y:y+h, x:x+w])
print(confidence)
if confidence < 50:
cv2.putText(frame, names[ids-1], (x, y - 8), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
else:
cv2.putText(frame, "unknown", (x, y - 8), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 255), 2)
cv2.imshow("test", frame)
if ord("q") == cv2.waitKey(1):
break