Given an array of pixels, how to I set up a Gtk3 image in Python

Viewed 138

I have written a simple GTK 3 application that reads an image, displays it, applies a threshold to the pixel intensity and tries to draw the result. So I have a numpy array with the pixel values. I do not know how to load the GtkImage from an array of pixels.

It seems the the gtk.gdk.Drawable class might be the answer. I cannot import GdkDrawable because the introspection typelib is not found. So I am stuck - how to I get use a numpy array to set the image of a GtkImage object in Python?

The only way I know to do it is to use Pillow to write the array to a png file and then set the GtkImage widget from the file. Since I want to update as a slider is adjusted, that is too slow.

import gi
from PIL import Image

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GdkPixbuf

#Load the gtk image widget from a file

#Get pixel array
pb = self.image_widget.get_pixbuf()
h = pb.get_height()
w = pb.get_width()
pixels = pb.get_pixels()
pixels = np.frombuffer(pixels, dtype=np.uint8)
pixels = pixels.reshape((h,w,3))

# Apply the threshold
self.pixels = pixels
self.pixels = (self.pixel>thresh)*255

im = Image.fromarray(np.uint8(self.pixels))
im.save('temp.png')
self.image_widget.set_from_file('temp.png')
self.image_widget.show()

0 Answers
Related