在我的脚本中,我尝试捕获 Surface 设备的相机帧。它大部分工作正常,但是当我使用电源按钮关闭显示器时,相机的灯会关闭。之后,即使我将手指放在相机上,它仍然可以识别我的脸。我尝试过重置框架,但没有帮助。我做错了什么?
# -*- coding: utf-8 -*-
from tkinter import Tk
import sys, threading, os, face_recognition, time, keyboard, cv2, numpy as np, tkinter as tk
class Window:
def __init__(self) -> None:
self.win = Tk()
self.win.attributes("-fullscreen", True)
self.win.overrideredirect(True)
self.label = tk.Label(self.win, text="Keinen Zugriff auf dieses Gerät!")
self.label.config(font=("Segoe UI", 32, "bold"))
self.label.place(relx=0.5, rely=0.5, anchor="center")
self.label2 = tk.Label(self.win, text="Kamera wird initialisiert...")
self.label2.place(relx=0.5, rely=0.6, anchor="center")
def hide(self):
self.win.withdraw()
def show(self):
self.win.deiconify()
def set_debug(self, text):
self.label2.config(text=text)
class App:
def __init__(self):
self.cam = None
self.window = Window()
threading.Thread(target=self.close_keys, daemon=True).start()
threading.Thread(target=self.cam_reload, daemon=True).start()
threading.Thread(target=self.face_rec, daemon=True).start()
self.window.win.mainloop()
def cam_reload(self):
while True:
if self.cam is None:
self.cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if self.cam.isOpened():
self.window.set_debug(text="")
else:
self.cam.release()
self.cam = None
time.sleep(1)
print(self.cam)
def close_keys(self):
while True:
if keyboard.is_pressed("alt") and keyboard.is_pressed("n") and keyboard.is_pressed("i") and keyboard.is_pressed("a"):
os._exit(0)
def face_rec(self):
path = "C:/Users/gemei/OneDrive/Desktop/Python/Security/images/Wolf.jpg"
img = face_recognition.load_image_file(path)
img_encodings = face_recognition.face_encodings(img)
if not img_encodings:
print("No face encodings found in the image.")
return
img_encoding = img_encodings[0]
known = [img_encoding]
known_names = ["admin"]
while True:
if not self.cam:
self.cam = cv2.VideoCapture(0, cv2.CAP_DSHOW)
if self.cam and self.cam.isOpened():
ret, self.frame = self.cam.read()
if ret:
print("Frame received")
small_frame = cv2.resize(self.frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = np.ascontiguousarray(small_frame[:, :, ::-1])
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known, face_encoding)
name = "Unknown"
if True in matches:
best_match_index = np.argmin(face_recognition.face_distance(known, face_encoding))
if matches[best_match_index]:
name = known_names[best_match_index]
self.face_detected = True
print("Face detected")
if self.face_detected:
self.window.hide()
else:
self.window.show()
else:
print("No frame received")
self.frame = None
self.face_detected = False
print(self.face_detected)
if __name__ == "__main__":
while True:
try:
App()
except:
continue
我怀疑这可能与我使用的线程有关。
self.frame = None
这是我尝试过的,但它仍然保存了框架。
关闭显示器后,cv2 似乎循环显示两张图片,但没有拍摄新图像...