我写了这个函数,但有时会给我这个错误
"Authenticated as Muhammad Zair
[ WARN:[email protected]] global cap_msmf.cpp:1768 CvCapture_MSMF::grabFrame videoio(MSMF): can't grab frame. Error: -2147483638
Deleting the database object"
这是函数:
@staticmethod
def authenticate_user(users):
video = cv2.VideoCapture(0)
start_time = time.time()
capture = False
frame = None
flag = False
def video_thread():
nonlocal capture, frame
while not flag:
capture, frame = video.read()
if not capture:
continue
def video_show():
while not flag:
if frame is not None:
cv2.imshow("the video", frame)
cv2.waitKey(1)
capture_thread1 = threading.Thread(target=video_thread)
capture_thread1.start()
capture_thread2 = threading.Thread(target = video_show)
capture_thread2.start()
while time.time() - start_time < 20 and not flag:
if capture:
for user in users:
user_id, user_name, user_type, image_path = user
registered_image = cv2.imread(image_path)
result = DeepFace.verify(frame, registered_image, model_name='VGG-Face', enforce_detection=False)
if result['verified']:
print(f"Authenticated as {user_name}")
flag = True
break
video.release()
cv2.destroyAllWindows()
if flag:
return user_type
print("Failed to authenticate ")
sys.exit()
本以为人脸认证后程序能正常运行并退出该功能。但它在终端中给出错误警告,它不会终止程序,但我想解决它。
您正在从capture_thread1读取视频,因此需要在线程中释放它。否则,线程将尝试读取已经发布的视频。
此外,您需要销毁 capture_thread2 中的窗口。
拥有一个可以在使用线程时触发的停止命令也会很有帮助。我用你的旗帜做了它,你可以看到下面的例子:
import cv2
import time
import threading
import sys
from deepface import DeepFace
def authenticate_user():
video = cv2.VideoCapture(0)
start_time = time.time()
capture = False
frame = None
flag = False
def video_thread(arg):
nonlocal capture, frame
capture_thread1 = threading.currentThread()
while getattr(capture_thread1, "flag", True):
capture, frame = video.read(2)
if not capture:
continue
video.release()
def video_show(arg):
capture_thread2 = threading.currentThread()
while getattr(capture_thread2, "flag", True):
if frame is not None:
cv2.imshow("the video", frame)
cv2.waitKey(1)
cv2.destroyAllWindows()
capture_thread1 = threading.Thread(target=video_thread, args=("task",))
capture_thread1.start()
capture_thread2 = threading.Thread(target = video_show, args=("task",))
capture_thread2.start()
while time.time() - start_time < 20 and not flag:
if capture:
registered_image = cv2.imread("./my_img.jpg")#try with your path!!!
result = DeepFace.verify(frame, registered_image, model_name='VGG-Face', enforce_detection=False)
if result['verified']:
print(f"Authenticated as you")
capture_thread1.flag = False
capture_thread2.flag = False
break
if capture_thread1.flag == False:
return 1
print("Failed to authenticate ")
sys.exit()
authenticate_user()