Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.7k views
in Technique[技术] by (71.8m points)

python - resizing an image in tkinter

the following code plays a given video file on a tkinter window:

from tkinter import *
from PIL import ImageTk, Image
import cv2


root = Tk()
main_label = Label(root)
main_label.grid()

# Capture from camera
cap = cv2.VideoCapture("video.mp4")


# function for video streaming
def video_stream():
    ret, frame = cap.read()
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    img = Image.fromarray(cv2image)
    tk_img = ImageTk.PhotoImage(image=img)
    main_label.configure(image=tk_img)
    main_label.tk_img = tk_img
    main_label.after(20, video_stream)


video_stream()
root.mainloop()

my question is how can I resize the video to be played in a 500 by 500 resolution for example?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First I would like to mention a possible problem.

Always check whether the frame returns or not. Otherwise your application will crash.

ret, frame = cap.read()
if ret:
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)

Now resize your frame

# function for video streaming
ret, frame = cap.read()
if ret:
    cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
    cv2image = cv2.resize(cv2image, (500, 500))

Correct Code:

from tkinter import *
from PIL import ImageTk, Image
import cv2


root = Tk()
main_label = Label(root)
main_label.grid()

# Capture from camera
cap = cv2.VideoCapture("video.mp4")


# function for video streaming
def video_stream():
    ret, frame = cap.read()
    if ret:
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
        cv2image = cv2.resize(cv2image, (500, 500))
        img = Image.fromarray(cv2image)
        tk_img = ImageTk.PhotoImage(image=img)
        main_label.configure(image=tk_img)
        main_label.tk_img = tk_img
        main_label.after(20, video_stream)


video_stream()
root.mainloop()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...