2011-10-26 23 views
10

Estoy buscando para ver si hay otra manera de convertir una imagen de PIL a GTK Pixbuf. En este momento todo lo que tengo es lo que parece ser una práctica de codificación ineficaz que encontré y pirateó para mis necesidades. Esto es lo que tengo hasta ahora:Convertir la imagen de PIL a GTK Pixbuf

def image2pixbuf(self,im): 
    file1 = StringIO.StringIO() 
    im.save(file1, "ppm") 
    contents = file1.getvalue() 
    file1.close() 
    loader = gtk.gdk.PixbufLoader("pnm") 
    loader.write(contents, len(contents)) 
    pixbuf = loader.get_pixbuf() 
    loader.close() 
    return pixbuf 

¿Hay alguna manera más fácil de hacer esta conversión que me perdí?

Respuesta

9

Puede hacerlo de manera eficiente si vas a través de una matriz numpy:

import numpy 
arr = numpy.array(im) 
return gtk.gdk.pixbuf_new_from_array(arr, gtk.gdk.COLORSPACE_RGB, 8) 
+7

Después de la migración de PyGtk a pygi, la línea de retorno probablemente debería ser: 'GdkPixbuf.Pixbuf.new_from_data volver (arr, GdkPixbuf .Colorspace.RGB, False, 8, arr.shape [1], arr.shape [0], arr.shape [1] * 3) ' –

6

Si está utilizando pygi y GTK + 3, aquí es una alternativa que también elimina la necesidad de una dependencia de numpy:

import array 
from gi.repository import GdkPixbuf 

def image2pixbuf(self,im): 
    arr = array.array('B', im.tostring()) 
    width, height = im.size 
    return GdkPixbuf.Pixbuf.new_from_data(arr, GdkPixbuf.Colorspace.RGB, 
              True, 8, width, height, width * 4) 
+0

Lamentablemente esto parece no funcionar en este momento, consulte http: // stackoverflow.com/questions/7906814/converting -pil-image-to-gtk-pixbuf – Havok

+0

¿Podría ser más específico? ¿Qué parte no funciona exactamente? Además, su enlace apunta a esta pregunta actual sobre stackoverflow. ¿Quizás quisiste apuntar a otro? –

+0

Lo siento, pegué el enlace incorrecto: http://stackoverflow.com/questions/10341988/converting-pil-gdkpixbuf/ – Havok

2

no soy capaz de utilizar GTK 3.14 (esta versión tiene el método new_from_bytes) [1], por lo que hizo esto workaroud como la suya con el fin de conseguir que funcione:

from gi.repository import GdkPixbuf 
import cv2 

def image2pixbuf(im): 
    # convert image from BRG to RGB (pnm uses RGB) 
    im2 = cv2.cvtColor(im, cv2.COLOR_BGR2RGB) 
    # get image dimensions (depth is not used) 
    height, width, depth = im2.shape 
    pixl = GdkPixbuf.PixbufLoader.new_with_type('pnm') 
    # P6 is the magic number of PNM format, 
    # and 255 is the max color allowed, see [2] 
    pixl.write("P6 %d %d 255 " % (width, height) + im2.tostring()) 
    pix = pixl.get_pixbuf() 
    pixl.close() 
    return pix 

Referencias:

  1. https://bugzilla.gnome.org/show_bug.cgi?id=732297
  2. http://en.wikipedia.org/wiki/Netpbm_format