I've created a class to display my webcam video on a Tkinter screen and I would like to take 3 pictures(waiting 3 seconds after each picture taken) after a Tkinter button is pressed.
Here is my code(reduced), and my logic to take picture is done. Should I use Threads to solve this? I'm new to Python.
import tkinter, cv2, time, dlib, numpy as np, time, threading
from PIL import Image, ImageTk
class Tela:
def __init__(self, janela):
self.janela = janela
self.janela.title("Reconhecimento Facial")
self.janela.config(background="#FFFFFF")
self.image = None
self.cam = cv2.VideoCapture(0)
self.detector = dlib.get_frontal_face_detector()
self.delay = 15
self.update()
self.janela.mainloop()
def update(self): # display image on gui
ret, frame = self.cam.read()
if ret:
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 take_picture(self):
cou = 1 # counter of pictures
start = time.clock() # starts the time
ret, frame = self.cam.read()
if ret:
faces, confianca, idx = self.detector.run(frame)
secs = (time.clock() - start) # count seconds
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)
if secs > 3:
imgfinal = cv2.resize(frame, (750, 600))
cv2.imwrite("fotos/pessoa." + str(id[0][0]) + "." + str(cou) + ".jpg", imgfinal)
print("Foto " + str(cou) + " tirada")
cou += 1
start = time.clock() # reset the counter of seconds
if cou > 3:
# here is where the thread should stop
# Creates the window
Tela(tkinter.Tk())