简介
最近有个需求,需要开发个桌面应用工具,可是实时显示rstp视频,于是想到了用python自带的tkinter 来开发,最后打包成exe应用。
import cv2
import random
import threading
from tkinter import *
from PIL import Image, ImageTk
def center_window(root):
root.title('')
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry('%dx%d+%d+%d' % (width, height, x, y))
# 获取RTSP流并显示实时画面
def get_rtsp_stream():
cap = cv2.VideoCapture("rtsp://admin:a12345678@192.168.1.3:554")
while True:
ret, frame = cap.read()
frame = cv2.resize(frame, (int(width * 0.5), int(height * 0.4)))
if not ret:
break
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
canvas.create_image(0, 0, anchor=NW, image=imgtk)
canvas.image = imgtk
cap.release()
# 显示图片
def show_image():
cap = cv2.VideoCapture("rtsp://admin:123456@192.168.1.1:554")
ret, frame = cap.read()
frame = cv2.resize(frame, (int(width * 0.5), int(height * 0.4)))
cv2.imwrite("image.jpg",frame)
cap.release()
img = Image.open("image.jpg")
imgtk = ImageTk.PhotoImage(image=img)
image_panel.imgtk = imgtk
image_panel.config(image=imgtk,anchor=NW)
random_number = random.choice([-0.15, 0.15])
final_result = lgm_text + random_number
if final_result < 0:
final_result = 0.0
if final_result > 5:
final_result = 5.0
lgm_label.config(text=final_result)
def on_click(event):
global lgm_text
lgm_text = event.widget["text"]
#tkinter 清空frame
def clear_frame(frame):
for child in frame.winfo_children():
child.destroy()
def on_mouse_enter(event):
step = 0
for i in [0.0,0.75,1.0,1.25,1.5,1.75,2.0,3.0,4.0,5.0]:
button = Button(frame, text=i, font=("", 12))
button.place(relx=0.1, rely=0.08+round(step, 2), relheight=0.08, relwidth=0.2)
button.bind("<Button-1>", lambda e: on_click(e))
step += 0.08
def on_mouse_leave(event):
clear_frame(frame)
if __name__ == '__main__':
lgm_text = 0.0
root = Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
width = int(screen_width*0.67)
height = int(screen_height*0.8)
center_window(root)
# 实时画面面板
canvas = Canvas(root)
canvas.place(relx=0.05, rely=0.05, relheight=0.4, relwidth=0.5)
# 图片面板
image_panel = Label(root)
image_panel.place(relx=0.05, rely=0.55, relheight=0.4, relwidth=0.5)
# 抓拍按钮
button = Button(root, text='抓拍按钮',font=("", 18),command=lambda: threading.Thread(target=show_image).start())
button.place(relx=0.6, rely=0.3, relheight=0.05, relwidth=0.15)
# 林格曼值
lgm_label = Label(root, text="",font=("", 20), fg="red")
lgm_label.place(relx=0.6, rely=0.75, relheight=0.05, relwidth=0.15)
# 林格曼等级面板
frame = Frame(root)
frame.place(relx=0.8, rely=0.1, relheight=0.7, relwidth=0.5)
frame.bind('<Enter>', on_mouse_enter)
frame.bind('<Leave>', on_mouse_leave)
thread = threading.Thread(target=get_rtsp_stream)
thread.daemon = True
thread.start()
root.mainloop()