Tkinter显示其他窗口

2024-10-01 17:26:19 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以使用Tkinter显示OpenCV制作的窗口?我想用Tkinter打开它,这样我可以提供更多的GUI功能。以前做过吗?我查了一下谷歌,也查了一下,但什么也没找到。在

所以正如kobejohn建议的,我附上了相机捕捉和显示的代码。在

import cv2
import urllib 
import numpy as np
import subprocess

stream=urllib.urlopen('IP Address')
bytes=''
while True:
    bytes+=stream.read(1024)
    a = bytes.find('\xff\xd8')
    b = bytes.find('\xff\xd9')
    if a!=-1 and b!=-1:
        jpg = bytes[a:b+2]
        bytes= bytes[b+2:]
        i = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.CV_LOAD_IMAGE_COLOR)
        cv2.imshow('i',i)
        if cv2.waitKey(1) ==27:
            exit(0)

Tags: import功能streamifbytestkinternpgui
1条回答
网友
1楼 · 发布于 2024-10-01 17:26:19

此代码基于注释中的讨论。它不会把opencv窗口放到tkinter中。它只需要获取opencv图像并将它们放入tkinter。在

Prakhar,我没有可用的IP摄像机,你能试试吗?我已经确认它能和这个答案底部的USB代码一起工作。在

基本上,我只是将您的jpg阅读代码插入到this SO question的简化版本中,以获得下面的代码。它使用两步转换:bytes>;opencv image>;tkinter image。也许有一种更有效的方法可以将字节直接转换为tkinter映像,但是如果性能出现问题,可以解决这个问题。在


IP摄像机

import cv2
import numpy as np
import PIL.Image
import PIL.ImageTk
import Tkinter as tk
import urllib

stream = urllib.urlopen('IP Address')
bytes_ = ''


def update_image(image_label):
    global bytes_
    bytes_ += stream.read(1024)
    a = bytes_.find('\xff\xd8')
    b = bytes_.find('\xff\xd9')
    if (a != -1) and (b != -1):
        jpg = bytes_[a:b+2]
        bytes_ = bytes_[b+2:]
        cv_image = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),
                                cv2.CV_LOAD_IMAGE_COLOR)
        cv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2RGB)
        pil_image = PIL.Image.fromarray(cv_image)
        tk_image = PIL.ImageTk.PhotoImage(image=pil_image)
        image_label.configure(image=tk_image)
        image_label._image_cache = tk_image  # avoid garbage collection
        root.update()


def update_all(root, image_label):
    if root.quit_flag:
        root.destroy()  # this avoids the update event being in limbo
    else:
        update_image(image_label)
        root.after(1, func=lambda: update_all(root, image_label))


if __name__ == '__main__':
    root = tk.Tk()
    setattr(root, 'quit_flag', False)
    def set_quit_flag():
        root.quit_flag = True
    root.protocol('WM_DELETE_WINDOW', set_quit_flag)
    image_label = tk.Label(master=root)  # label for the video frame
    image_label.pack()
    root.after(0, func=lambda: update_all(root, image_label))
    root.mainloop()

USB摄像头

*编辑-我已经确认下面的代码可以用opencv从USB摄像机上拍摄视频并发送到tkinter窗口。所以希望上面的代码能为你的ip摄像机工作。在

^{pr2}$

相关问题 更多 >

    热门问题