我对 Python 不太熟练,这是我第一次使用 Tkinter 来创建一个用户界面,用于显示我的数字分类程序在 mnist 数据集上的结果。我有一个关于在 Tkinter 中显示来自 numpy 数组而不是来自我电脑上的文件路径的图像的问题。我尝试过的当前代码是:
img = PhotoImage(test_images[0]) window.create_image(20,20, image=img)
然而,这没有成功,但我不知道还有什么其他方法可以尝试。下面是一张从数组中绘制的图像的图片,我希望在 UI 中显示它,图片下方只是我加载和绘制图像的代码,以防有帮助。抱歉如果这是我忽略的简单修复,我对此非常新手。谢谢
https://i.gyazo.com/8962f16b4562c0c15c4ff79108656087.png
# 加载数据集train_images = mnist.train_images() #训练数据train_labels = mnist.train_labels() #训练标签test_images = mnist.test_images() # 测试训练图像test_labels = mnist.test_labels()# 训练数据标签# 归一化图像的像素值,使网络更易于训练train_images = (train_images/255) - 0.5test_images = (test_images/255) - 0.5# 将图像展平为784维向量,以便传入神经网络train_images = train_images.reshape((-1, 784))test_images = test_images.reshape((-1, 784))# 打印图像形状print(train_images.shape) # 60,000行和784列print(test_images.shape)
for i in range(0,15): first_image = test_images[i] first_image = np.array(first_image, dtype='float') pixels = first_image.reshape((28,28)) plt.imshow(pixels) plt.show()
错误信息:
Traceback (most recent call last): File "C:/Users/Ben/Desktop/Python Projects/newdigitclassifier/classifier.py", line 122, in <module> img = PhotoImage(test_images[0]) File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 3545, in __init__ Image.__init__(self, 'photo', name, cnf, master, **kw) File "C:\Users\Ben\AppData\Local\Programs\Python\Python36\lib\tkinter\__init__.py", line 3491, in __init__ if not name:ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
回答:
这里是解决方案:
import cv2import tkinter as tkfrom PIL import Image, ImageTkimport tensorflow as tf# 初始化窗口和图像属性HEIGHT = 200WIDTH = 200IMAGE_HEIGHT = 200IMAGE_WIDTH = 200# 加载mnist数据集mnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()def imageShow(index): root = tk.Tk() # 将图像调整为更大的图像 img_array = cv2.resize(x_train[index], (IMAGE_HEIGHT,IMAGE_WIDTH), interpolation = cv2.INTER_AREA) img = ImageTk.PhotoImage(image=Image.fromarray(img_array)) canvas = tk.Canvas(root,width=WIDTH,height=HEIGHT) canvas.pack() canvas.create_image(IMAGE_HEIGHT/2,IMAGE_WIDTH/2, image=img) root.mainloop()imageShow(5)
数据集已从tensorflow导入。我添加了一个额外的功能来调整图像大小。结果看起来像这样