import tkinter as tk
from PIL import Image, ImageTk
import cv2
import numpy as np
import time g_exit = False def close_window():
global g_exit
g_exit = True def video_init():
cap = cv2.VideoCapture(0)
cap.set(3, 640)
cap.set(4, 480)
time.sleep(2)
return cap def video_show():
cap = video_init()
while (cap.isOpened() and g_exit == False):
ret, frame = cap.read()
if ret == True:
frame = cv2.flip(frame, 1)
# 将图像的通道顺序由BGR转换成RGB
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
if isinstance(frame, np.ndarray):
frame = Image.fromarray(frame.astype(np.uint8)) photo = ImageTk.PhotoImage(image=frame)
image_cvs.create_image([320, 240], image=photo) win.update_idletasks()
win.update()
cap.release()
win.quit() if __name__ == '__main__':
win = tk.Tk()
image_cvs = tk.Canvas(win, width=640, height=480, bg='white')
image_cvs.pack() # 点击界面右上角的关闭按钮时,会触发'WM_DELETE_WINDOW'消息
# 我们在此截获该消息,并改变其行为
win.protocol('WM_DELETE_WINDOW', close_window) win.after(200, video_show)
win.mainloop()
在使用Canvas显式图片时,其image参数有两个重要的点需要注意,一个是格式,另外一个是要保持持续引用(可使用全局变量)。如下:
- The image object should be a PhotoImage or BitmapImage, or a compatible object (such as the PIL PhotoImage).
- The application must keep a reference to the image object.