【发布时间】:2022-10-23 13:24:19
【问题描述】:
以下程序用于识别我在网络摄像头中显示的面孔。如果以防万一,它不能识别它应该捕获屏幕截图的面部。当我显示保存在我的数据库中的已知人脸时,该程序非常完美。但是,当我向它展示不认识的人或者我闪烁网络摄像头使其无法读取面部编码时,网络摄像头突然“无响应”。
在程序中,您可以在 While 循环中看到“if 语句用于识别人脸,while 循环用于捕获屏幕截图”。 if 语句运行良好。但是,当它进入其他部分时,网络摄像头会在窗口中显示“无响应”。
代码有点长。所以,如果你愿意,那么你可以跳过上面的部分。我指定了发生问题的部分。
import cv2
import numpy as np
import matplotlib.pyplot as plt
import face_recognition
import os
path = 'images'
images = []
classNames = []
myList = os.listdir(path)
print(myList)
for cls in myList:
curImg = cv2.imread(f'{path}/{cls}')
images.append(curImg)
classNames.append(os.path.splitext(cls)[0])
print(classNames)
def findEncodings(images):
encodeList = []
for img in images:
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
encode = face_recognition.face_encodings(img)[0]
encodeList.append(encode)
return encodeList
encodeListKnown = findEncodings(images)
print("Encoding Complete.")
cap = cv2.VideoCapture(1400)
# you can skip the above part if it's irrelevant with the error.
while True:
success, img = cap.read()
imgS = cv2.resize(img, (0, 0), None, 0.25, 0.25)
imgS = cv2.cvtColor(imgS, cv2.COLOR_BGR2RGB)
faceCurFrame = face_recognition.face_locations(imgS)
encodeCurFrame = face_recognition.face_encodings(imgS, faceCurFrame)
for encodeFace, faceLoc in zip(encodeCurFrame, faceCurFrame):
matches = face_recognition.compare_faces(encodeListKnown, encodeFace)
faceDis = face_recognition.face_distance(encodeListKnown, encodeFace)
print(faceDis)
matchIndex = np.argmin(faceDis)
# The if statement is for recognizing the face that is being shown.
if matches[matchIndex]:
name = classNames[matchIndex].upper()
print(name)
y1,x2,y2,x1 = faceLoc
y1,x2,y2,x1 = y1*4,x2*4,y2*4,x1*4
cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.rectangle(img, (x1, y2-35), (x2, y2), (0, 255, 0), cv2.FILLED)
cv2.putText(img, name, (x1+6, y2-6), cv2.FONT_HERSHEY_COMPLEX, 0.9, (255, 255, 255), 2)
cv2.imshow('Webcam', img)
cv2.waitKey(1)
# The else statement is for capturing the image if it doesn't recognize the face.
else:
if cap.isOpened():
ret, frame = cap.read()
print(ret)
print(frame)
img1 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
plt.imshow(img1)
cv2.imwrite(f".\\temp_img\\temp.png", frame)
print("Image Captured.")
plt.xticks([])
plt.yticks([])
cap.release()
cv2.destroyAllWindows()
time.sleep(0)
【问题讨论】:
标签: python