添加异常处理是一个好方法。在################# added ####################
# create window
# but Maybe you did.
cv2.namedWindow('im')
############################################
recognizer = cv2.createLBPHFaceRecognizer()
recognizer.load('/home/atul/Desktop/Atul/face reg/Face-Recognition-
master/trainer/trainer.yml')
cascadePath = "/home/atul/Desktop/Atul/face reg/Face-Recognition-
master/Classifiers/face.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
path = '/home/cdi/Downloads/training_data/Dhoni'
cam = cv2.VideoCapture('/home/atul/Downloads/M.S Dhoni.mp4')
################# added ####################
# check the CAM
if cam.isOpened() == False:
print ('Can\'t open the CAM')
exit()
############################################
font = cv2.cv.InitFont(cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1) #Creates a font
while True:
ret, im = cam.read()
################# added ####################
# if im is null break
if im is None:
break
############################################
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
faces=faceCascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100), flags=cv2.CASCADE_SCALE_IMAGE)
for(x,y,w,h) in faces:
nbr_predicted= recognizer.predict(gray[y:y+h,x:x+w])
cv2.rectangle(im,(x-50,y-50),(x+w+50,y+h+50),(225,0,0),2)
if(nbr_predicted==7):
nbr_predicted='Obama'
elif(nbr_predicted==2):
nbr_predicted='Dhoni'
cv2.cv.PutText(cv2.cv.fromarray(im),str(nbr_predicted)+" "+str(conf), (x,y+h),font, 255) #Draw the text
cv2.imshow('im',im)
cv2.waitKey(10)
################# added ####################
#close cam handle
cam.release()
#close window of all
cv2.destroyAllWindows()
############################################