OpenCV人脸识别程序崩溃

时间:2020-03-11 18:13:00

标签: python opencv crash tk

这是代码(我删除了所有不重要的内容)

closed = False

faceClassifier = cv2.CascadeClassifier('face.xml')
eyeClassifier = cv2.CascadeClassifier('eye.xml')
bodyClassifier = cv2.CascadeClassifier('body.xml')
cap = cv2.VideoCapture(0)
def drawBox():
    while closed == False:
        ret, img = cap.read()
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = faceClassifier.detectMultiScale(img, 1.3, 5)
        for (x,y,w,h) in faces:
            cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = img[y:y+h, x:x+w]

            eyes = eyeClassifier.detectMultiScale(roi_gray)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)
        cv2.imshow('img',img)

def stopProgram():
    closed = True

tkWindow = Tk()  
tkWindow.geometry('800x800')  
tkWindow.title('Machine Learning Face Detection')



button = Button(tkWindow,
text = 'Stop Program',
command = stopProgram)  
button.pack()  

button = Button(tkWindow,
text = 'Start Program',
command = drawBox)  
button.pack() 

tkWindow.mainloop()
cap.release()
cv2.destroyAllWindows()

一旦我遇到启动程序错误,相机窗口就会打开灰色,然后崩溃。有人知道为什么吗?我无法弄清楚,但是在尝试实现“停止”按钮之前,它一直在起作用。

1 个答案:

答案 0 :(得分:0)

第一个问题是您没有在函数closeddrawBox中将stopProgram标记为全局变量。另一个问题是drawBox中的while循环,这将导致程序停止响应,从而使“停止程序”按钮不可用。您需要使用tkWindow.afterHere是在cv2.VideoCapture中显示来自tkWindow的视频帧的示例。