- 【丁丁歷險記】全篇索引
- 本節教大家使用opencv的圖傳功能,配合Python內置的tkinter包製作上位機監控上位機界面,可以與圖像完成實時的交互功能。
- 圖傳請參考 python實現opencv+scoket網絡實時圖傳
- tkinter更多使用參數請參考 Python GUI tkinter
一、圖傳上位機界面設計
- 許多同學在製作圖傳或者使用opencv-python的包時,往往因爲不會做界面而導致不能實時進行與圖像的交互功能。因此一個簡單穩定的上位機界面變得十分重要了。
- 先做一個界面看看
from tkinter import * def tap(): e2Text.set("點我,點我") root = Tk() root.title("如易科技公衆平臺") root.geometry('850x500') """ 圖像畫布設置 """ panel = Label(root) panel.place(x=1,y=1,anchor='nw') root.config(cursor="arrow") """ 右側組件 """ l1Text = StringVar() l1 = Label(root,text = "按鈕點擊測試",bg='green',font=('Arial', 12), width=22, height=2) l1.place(x=642,y=2,anchor='nw') e1 = Entry(root,width = 10) e1.place(x=680,y=55,anchor='nw') b1 = Button(root, text="確定!", command=tap) b1.place(x=780,y=50,anchor='nw') l2Text = StringVar() l2 = Label(root,text = "輸出窗口測試",bg='red',font=('Arial', 12), width=22, height=2) l2.place(x=642,y=90 ,anchor='nw') l3Var = StringVar() e2Text = StringVar() e2 = Entry(root,textvariable = e2Text,state='disabled',bg='white',bd=2, width=20) e2.place(x=665,y=135 ,anchor='nw') root.mainloop()
運行界面後
二、添加攝像頭的動態顯示
- 添加opencv的視頻流捕獲函數
- 將視頻現實窗口放在左側的空白部分
-
from tkinter import * import cv2 from PIL import Image,ImageTk grakMark = False def tap(): global grakMark if grakMark: grakMark = False else: grakMark = True def video_loop(): #動態圖像現實窗口 success, img = camera.read() # 從攝像頭讀取照片 global grakMark if success: """ 攝像頭圖像 """ img = cv2.resize(img, (640, 480)) if grakMark: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.waitKey(10) cv2image = cv2.cvtColor(img, cv2.COLOR_BGR2RGBA)#轉換顏色從BGR到RGBA current_image = Image.fromarray(cv2image)#將圖像轉換成Image對象 imgtk = ImageTk.PhotoImage(image=current_image) panel.imgtk = imgtk panel.config(image=imgtk) root.after(5, video_loop) camera = cv2.VideoCapture(0) root = Tk() root.title("如易科技公衆平臺") root.geometry('850x500') """ 圖像畫布設置 """ panel = Label(root) panel.place(x=1,y=1,anchor='nw') root.config(cursor="arrow") """ 右側組件 """ l1Text = StringVar() l1 = Label(root,text = "按鈕點擊測試",bg='green',font=('Arial', 12), width=22, height=2) l1.place(x=642,y=2,anchor='nw') e1 = Entry(root,width = 10) e1.place(x=680,y=55,anchor='nw') b1 = Button(root, text="確定!", command=tap) b1.place(x=780,y=50,anchor='nw') l2Text = StringVar() l2 = Label(root,text = "輸出窗口測試",bg='red',font=('Arial', 12), width=22, height=2) l2.place(x=642,y=90 ,anchor='nw') l3Var = StringVar() e2Text = StringVar() e2 = Entry(root,textvariable = e2Text,state='disabled',bg='white',bd=2, width=20) e2.place(x=665,y=135 ,anchor='nw') video_loop() root.mainloop() # 當一切都完成後,關閉攝像頭並釋放所佔資源 camera.release() cv2.destroyAllWindows()
點擊確定按鈕,圖像則會變成灰度圖