Tkinter视频流在按钮命令后冻结

时间:2019-04-21 20:24:07

标签: python multithreading opencv tkinter

我有一个用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)  

0 个答案:

没有答案