我想看看是否有其他方法可以将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 有没有更简单的方法来完成这个我错过的转换?
发布于 2011-10-27 03:17:49
如果您使用numpy数组,则可以高效地执行此操作:
import numpy
arr = numpy.array(im)
return gtk.gdk.pixbuf_new_from_array(arr, gtk.gdk.COLORSPACE_RGB, 8)发布于 2012-01-17 18:18:10
如果你正在使用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)发布于 2015-01-30 21:02:40
我不能使用GTK3.14(这个版本有new_from_bytes方法) 1,所以为了让它工作,我像你这样做了这个变通方法:
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参考文献:
https://stackoverflow.com/questions/7906814
复制相似问题