2011-10-26 9 views
10

PIL画像をGTK Pixbufに変換する別の方法があるかどうかを検討しています。 今私が持っているのは、私が見つけて自分のニーズにハッキングした非効率的なコーディングのようなものです。これは私がこれまで持っているものです。PIL画像を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 

は、私は逃したこの変換を行うには、いくつかの簡単な方法はありますか?

答えて

9

あなたがnumpyの配列を経由して行く場合は、効率的にそれを行うことができます。

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

、戻りラインは、おそらく次のようになります。「、ARR(GdkPixbufのをGdkPixbuf.Pixbuf.new_from_dataを返します.Colorspace.RGB、False、8、arr.shape [1]、arr.shape [0]、arr.shape [1] * 3) ' –

6

あなたはPyGIとGTK + 3を使用している場合は、ここにも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

これは現時点では悲しいことですが、http://を参照してください。 stackoverflow.com/questions/7906814/converting -pil-image-to-gtk-pixbuf – Havok

+0

あなたはもっと具体的になりますか?どの部分が正しく動作しないのですか?また、あなたのリンクは、stackoverflowでこの現在の質問を指し示しています。おそらくあなたは別のものを指すことを意味しましたか? –

+0

申し訳ありませんが、間違ったリンクを貼り付けました:http://stackoverflow.com/questions/10341988/converting-pil-gdkpixbuf/ – Havok

2

私は、[1]ので、これはそれが働いて得るためにあなたのようにworkaroudんでした(このバージョンは、メソッドnew_from_bytesを持っている)GTK 3.14を使用することはできませんよ。

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 

参考文献:PyGIに私はPyGtkから移行後

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