如何将Gdk pixbuf对象转换为numpy数组 [英] How to turn Gdk pixbuf object into numpy array
问题描述
因此,我尝试拍摄屏幕截图,并以numpy数组的形式对其进行处理.但是,我所能找到的就是先将其转换为PIL Image,然后转换为numpy数组.因此,我想知道是否有一种方法可以在不使用PIL库的情况下直接将其转换为numpy数组
So, I am trying to take a screenshot of the screen and do some stuff with it as numpy array. However, all I could find is turning it into PIL Image first and then into numpy array. So, I was wondering if there is a way of turning it straight into numpy array without using the PIL library
from gi.repository import Gdk
window = Gdk.get_default_root_window()
x, y, width, height = window.get_geometry()
pb = Gdk.pixbuf_get_from_window(window, x, y, width, height)
谢谢
推荐答案
如果您不介意使用Gtk2和PyGtk,则可以执行以下操作
If you don't mind using Gtk2 and PyGtk, then the following will do
import gtk, numpy
image="yourimage.jpg"
t=gtk.gdk.pixbuf_new_from_file(image)
n=t.get_pixels_array()
print n.shape
最好的部分是n
是对t
中数据的引用,因此您可以使用numpy更改pixbuf
The best part is that n
is a reference to the data in t
so you can alter the pixbuf using numpy
如果您想使用Gtk3,那么这两个调用就可以了
If you wish to use Gtk3, these two calls will do
from gi.repository import GdkPixbuf
import numpy
def array_from_pixbuf(p):
" convert from GdkPixbuf to numpy array"
w,h,c,r=(p.get_width(), p.get_height(), p.get_n_channels(), p.get_rowstride())
assert p.get_colorspace() == GdkPixbuf.Colorspace.RGB
assert p.get_bits_per_sample() == 8
if p.get_has_alpha():
assert c == 4
else:
assert c == 3
assert r >= w * c
a=numpy.frombuffer(p.get_pixels(),dtype=numpy.uint8)
if a.shape[0] == w*c*h:
return a.reshape( (h, w, c) )
else:
b=numpy.zeros((h,w*c),'uint8')
for j in range(h):
b[j,:]=a[r*j:r*j+w*c]
return b.reshape( (h, w, c) )
def pixbuf_from_array(z):
" convert from numpy array to GdkPixbuf "
z=z.astype('uint8')
h,w,c=z.shape
assert c == 3 or c == 4
if hasattr(GdkPixbuf.Pixbuf,'new_from_bytes'):
Z = GLib.Bytes.new(z.tobytes())
return GdkPixbuf.Pixbuf.new_from_bytes(Z, GdkPixbuf.Colorspace.RGB, c==4, 8, w, h, w*c)
return GdkPixbuf.Pixbuf.new_from_data(z.tobytes(), GdkPixbuf.Colorspace.RGB, c==4, 8, w, h, w*c, None, None)
这篇关于如何将Gdk pixbuf对象转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!