在使用tkinter介面播放video時,如果只用cv2.imshow(),呼叫出來的視訊視窗是浮在原本主控GUI上的,顯得點不夠美觀簡潔,於是我又找到另一種播放影像的方法,利用label元件來播放視訊,因為labe元件是定義在主GUI原件上的,只要控制label原件上的轉換就好了
要另外引入pillow的元件:
from PIL import Image, ImageTk
這邊是介面Layout:
def init_notebookpage_3(self):
self.notebookpage_3_tab = tk.Frame(self.notebook2 )
self.notebook2.add(self.notebookpage_3_tab, text="notebookpage_3")
StreamOpenCVbutton = tk.Button(self.notebookpage_3_tab , font=('Courier', 7), text = "StreamOpenCV", command = self.StreamOpenCV)
StreamOpenCVbutton.pack(side = tk.TOP, expand=tk.YES, fill=tk.BOTH)
Showframebutton = tk.Button(self.notebookpage_3_tab , font=('Courier', 7),
text = "ShowFrame",command = self.show_frame)
Showframebutton.pack(side = tk.TOP, expand=tk.YES, fill=tk.BOTH)
self.stream = tk.Label(self.notebookpage_3_tab, width=100, height=100)
self.stream.pack(side=tk.LEFT, expand=tk.NO, fill = tk.BOTH)
我定義一個show_frame函式
def show_frame(self, event = None):
self.cap = cv2.VideoCapture(0)
_, frame = self.cap.read()
frame = cv2.resize(frame,(100,100))
img = Image.fromarray(frame)
imgtk = ImageTk.PhotoImage(image=img)
self.stream.imgtk = imgtk
self.stream.configure(image=imgtk)
self.stream.after(15, self.show_frame)