从Github(https://github.com/atulapra/Emotion-detection)找到的代码用于情感检测。我想对其进行一些更改,并希望与Tkinter结合使用,以方便用户交互。如下图所示。在这里,我为tk窗口编写了一些代码:
win = Tk()
win.title('EMOTIBOT')
win.config(background = "#D9D9D9")
win.resizable(width=FALSE, height=FALSE)
#frame1 for webcamera
frame1 = Frame(win, width=600, bg="black",height=300, padx=10, pady=10,highlightbackground="grey", highlightcolor="black", highlightthickness=5)
frame1.pack(side=LEFT ,fill=Y,padx=10, pady=10)
这里我对原始代码进行了一些更改:
if mode == "display":
model.load_weights('model.h5')
# prevents openCL usage and unnecessary logging messages
cv2.ocl.setUseOpenCL(False)
# dictionary which assigns each label an emotion (alphabetical order)
emotion_dict = {0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"}
# start the webcam feed
cap = cv2.VideoCapture(0)
def show_frame():
_, frame = cap.read()
frame = cv2.flip(frame, 1)
#cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
#while True:
facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = facecasc.detectMultiScale(cv2image,scaleFactor=1.3, minNeighbors=5)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)
prediction = model.predict(cropped_img)
maxindex = int(np.argmax(prediction))
cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imshow('Video', cv2.resize(frame,(1600,960),interpolation = cv2.INTER_CUBIC))
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, show_frame)
#Capture video frames
lmain = Label(frame1)
lmain.grid(row=0, column=0)
show_frame() #Display 2
win.mainloop()
这将打开2个窗口。第一个窗口是Tk窗口,在检测到的情绪上没有矩形。第二个窗口显示检测到的情绪的矩形。为什么第一个tk窗口在面上不显示矩形?
如果您需要我的脚本文件,请在这里。 (https://drive.google.com/file/d/1m7tLFxHF_hO0VLVb8FgAf-4lJKMxFLxA/view?usp=sharing)
我是OpenCV和Tk的新手。请帮助我。
将我们的讨论总结为答案that can be accepted:
cv2.imshow
以摆脱第二个窗口img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA))
以检测到的脸部以正确的颜色显示框。