0

I designed a window with tkinter and wanted to show a video stream there, and I also wanted to be able to pause the video with the "p" key. I created a function which puts a picture captured with a webcam into a label on the window. Then I put the function into the while loop to call it repeatedly and make a continuous video in the window. And I used waitKey() functions in the loop to read the key presses. The waitKey() also sets the frame rate or speed of the video. I managed to get the video running but the program does not react to key presses. On the other hand, I can change the frame rate when I change the argument of the waitKey(), so the function seems to work but it doesn't read the key presses and nothing happens when a key is pressed. There are also no error messages. I would be thankful if somebody would show me how to use the waitKey() in this loop so that I could control the video stream with key presses, or suggest a different way to do it. This is my code, most of it is designing the window but the loop with waitKey() functions is at the end:

import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter.ttk import *
from PIL import ImageTk, Image
from cv2 import cv2

mainwin = Tk()  #create main window

appWinWidth = int(0.6 * mainwin.winfo_screenwidth()) #set main window size (depending on the screen)
appWinHeight = int(0.5 * mainwin.winfo_screenheight())

screen_width = mainwin.winfo_screenwidth() #get screen dimensions
screen_height = mainwin.winfo_screenheight()

appWinX = int((screen_width - appWinWidth)/2) #set coordinates of the main window so that it 
appWinY = int((screen_height - appWinHeight)/2) #would be located in the middle of the screen

#create and place the frames
frame1 = tk.Frame(mainwin, background = "white", width = int(appWinWidth/2), height = appWinHeight)
frame2 = tk.Frame(mainwin, background = "black", width = int(appWinWidth/2), height = appWinHeight)

frame1.grid(row = 0, column = 0, sticky = "nsew")
frame2.grid(row = 0, column = 1, sticky = "nsew")

mainwin.grid_columnconfigure(0, weight = 1)
mainwin.grid_columnconfigure(1, weight = 1)
mainwin.grid_rowconfigure(0, weight = 1)

#set the geometry of the main window
mainwin.geometry("{}x{}+{}+{}".format(appWinWidth, appWinHeight, appWinX, appWinY)) 
mainwin.resizable(width = 0, height = 0)

#create labels in frames
frame2.grid_propagate(0) #labels and other widgets in frame don't change the size of the frame
frame2.grid()
labelF2 = Label(frame2)
labelF2.grid()
labelF2.place(relx=0.5, rely=0.5, anchor="center")
frame1.grid_propagate(0)
labelF1 = Label(frame1, background = "white")
labelF1.grid()
mainwin.update()

#get camera feed and frame size
cap = cv2.VideoCapture(0)
capFrameWidth = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
capFrameHeight = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
widthRelation = capFrameWidth/frame2.winfo_width()
heigthRelation = capFrameHeight/frame2.winfo_height()

#define the size of the video frame so that the video would fit into the frame of the main window
if widthRelation > 1 and widthRelation > heigthRelation:
    fittedSize = (int(capFrameWidth/widthRelation), int(capFrameHeight/widthRelation))
elif heigthRelation > 1 and heigthRelation > widthRelation:
    fittedSize = (int(capFrameWidth/heigthRelation), int(capFrameHeight/heigthRelation))
else:
    fittedSize = (capFrameWidth, capFrameHeight)

#funtion for getting a video frame, resizing it for the main window and placing it into the frame 2
def video_to_mainwin():
    chk, frame = cap.read()
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    imgV = cv2.resize(cv2image, fittedSize) 
    img = Image.fromarray(imgV)
    imgtk = ImageTk.PhotoImage(image=img)
    labelF2.imgtk = imgtk
    labelF2.configure(image=imgtk)

#run the video function continuously to create a stream, and be ready to react to key presses
while True:
    key = cv2.waitKey(1)
    if key == ord('p'):  #if 'p' is pressed, pause the stream and write 'Paused' to frame 1 on the main window
        video_to_mainwin()
        labelF1.config(text = 'Paused')
        mainwin.update()
        key2 = cv2.waitKey(0) #remain paused until 'c' is pressed
        if key2 == ord('c'):
            labelF1.config(text = '') 
    else:                   #if no key is pressed, then just show the video stream
        video_to_mainwin()
        mainwin.update()
2
  • if you display image in tkinter window then you don't need cv2.waitKey(1) - use tkinter for this - root.bind("p", function) to run function when you press p. And when you use bind() then you don't need while True to check pressed key - bind() does it for you. Eventually you may need root.after(time, function) to run function which update image in window.
    – furas
    Feb 7, 2021 at 2:02
  • place(), grid(), pack() are different 'layout managers` - every widget need only one layout manage - it makes no sense to do labelF2.grid() and labelF2.place(...)
    – furas
    Feb 7, 2021 at 2:20

1 Answer 1

0

If you display cv2 image in tkinter then you don't need cv2.waitKey().

You can use tkinter for this

mainwin.bind("p", function_name)

to run function_name() when you press p.

And when you use bind() then you don't need while True to check pressed key because tkinter mainloop will do it for you.

You need only root.after(milliseconds, function_name) to run function which will update image in window every few milliseconds.


Working code

#from tkinter import *      # PEP8: `import *` is not preferred
#from tkinter.ttk import *  # PEP8: `import *` is not preferred

import tkinter as tk
from tkinter import ttk
from PIL import ImageTk, Image
from cv2 import cv2

# --- constants --- (PEP8: UPPER_CASE_NAMES)

#FPS = 25

# --- classes --- (PEP8: CamelCaseNames)

# ... empty ...

# --- functions --- (PEP8: lower_case_names)

def video_to_mainwin():
    """Getting a video frame, resizing it for the main window and placing it into the frame 2."""

    if not paused:
        chk, frame = cap.read()
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        imgV = cv2.resize(cv2image, fitted_size) 
        img = Image.fromarray(imgV)
        imgtk = ImageTk.PhotoImage(image=img)
        labelF2.imgtk = imgtk
        labelF2.configure(image=imgtk)

    # run it again after `1000/FPS` milliseconds
    #mainwin.after(int(1000/FPS), video_to_mainwin)
    mainwin.after(int(1000/cap_fps), video_to_mainwin)

def set_pause(event):
    global paused
    
    paused = True
    labelF1.config(text = 'Paused')

def unset_pause(event):
    global paused
    
    paused = False
    labelF1.config(text = '') 
    
# --- main ---- (PEP8: lower_case_names)
    
paused = False  # default value at start

# - cap - 

cap = cv2.VideoCapture(0)
cap_frame_width  = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
cap_frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
cap_fps = int(cap.get(cv2.CAP_PROP_FPS))

# - tk -

mainwin = tk.Tk()  # create main window

app_win_width = int(0.6 * mainwin.winfo_screenwidth()) # set main window size (depending on the screen)
app_win_height = int(0.5 * mainwin.winfo_screenheight())

screen_width = mainwin.winfo_screenwidth() # get screen dimensions
screen_height = mainwin.winfo_screenheight()

app_win_x = int((screen_width - app_win_width)/2) # set coordinates of the main window so that it 
app_win_y = int((screen_height - app_win_height)/2) # would be located in the middle of the screen

#create and place the frames
frame1 = tk.Frame(mainwin, background="white", width=int(app_win_width/2), height=app_win_height)
frame2 = tk.Frame(mainwin, background="black", width=int(app_win_width/2), height=app_win_height)

frame1.grid(row=0, column=0, sticky="nsew")   # PEP8: without spaces around `=`
frame2.grid(row=0, column=1, sticky="nsew")   # PEP8: without spaces around `=`

mainwin.grid_columnconfigure(0, weight=1)   # PEP8: without spaces around `=`
mainwin.grid_columnconfigure(1, weight=1)   # PEP8: without spaces around `=`
mainwin.grid_rowconfigure(0, weight=1)

#set the geometry of the main window
mainwin.geometry("{}x{}+{}+{}".format(app_win_width, app_win_height, app_win_x, app_win_y)) 
mainwin.resizable(width=0, height=0)

# create labels in frames
frame2.grid_propagate(0) # labels and other widgets in frame don't change the size of the frame
frame2.grid()

labelF2 = tk.Label(frame2)
labelF2.place(relx=0.5, rely=0.5, anchor="center")

frame1.grid_propagate(0)

labelF1 = tk.Label(frame1, background = "white")
labelF1.grid()

mainwin.update() # to create window and correctly calculate sizes

# get camera feed and frame size
width_relation  = cap_frame_width/frame2.winfo_width()
heigth_relation = cap_frame_height/frame2.winfo_height()


# define the size of the video frame so that the video would fit into the frame of the main window
if width_relation > 1 and width_relation > heigth_relation:
    fitted_size = (int(cap_frame_width/width_relation), int(cap_frame_height/width_relation))
elif heigth_relation > 1 and heigth_relation > width_relation:
    fitted_size = (int(cap_frame_width/heigth_relation), int(cap_frame_height/heigth_relation))
else:
    fitted_size = (cap_frame_width, cap_frame_height)

# assing functions to buttons
mainwin.bind("p", set_pause)
mainwin.bind("c", unset_pause)

# star video
video_to_mainwin()

# start tkinter mainloop (event loop)
mainwin.mainloop()

# - end -

cap.release()

PEP 8 -- Style Guide for Python Code


I have few examples with cv2 and tkinter on Github.

For example: python-cv2-streams-viewer uses cv2 in separted thread to read from webcam or file (even from file on internet). It also uses tk.Frame to create widget which display stream from cv2. It uses this widget many times to display many streams at the same time.

Other examples in python-examples - cv2 or tkinter

1
  • This code works exactly as I wanted! Thank you very much! Actually I tried to use the binding function myself, too, but I could just print the text with the bind(), I didn't find a way to pause the video with this function. But the idea to use a flag like "paused" is really good, it works. As regards the waitKey() then I don't know why didn't it work but maybe it created a separate thread so that even if the delay set in the argument of the waitKey() worked, the key value was not accessible.
    – reip
    Feb 7, 2021 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.