1 回答
TA贡献1827条经验 获得超9个赞
PhotoImage这是在将图像分配给函数中的局部变量时删除图像的错误。
你必须将它分配给全局变量(如果你有很多图像,它可以是列表)或分配给你用来显示它的小部件 -label.photo = image
我可以测试它,但这是用于label.photo = image解决此问题的版本
它还使用for-loop 来创建标签并将它们保存在列表中。
但是当你使用label.photo = imagethen list 是没有必要的。List 仅用于访问标签以在创建新标签之前删除旧标签。
import tkinter as tk # PEP8: `import *` is not preferred
from tkinter import filedialog
# --- functions ---
def train_button():
os.system('python3 extract_embeddings.py --dataset dataset --embeddings output/embeddings.pickle --detector face_detection_model --embedding-model openface_nn4.small2.v1.t7')
os.system('python3 train_model.py --embeddings output/embeddings.pickle --recognizer output/recognizer.pickle --le output/le.pickle')
messagebox.showinfo("INFO","Training completed")
def select_photo():
#global all_labels
root.filename = filedialog.askopenfilename(initialdir="test", title ="Select a photo", filetypes=(("all files","*.*"),("png files","*.png"),("jpeg files","*.jpeg")))
output = subprocess.check_output("python3 recognize.py --detector face_detection_model --embedding-model openface_nn4.small2.v1.t7 --recognizer output/recognizer.pickle --le output/le.pickle --image "+root.filename, shell=True)
output = output.decode('utf-8')
pic_name = output.split('\n')[0]
# remove previous labels
for label in all_labels:
label.destroy()
for number in range(3):
#filename = f"images/{pic_name}/{pic_name}{number+1}.jpeg" # f-string (Python 3.6+)
filename = "images/{}/{}{}.jpeg".format(pic_name, pic_name, number+1) # (Python 2.7, 3.0+)
image = ImageTk.PhotoImage(Image.open(filename))
label = tk.Label(image=image)
label.photo = image # assign to class variable to resolve problem with bug in `PhotoImage`
label.grid(row=1, column=number)
all_labels.append(label)
# --- main ---
all_labels = []
root = tk.Tk()
button1 = tk.Button(root, text="Train", command=train_button)
button1.grid(row=0, column=0)
button2 = tk.Button(root, text="Recognise from image", command=select_photo)
button2.grid(row=0, column=1)
root.mainloop()
添加回答
举报