我有一些IP摄像机提供RTSP视频馈送,我知道OpenCV可以通过使用cv2.videoCapture()
和类似cap.read()
的功能在窗口上的cv2.imshow()
功能上显示视频。现在我正试图将该视频显示在TKinter GUI窗口上。下面是OpenCV网站上的RTSP示例代码,它在一个独立的窗口上运行得很好:
import cv2
cap = cv2.VideoCapture('rtsp://192.168.0.169:554/mpeg4')
while True:
ret, img = cap.read()
if ret == True: #lines below may not be necessary
cv2.imshow('video output', img)
k = cv2.waitKey(10)& 0xff
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
如何将视频馈送应用于TKinter.Frame()
或类似的内容?此外,我将在同一界面窗口上总共使用3台相机,并添加按钮将相机馈送切换到不同的TKinter.Frame()
。
提前谢谢!
我设法使用PIL ImageTk将来自Ip摄像头的rtsp流显示到Tkinter GUI。尽管我认为由于编码不好,它在我的系统上有点滞后。我建议您在不同的线程上使用cv2.VideoCapture运行处理,因为它有时会刷新GUI。
import tkinter as tk
import cv2
from PIL import Image
from PIL import ImageTk
import threading
import os
class MainWindow():
def __init__(self, window, cap):
self.window = window
self.cap = cap
self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH)
self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
self.interval = 10 # Interval in ms to get the latest frame
# Create canvas for image
self.canvas = tk.Canvas(self.window, width=600, height=400)
self.canvas.grid(row=0, column=0)
# Update image on canvas
root.after(self.interval, self.update_image)
self.button = tk.Button()
def update_image(self):
# Get the latest frame and convert image format
self.OGimage = cv2.cvtColor(self.cap.read()[1], cv2.COLOR_BGR2RGB) # to RGB
self.OGimage = Image.fromarray(self.OGimage) # to PIL format
self.image = self.OGimage.resize((600, 400), Image.ANTIALIAS)
self.image = ImageTk.PhotoImage(self.image) # to ImageTk format
# Update image
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.image)
# Repeat every 'interval' ms
self.window.after(self.interval, self.update_image)
#def run_decoding():
#os.system("ffmpeg -i rtsp://192.168.1.10?tcp -codec copy -f mpegts udp://127.0.0.1:5000 &")
if __name__ == "__main__":
#my_cam = ONVIFCamera('192.168.1.10', 80, 'gemer.daniel@gmail.com', 'dg24111998')
#media = my_cam.create_media_service()
#ptz = my_cam.create_ptz_service()
#media_profile = media.GetProfiles()[0]
# Get PTZ configuration options for getting continuous move range
#request = ptz.create_type('GetConfigurationOptions')
#request.ConfigurationToken = media_profile.token
#ptz_configuration_options = ptz.GetConfigurationOptions(request)
#request = ptz.create_type('ContinuousMove')
#request.ProfileToken = media_profile._token
#ptz.Stop({'ProfileToken': media_profile._token})
#p1 = threading.Thread(target=run_decoding)
#p1.start()
root = tk.Tk()
MainWindow(root, cv2.VideoCapture("rtsp://192.168.1.10?tcp"))
root.mainloop()
此外,如果您使用Tkinted进行约束,您可以尝试PyQT5库,我在处理帧时会得到更好的结果。