描述: 我目前正在开发一个人脸识别项目,使用 Tkinter 作为 GUI,使用 OpenCV 在 Visual Studio 上进行图像处理。我的目标是使用图像数据集训练模型并显示一条弹出消息,指示训练完成。但是,我遇到了一个问题,当我单击“训练数据”按钮时没有任何反应。窗口打不开,也没有显示错误消息。
代码:
from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import mysql.connector
import cv2
import os
import numpy as np
class Train:
def __init__(self, root):
self.root = root
self.root.geometry("1530x790+0+0")
self.root.title("Face Recognition System")
title_lbl= Label(self.root, text= "TRAIN DATA SET",font=("times new roman",35,"bold"), bg="white",fg="darkgreen")
title_lbl.place(x=0,y=0,width=1530, height=45)
img_top= Image.open(r"C:\Users\The-Javeira\Desktop\test\images\b.jpg")
img_top= img_top.resize((1530,325), Image.ANTIALIAS)
self.photoimg_top= ImageTk.PhotoImage(img_top)
f_lbl2= Label(self.root,image=self.photoimg_top)
f_lbl2.place(x=0,y=55,width=1530,height=325)
#button
b1_1=Button(self.root ,text="TRAIN DATA", command=self.train_classifier, cursor="hand2",font=("times new roman",30,"bold"), bg="red",fg="white")
b1_1.place(x=0,y=380,width=1530,height=60)
img_bottom= Image.open(r"C:\Users\The-Javeira\Desktop\test\images\train2.JPEG")
img_bottom= img_bottom.resize((1530,325), Image.ANTIALIAS)
self.photoimg_bottom= ImageTk.PhotoImage(img_bottom)
f_lbl2= Label(self.root,image=self.photoimg_bottom)
f_lbl2.place(x=0,y=440 ,width=1530,height=325)
def train_classifier(self):
data_dir=("images data")
path=[os.path.join(data_dir,file) for file in os.listdir(data_dir)]
faces=[]
ids=[]
for image in path:
img=Image.open(image).convert('L') #Gray Scale Image
imageNp=np.array(img,'uint8')
id=int(os.path.split(image)[1].split('.')[1])
faces.append(imageNp)
ids.append(id)
cv2.imshow("Training Data",imageNp)
cv2.waitKey(1)==13
ids=np.array(ids)
#============Train the classifier and Save ===========
clf=cv2.face.LBPHFaceRecognizer_create()
clf.train(faces,ids)
clf.write("Classifier.xml")
messagebox.showinfo("Result","Training Datasets Completed!!")
cv2.destroyAllWindows()
if __name__ == "__main__":
root = Tk()
obj = Train(root)
root.mainloop()
预期行为: 当我单击“训练数据”按钮时,我希望打开一个窗口,显示训练进度并显示图像。 训练完成后,我预计会弹出一条消息“训练数据集已完成!!”出现。 分类器应在指定目录中保存为“Classifier.xml”。
实际行为: 当我单击“训练数据”按钮时,没有任何反应。该窗口不会打开,并且没有显示错误消息。 没有出现预期的指示训练完成的弹出消息。 指定目录中没有创建“Classifier.xml”文件
附加信息 所有必需的依赖项均已安装。
尝试在不同的进程或线程中执行训练方法,并在线程完成时显示消息。我相信你的问题是你在 gui 中使用了 for 循环。
首先卸载 pip uninstall opencv-contrib-python 然后重新安装 pip install opencv-contrib python 关于这个“clf=cv2.face.LBPHFaceRecognizer_create()” 写, “clf=cv2.face.LBPHFaceRecognizer.create()” 看看它是否有效