简体   繁体   中英

How to resize video stream from cv2 according to tkinter window

Here is a code in which I just want to show the stream from a video camera on a Tkinter label. Now the problem is when someone tries to resize the Tkinter window, the stream should resize accordingly maintaining the same aspect ratio. I tried some tweaks but those did not work out. Below is my code.

root.bind( "<Configure>", resize )

width = cap. get(cv2. CAP_PROP_FRAME_WIDTH )
height = cap. get(cv2. CAP_PROP_FRAME_HEIGHT )
k = int(compute_hcf(int(width),int(height)))
w_ratio = width//k
h_ratio = height//k

def resize(event):
    h = root.winfo_height()
    w = root.winfo_width()
    k = min(h,w)
    print(k)
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, k//w_ratio)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, k//h_ratio)

This gives me the following error while trying to resize the window.

[ WARN:0] global C:\projects\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (436) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback

If anyone can help, Thank you.

So after reading your code, it seems you are overcomplicating the issue by trying to create an event that resizes it for you.

So I've gone back to basics and just created a webcam stream that will resize whenever you resize the window while maintaining the aspect ratio.

Here is some code that I've found and modified, it doesn't use tkinter , but it's not that important because you can incorporate this in wherever you see fit.

The only major issue I have with this, is when resizing you may find that your window will freeze, but only for a few seconds, it will come back after a while, you wont actually freeze the image, just window control.

You may need to use python multithreading , I actually might try and do that this evening because I find this quite interesting.

import cv2

def main():

    windowName = "Top"
    cv2.namedWindow(windowName)
    cap = cv2.VideoCapture(0)

    cap.set(3, 650)
    cap.set(4, 750)
    
    if cap.isOpened():
        ret, frame = cap.read()
    else:
        ret = False

    while ret:
        ret, frame = cap.read()
        cv2.imshow(windowName, frame)
        if cv2.waitKey(1) == 27:
            break

    cv2.destroyAllWindow()

    cap.release()   
if __name__== "__main__":

    main() 

But in terms of actual functionality, this will let you stream your camera and resize the window without it cropping out, maintaining the same aspect ratio.

if you have any questions let me know

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM