首页 > 解决方案 > 给定一个像素数组,如何在 Python 中设置 Gtk3 图像

问题描述

我编写了一个简单的 GTK 3 应用程序,它读取图像、显示图像、对像素强度应用阈值并尝试绘制结果。所以我有一个带有像素值的 numpy 数组。我不知道如何从像素数组中加载 GtkImage。

似乎 gtk.gdk.Drawable 类可能是答案。我无法导入 GdkDrawable,因为没有找到自省类型库。所以我被卡住了 - 如何使用 numpy 数组在 Python 中设置 GtkImage 对象的图像?

我知道的唯一方法是使用 Pillow 将数组写入 png 文件,然后从文件中设置 GtkImage 小部件。由于我想在调整滑块时更新,所以太慢了。

import gi
from PIL import Image

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk, GdkPixbuf

#Load the gtk image widget from a file

#Get pixel array
pb = self.image_widget.get_pixbuf()
h = pb.get_height()
w = pb.get_width()
pixels = pb.get_pixels()
pixels = np.frombuffer(pixels, dtype=np.uint8)
pixels = pixels.reshape((h,w,3))

# Apply the threshold
self.pixels = pixels
self.pixels = (self.pixel>thresh)*255

im = Image.fromarray(np.uint8(self.pixels))
im.save('temp.png')
self.image_widget.set_from_file('temp.png')
self.image_widget.show()

标签: gtk3

解决方案


推荐阅读