Adrian
Adrian

Reputation: 879

How to display an image from a matrix of pixels?

In Python and Gtk3, When I have an image file, I can display that image like this

image = Gtk.Image()
image.set_from_file(file_name)

But If I have a matrix like the following

[[ 10, 120,  38,  75, 189],
 [200, 122, 130,   0,  29],
 [255,  11, 102, 222,  18],
 [ 36, 118, 199,  45,  26],
 [231, 218,  12,   5, 156]]

which represents the pixels of an image in grayscale, is there a method that allows to display that image directly from that matrix instead of having to save it to an image file and then load that file?

Upvotes: 1

Views: 637

Answers (1)

PM 2Ring
PM 2Ring

Reputation: 55489

I've only used Gtk2, but I agree with Nick's suggestion to check out gtk.gdk.Pixbuf.

From the linked doc:

A gtk.gdk.Pixbuf object contains the data that describes an image using client side resources. By contrast a gtk.gdk.Pixmap uses server side resources to hold image data. Manipulating the image data in a gtk.gdk.Pixmap may involve round trip transfers between a client and a server in X11 while manipulating image data in a gtk.gdk.Pixbuf involves only client side operations. Therefore using gtk.gdk.Pixbuf objects may be more efficient than using gtk.gdk.Pixmap objects if a lot of image manipulation is necessary.

In particular, take a look at the pixbuf_new_from_array() method. To do the reverse, you can use the get_pixels_array() method. These methods give you access to the Pixbuf's pixel_array attribute.

You can render a Pixbuf using gtk.gdk.Drawable.draw_pixbuf().

Upvotes: 1

Related Questions