У меня есть экран, созданный с помощью Tkinter, и на нем есть виджет метки, где отображается видео с веб-камеры, и некоторые кнопки, которые выполняют некоторые действия, проблема в том, что когда я нажимаю кнопку btn_trei
и выполняет действие, видеозамерзает.Может ли кто-нибудь помочь мне исправить мой сценарий для обработки как действий, зацикливания видео, так и действий кнопок. Вот мой код.
import tkinter, cv2, threading, dlib, numpy as np, datetime as dt
from PIL import Image, ImageTk
from conexao import conexao
from treinamento import Treinar
class Tela:
def __init__(self, janela):
self.janela = janela
self.frame = None
self.counter = 1
self.id = None
self.cam = cv2.VideoCapture(0)
self.detector = dlib.get_frontal_face_detector()
self.quadro = tkinter.Frame(self.janela, width=600, height=500)
self.quadro.grid(row=0, column=0, padx=10, pady=2, rowspan=10)
self.painel = tkinter.Label(self.quadro)
self.painel.grid(row=0, column=0)
self.btn_trei = tkinter.Button(self.trei, text="Treinar", state="normal", command=self.treinar)
self.btn_trei.grid(row=9, column=1, pady=5)
self.delay = 15
self.update()
self.janela.mainloop()
def update(self):
ret, frame = self.cam.read()
if ret:
self.frame = frame.copy()
faces, confianca, idx = self.detector.run(frame)
for i, face in enumerate(faces):
e, t, d, b = (int(face.left()), int(face.top()), int(face.right()), int(face.bottom()))
cv2.rectangle(frame, (e, t), (d, b), (0, 255, 255), 2)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
self.image = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=self.image)
self.painel.imgtk = imgtk
self.painel.config(image=imgtk)
self.janela.after(self.delay, self.update)
def treinar(self):
#Execute method from Treinar class
# Here is when the camera freezes for 5~10 seconds
t = threading.Thread(target=Treinar().treinar_classes,args=())
t.start()
######### Treinar class ########################
import os, glob, _pickle as cPickle, dlib, cv2, numpy as np
class Treinar:
def __init__(self):
self.detector = dlib.get_frontal_face_detector()
self.detectorPontos = dlib.shape_predictor("recursos/shape_predictor_68_face_landmarks.dat")
self.reconhecimento = dlib.face_recognition_model_v1("recursos/dlib_face_recognition_resnet_model_v1.dat")
self.indice = {}
self.idx = 0
self.descritores = None
def treinar_classes(self):
for arquivo in glob.glob(os.path.join("fotos", "*jpg")):
img = cv2.imread(arquivo)
faces = self.detector(img, 1)
numFaces = len(faces)
for face in faces:
pontosFace = self.detectorPontos(img, face)
descritorFace = self.reconhecimento.compute_face_descriptor(img, pontosFace)
listaDescritores = [df for df in descritorFace]
npArrayDescritor = np.asarray(listaDescritores, dtype=np.float64)
npArrayDescritor = npArrayDescritor[np.newaxis, :]
if self.descritores is None:
self.descritores = npArrayDescritor
else:
self.descritores = np.concatenate((self.descritores, npArrayDescritor), axis=0)
self.indice[self.idx] = arquivo
self.idx += 1
np.save("descritores/descritor_pessoa.npy", self.descritores)
with open("descritores/indices_pessoa.pickle", "wb") as f:
cPickle.dump(self.indice, f)