【问题标题】:Image converted from a scikit array to PIL photoimage is being distorted从 scikit 数组转换为 PIL photoimage 的图像被扭曲
【发布时间】:2019-04-28 15:16:06
【问题描述】:

我正在尝试将由 scikit-image 和 scipy 处理的图像添加到 tkinter gui。要将其添加到画布,需要将其保存为 png,或转换为 PIL 图像。但是,当我尝试使用ImageTkImage.fromarray() 时,图像会严重失真。我不希望将其保存为 png,因为它只是生成数据标签的中间步骤。

我尝试检查数组的形状,它们是相同的。我尝试打印出图像,并且填充对象是正确的图像,而 im 被扭曲了。所以在 Tkinter gui 中这不是问题。另外,如果我不使用np.asarray(),它会产生相同的输出。

def generateCanny(imageName):
    #imagename should be a path to the image, created with os path join
    img = skimage.io.imread(imageName)
    print('orig {}'.format(img.shape))

    gray = np.sqrt((img*img).sum(-1))
    #converts the image to greyscale

    edges = skimage.feature.canny(gray, sigma=3)

    fill = scipy.ndimage.binary_fill_holes(edges)
    return fill

imageName = os.path.join(imagePath, imageStr)
filled_objects = generateCanny(imageName)
a = np.asarray(filled_objects)
im = PIL.Image.fromarray(a)

这是两张图片,im 在左边,filled_objects 在右边

我认为您可以轻松转换它,因为filled_objects 只是一个数组,但Image.fromarray() 必须进行一些处理。

【问题讨论】:

    标签: python-3.x tkinter python-imaging-library scikit-image


    【解决方案1】:

    问题是fromarray 没有正确解释布尔数组a。如果您将 a 转换回 RGB,使用:

    # Extend the array into 3 dimensions, repeating the data:
    a = np.repeat(a[...,None],3,axis=2).astype(np.uint8)
    # Scale to 0-255:
    a = 255*a
    im = PIL.Image.fromarray(a)
    

    然后im.show() 将显示正确的图像。

    【讨论】:

      【解决方案2】:

      将结果转换为 NumPy 的 uint8 即可:

      from skimage import data, color, feature, util
      import tkinter as tk
      import numpy as np
      from PIL import ImageTk, Image
      from scipy.ndimage import binary_fill_holes
      
      rgb = data.hubble_deep_field()
      gray = color.rgb2grey(rgb)
      edges = feature.canny(gray, sigma=3)
      filled_objects = binary_fill_holes(edges)
      
      img_bool = Image.fromarray(filled_objects)
      img_uint8 = Image.fromarray(util.img_as_ubyte(filled_objects))
      
      root = tk.Tk()
      photo_bool = ImageTk.PhotoImage(img_bool)
      photo_uint8 = ImageTk.PhotoImage(img_uint8)
      label_bool = tk.Label(root, image=photo_bool).grid(row=1, column=1)
      label_uint8 = tk.Label(root, image=photo_uint8).grid(row=1, column=2)
      root.mainloop()
      

      【讨论】:

        猜你喜欢
        • 2016-07-25
        • 2017-06-25
        • 2013-08-31
        • 2016-01-11
        • 2016-05-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        相关资源
        最近更新 更多