cadend9
cadend9

Reputation: 97

GTK Python Transparent Background for PNG Image

I am using Python and GTK 3 to overlay images onto a GStreamer video stream, and I am attempting to use the Gtk.Overlay() widget to do this. The image is a .png file with a transparent background. I am able to overlay the image just fine, but when I overlay the image it has a white square as a background rather than showing the videostream underneath.

Code Snippet:

    overlay = Gtk.Overlay()
    # the drawing area holds the Gstreamer video stream
    drawing_area = Gtk.DrawingArea()
    drawing_area.set_double_buffered(True)
    overlay.add(drawing_area)
    # set the drawing area as the base layer of the overlay

    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename='icon.png', width=240, height=240, preserve_aspect_ratio=True)
    img = Gtk.Image.new_from_pixbuf(pixbuf)
    img.set_halign(Gtk.Align.START)
    img.set_valign(Gtk.Align.END)
    overlay.add_overlay(img)
    # overlay the image on the base layer (the video)

Full Code:

from gi.repository import Gdk, Gst, Gtk, GdkX11, GstVideo, GdkPixbuf
import signal

signal.signal(signal.SIGINT, signal.SIG_DFL)

def window_closed(widget, event, pipeline):
    widget.hide()
    pipeline.set_state(Gst.State.NULL)
    Gtk.main_quit()

if __name__ == "__main__":
    Gdk.init([])
    Gtk.init([])
    Gst.init([])
    pipeline = Gst.Pipeline()
    # configuring the pipeline code here,
    # uses nvarguscamerasrc on the Jetson Nano
    
    # Creating the window
    window = Gtk.Window()
    window.connect("delete-event", window_closed, pipeline)
    window.set_default_size(1920, 1080)
    window.set_title("Application")
    
    overlay = Gtk.Overlay()
    # the drawing area holds the Gstreamer video stream
    drawing_area = Gtk.DrawingArea()
    drawing_area.set_double_buffered(True)
    overlay.add(drawing_area)
    # set the drawing area as the base layer of the overlay

    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(filename='icon.png', width=240, height=240, preserve_aspect_ratio=True)
    img = Gtk.Image.new_from_pixbuf(pixbuf)
    img.set_halign(Gtk.Align.START)
    img.set_valign(Gtk.Align.END)
    overlay.add_overlay(img)
    # overlay the image on the base layer (the video)

    window.add(overlay)
    window.show_all()
    window.realize()
    
    xid = drawing_area.get_window().get_xid()
    sink.set_window_handle(xid)
    # set the GStreamer video sink to the drawing area in the window
    
    Gtk.main()

Output: Display Output

Thanks!

Upvotes: 3

Views: 812

Answers (1)

jackw11111
jackw11111

Reputation: 1547

You could try setting the alpha using this composite(...) method :

pixbuf.composite(pixbuf, 0, 0, 240, 240, 0, 0, 1, 1, GdkPixbuf.InterpType.INTERP_NEAREST, 0)

Upvotes: 1

Related Questions