ImageTk.PhotoImage无法正常显示图像

时间:2012-11-17 14:43:38

标签: python image numpy image-processing tkinter

我正在尝试将numpy数组转换为PIL格式然后将其显示为标签!我可以为原始图像执行此操作但是在我拍摄fft和fftshift之后我无法正确显示它。!

image1=Image.open('sam.jpg')
image1 = image1.resize((120, 120), Image.ANTIALIAS)
Labe(image=photo1).grid(row=0, column=7, columnspan=3, rowspan=2, padx=5, pady=5)
ipx1=np.array(image1)
(w,h)=ipx1.shape #120x20

现在我用我的形象做了一些事情:

img_fft=np.fft.fft2(image1)
img_shift=np.fft.fftshift(image1_fft)
img_plot1=np.log10(1+abs(img_shift))


foto=Image.fromarray((img_plot1*255.999).round().astype(np.uint8),mode='L')
photo=ImageTk.PhotoImage(foto)
Label(image=photo).grid(row=0, column=10, columnspan=4, rowspan=2, padx=5, pady=5)

但不是: correct imag

我得到了:

wrong image

任何想法?

1 个答案:

答案 0 :(得分:2)

当你把东西卖回uint8时,你会遇到溢出问题。

您正在使用(img_plot1*255.999).round().astype(np.uint8)转换,但是对于接近或接近1的值(大于0.998),这会溢出

假设img_plot1将始终包含介于0和1之间的值,我认为您只想做其中任何一项:

(img_plot1 * 255.99).astype(np.uint8)

(img_plot1 * 255).round().astype(np.uint8) 

round调用将向上或向下舍入,而纯int类型调用实际上是floor调用。

但是,只需从输出图像中的“波段”进行猜测,输入数据就会溢出并多次“包裹”。因此,输入数据的范围可能大于0-1。

因此,如果您不想担心img_plot1中确切的值范围,您可以根据其范围将其重新调整为0-255:

rescaled = 255 * (img_plot1 - img_plot1.min()) / img_plot1.ptp()
foto = Image.fromarray(rescaled.astype(np.uint8), mode='L')

您也可以使用np.digitize来重新调整数组,但它的可读性会降低,即使用它。如果要剪切高于和低于阈值的值(例如0和255),也请查看np.clip