如何在python gtk gui中显示opencv视频帧?

2024-03-29 01:55:27 发布

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

我已经尝试从线程到gtk的imagebox执行此操作。帧显示成功一段时间,但5秒后gui冻结,图像显示为空白,但线程仍在运行

import gi
import threading
import cv2
import time
gi.require_version("Gtk" , "3.0")
from gi.repository import Gtk , GLib , GObject , GdkPixbuf
run = True
cam = cv2.VideoCapture(0)
ret , frame = cam.read()
frame  = cv2.cvtColor(frame , cv2.COLOR_BGR2RGB)
cam.release()
class MyWindow(Gtk.Window):

    def __init__(self):

        global cam, frame , run

        Gtk.Window.__init__(self,title="Hello")
        self.set_border_width(10)

        image = Gtk.Image()

        h, w, d = frame.shape
        pixbuf = GdkPixbuf.Pixbuf.new_from_data(frame.tostring(),GdkPixbuf.Colorspace.RGB, False, 8, w, h, w*d)
        image.set_from_pixbuf (pixbuf.copy())
        self.add(image)
    def thread_running_example():
        cam = cv2.VideoCapture(0)
        while run:
            ret , frame = cam.read()
            frame  = cv2.cvtColor(frame , cv2.COLOR_BGR2RGB)
            h, w, d = frame.shape
            pixbuf = GdkPixbuf.Pixbuf.new_from_data(frame.tostring(), GdkPixbuf.Colorspace.RGB, False, 8, w, h, w*d)                
            image.set_from_pixbuf (pixbuf.copy())



    thread = threading.Thread( target = thread_running_example )
    thread.daemon=True 
    thread.start()

win = MyWindow()
win.connect("destroy" , Gtk.main_quit )
win.show_all()
Gtk.main()

Tags: runfromimageimportselfgtkcv2thread