从scikit数组转换为PIL photoimage的图像被扭曲

问题描述 投票:3回答:2

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

我试过检查数组的形状,它们是一样的。我尝试打印出图像,fill_objects是正确的图像,而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在右边

scikit to PIL image conversion distortion

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

python-3.x tkinter python-imaging-library scikit-image
2个回答
2
投票

问题是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()将显示正确的图像。


0
投票

将结果转换为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()

result

© www.soinside.com 2019 - 2024. All rights reserved.