Ask Your Question
0

Why gui stop capturing video from camera(opencv with python)?

asked 2020-04-13 12:41:46 -0600

alsada gravatar image

updated 2020-04-13 13:52:12 -0600

I am new in field of programming, and the task of my project is to have gui using python and tkinter:

  1. first key in menu should open the video when it pressed.
  2. second key should recognize the faces when it pressed and keep recognizing until the program stop.

Issue: when I run the code and press first button, code works fine and start to capture the video. But when I press second key, program stops showing the video (also rectangle around the face does not appear) but the program still gives me output message that I expect when it recognize known faces without giving any error messages.

Why does it stop showing the video? Do I need to create class for such project or what?

Thank you in advance.

Here is my code:

import cv2
import numpy as np
import dlib
import face_recognition
import os
import time
import playsound
from gtts import gTTS
import speech_recognition as sr
import winsound
from time import sleep
from tkinter import *
from PIL import Image
from PIL import ImageTk

faces = []
encode = []
known_faces = []
names = []

white       = "#ffffff"
lightBlue2  = "#adc5ed"
font        = "Constantia"
fontButtons = (font, 12)
maxWidth    = 1000
maxHeight   = 600
mainWindow = Tk()
mainWindow.title('SUTech')
mainWindow.configure(bg=lightBlue2)
mainWindow.geometry('%dx%d+%d+%d' % (maxWidth,maxHeight,0,0))
mainFrame = Frame(mainWindow)
mainFrame.place(x=480,y=0)
lmain = Label(mainFrame)

cap = cv2.VideoCapture(0)    

def show_frame():    
    ret, frame = cap.read()    
    cv2image   = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)    
    img   = Image.fromarray(cv2image).resize((512, 512))    
    imgtk = ImageTk.PhotoImage(image=img)    
    lmain.grid(row=0, column=0)    
    lmain.grid(row=0, column=0)    
    lmain.imgtk = imgtk    
    lmain.configure(image=imgtk)    
    lmain.after(10, show_frame)

def facing():    
    x = 0    
    for filename in os.listdir('faces/'):    
        if filename.endswith('.jpg'):
           faces.append(face_recognition.load_image_file(os.path.join('faces/',filename)))
            encode.append(face_recognition.face_encodings(faces[x])[0])    
            known_faces.append(encode[x])    
            names.append(filename.replace('.jpg', ''))    
            x = x + 1    
    while(cap.isOpened()):    
        ret, frame = cap.read()    
        img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)   
        location = face_recognition.face_locations(img, number_of_times_to_upsample=1, model=0)    
        encodings = face_recognition.face_encodings(img, location)    
        name = 'Unkown'    
        for encoding in encodings:    
            match = face_recognition.compare_faces(known_faces, encoding,tolerance=0.9)    
            distance = face_recognition.face_distance(known_faces, encoding)    
            bestMatch = np.argmin(distance)    
            if match[bestMatch]:   
                name = names[bestMatch]    
                print('Detected face:'+ str(name))    
                for (x, y, w, h) in (location):    
                    cv2.rectangle(frame,(h, x),(y, w), (0,255,0), 3)    
                    cv2.rectangle(frame,(h , w+30),(y, w), (0,255,0), -1)    
                    font = cv2.FONT_HERSHEY_DUPLEX

                    cv2.putText(frame, name, (h , w+25), cv2.FONT_HERSHEY_COMPLEX,1, (0,0,255), 2)       



#file menu    
menubar = Menu(mainWindow)    
file = Menu(menubar, tearoff = 0)    
menubar.add_cascade(label ='File', menu = file)    
file.add_command(label ='New File', command = show_frame)    
file.add_separator()    
file.add_command(label ='Face_detection', command = facing)    
file.add_separator()    
file.add_command(label ='Exit', command = lambda:mainWindow.destroy())    
mainWindow.config(menu = menubar)    
mainWindow.mainloop()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
0

answered 2020-04-13 12:54:03 -0600

mvuori gravatar image

The problem is that facing() uses imshow() without waitKey(), meaning that it never actually shows anything.

edit flag offensive delete link more

Comments

1

when I use waitKey() it shows the frame in separated window not inside tkinter window.

alsada gravatar imagealsada ( 2020-04-13 13:26:39 -0600 )edit

When you clicked new file from menu, you are not getting to streaming video. Also for showing face detection from face detection menu too. That why you must add bothcv2.imshow and cv2.waitKey() for both function. Or use imshow and waitkey and place before menubar.

supra56 gravatar imagesupra56 ( 2020-04-13 21:33:02 -0600 )edit
1

Thank you supara56, but when I add cv2.imshowt frame will be shown separated window not inside tkinter window. My task to open the video in the tkinter window and then having the face recognition in the same place when I press the second key(face recognition key). I mean face recognition will be detected from mainFrame that I created`.

alsada gravatar imagealsada ( 2020-04-14 13:09:44 -0600 )edit

@alsada. I understood your problem in second key pressed. Do you wanted separated window or same window?

supra56 gravatar imagesupra56 ( 2020-04-15 07:48:31 -0600 )edit

I wanted to be in the same window, I think the problem is in the second function , frame should be converted to PIL format then to imageTk format to be shown in Tkinter window and when second key is pressed first function should be killed. am I right? if yes could you please help me to solve this issue?

alsada gravatar imagealsada ( 2020-04-15 12:09:52 -0600 )edit

I ran test. In fact, I don't get menu. I'm am using Raspberry pi 3B/4B, using linux. This is what you're seeing:

%Run filemenu.py

Starting face recognition
Step 1: Dataset creation.
Enter person's name: supra
/home/pi/Documents/supra
/home/pi/Documents/supra
Directory  /home/pi/Documents/supra  Created 
Efter create directory
Print1. Loop: 1
Print1. Loop: 2
Print1. Loop: 3
Print1. Loop: 4
Found image number 1
supra56 gravatar imagesupra56 ( 2020-04-19 11:20:26 -0600 )edit

I clicked file..New file ..is working. But in fact, I don't see stop working. But testing face detection from menu. let you know.

supra56 gravatar imagesupra56 ( 2020-04-19 12:04:38 -0600 )edit

When I clicked face detection from menu. I got error stating that: Exception in Tkinter callback

Traceback (most recent call last):
  File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/home/pi/tmp_opencv4.2/filemenu.py", line 49, in facing
    for filename in os.listdir('faces/'):
FileNotFoundError: [Errno 2] No such file or directory: 'faces/'
supra56 gravatar imagesupra56 ( 2020-04-19 12:09:27 -0600 )edit

I see how you're doing. But I put my pics in faces's folder. Firstly, detected face working. After about 30 secs, the window popup. Then I clicked New File...the streaming is still working. then I clicked face detection..... I still not getting face detection. I will try to get it working.

supra56 gravatar imagesupra56 ( 2020-04-19 12:43:41 -0600 )edit

I will answer your question.

  • when second key is pressed first function should be killed. am I right

The answer is No. When I clicked face detection..it still same. It will not stop video.. I have one problem is face+detection namespaces.

supra56 gravatar imagesupra56 ( 2020-04-19 13:00:41 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2020-04-13 12:41:46 -0600

Seen: 1,940 times

Last updated: Apr 13 '20