- 【丁丁历险记】全篇索引
- 本节教大家使用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()
点击确定按钮,图像则会变成灰度图