【发布时间】:2020-10-18 19:04:07
【问题描述】:
我已经为我的 Keras 模型实现了这个代码,它可以正常工作,但现在我想为我的 PyTorch 模型实现这个代码,但是我无法配置它来进行预测,下面是我的完整代码,我需要有关分类功能的帮助:
# importing libraries
import tkinter as tk
from tkinter import *
# import PIL
from tkinter import filedialog
import numpy
from PIL import Image, ImageTk
import torch
# importing model
model=torch.load('corelK_model_0.pt')
classes = {
0:'africa',
1: 'beach',
2: 'tallbuilding',
3: 'buses',
4: 'dinosaurs',
5: 'elephants',
6: 'Roses',
7: 'horses',
8: 'mountains',
9: 'food'
}
def upload_image():
file_path = filedialog.askopenfilename()
uploaded = Image.open(file_path)
uploaded.thumbnail(((top.winfo_width() / 2.25, (top.winfo_height() / 2.25))))
im = ImageTk.PhotoImage(uploaded)
sign_image.configure(image=im)
sign_image.image = im
label.configure(text=' ')
show_classify_button(file_path)
def show_classify_button(file_path):
classify_btn = Button(top, text="Classify Image", command=lambda: classify(file_path), padx=10, pady=5)
classify_btn.configure(background="#364156", foreground="white", font=('arial', 10, 'bold'))
classify_btn.place(relx=0.79, rely=0.46)
def classify(file_path):
image = Image.open(file_path)
image = image.resize((32, 32))
image = numpy.expand_dims(image, axis=0)
image = numpy.array(image)
pred = model.predict_classes([image])[0]
sign = classes[pred]
print(sign)
label.configure(foreground='#011638', text=sign)
# initialize GUI
top = tk.Tk() # calling the constructor or creating the object of tk class
top.geometry('800x600') # set height and width
top.title("Image Classification CIFAR10")
top.configure(background="#CDCDCD")
# set Heading
heading = Label(top, text="Image Classifier", pady=20, font=('arial', 20, 'bold'))
heading.configure(background="#CDCDCD", foreground='#364156')
heading.pack()
upload = Button(top, text="Upload an image", command=upload_image, padx=10, pady=5)
heading.configure(background="#364156", foreground='white', font=('arial', 10, 'bold'))
upload.pack(side=BOTTOM, pady=50)
# upload image
sign_image = Label(top)
sign_image.pack(side=BOTTOM, expand=True)
# predicted class
label = Label(top, background="#CDCDCD", font=('arial', 15, 'bold'))
label.pack(side=BOTTOM, expand=True)
top.mainloop()
我使用的模型是迁移学习后的VGG16,我使用torch.save保存了它。
【问题讨论】:
标签: python tkinter deep-learning computer-vision pytorch