Python opencv and face_recognition problem after turn of Monitor

In my script, I try to capture the camera frame of my Surface device. It mostly works fine, but when I turn off my monitor using the power button, the light of the camera turns off. After that, even when I hold my finger over the camera, it still recognizes my face. I’ve tried resetting the frame, but it didn’t help. What am I doing wrong?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code># -*- 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
</code>
<code># -*- 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 </code>
# -*- 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

I suspect it might have something to do with the threads I’m using.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>self.frame = None
</code>
<code>self.frame = None </code>
self.frame = None

This is what i tried but it still saves the frame.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật