[Python] how to show opencv video frame in python gtk gui?

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    i have try to do this from thread to an imagebox of gtk . The frames are showing successfull for some times but after 5 seconds the gui freezes and the image appears to be blank , but the thread is still running

    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()

    Continue reading...

Compartilhe esta Página