1. import numpy as np
    2. import cv2
    3. import os
    4. from sklearn.model_selection import train_test_split
    5. def open_img(path):
    6. imgList = [] #图片
    7. labels = [] #各图片对应的表情
    8. label = [] #仅表情(无重复)
    9. for file in os.listdir(path):
    10. if file == '.anonr' or file == '.htaccess':
    11. continue
    12. position = path+'/'+file
    13. for parent, dirnames, filenames in os.walk(position):
    14. for filename in filenames:
    15. if filename == '.htaccess':
    16. continue
    17. fileList = filename.split('_')
    18. if fileList[2] not in label:
    19. label.append(fileList[2])
    20. labels.append(label.index(fileList[2]))
    21. img = cv2.imread(position+'/'+filename,cv2.IMREAD_GRAYSCALE)
    22. img = cv2.resize(img, (250, 350))
    23. imgList.append(img)
    24. return imgList,labels
    25. def train_and_test(imgList,labels):
    26. x_train,x_test,y_train,y_test = train_test_split(imgList,np.array(labels),test_size=0.3,random_state=42,stratify=np.array(labels))
    27. recognizer = cv2.face.FisherFaceRecognizer_create()
    28. recognizer.train(x_train,y_train)
    29. right = 0
    30. false = 0
    31. for cnt in range(len(y_test)):
    32. test_label = recognizer.predict(x_test[cnt])
    33. if((test_label == y_test[cnt]).any()):
    34. right += 1
    35. else:
    36. false += 1
    37. return right/(right+false)
    38. if __name__ == '__main__':
    39. path = "../faces"
    40. imgList,labels = open_img(path)
    41. print('表情识别的准确率为:',train_and_test(imgList,labels))