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. # 图片
    7. img_list = []
    8. # 各图片对应的人名
    9. labels_ = []
    10. # 仅人名(无重复)
    11. label = []
    12. for file in os.listdir(path_):
    13. if file == '.anonr' or file == '.htaccess':
    14. continue
    15. label.append(file)
    16. position = path_+'/'+file
    17. for parent, dirnames, filenames in os.walk(position):
    18. for filename in filenames:
    19. if filename == '.htaccess':
    20. continue
    21. labels_.append(len(label)-1)
    22. img = cv2.imread(position+'/'+filename, cv2.IMREAD_GRAYSCALE)
    23. img = cv2.resize(img, (250, 350))
    24. img_list.append(img)
    25. return img_list, labels_
    26. def train_and_test(img_list, labels_):
    27. x_train, x_test, y_train, y_test = train_test_split(img_list, np.array(labels_),
    28. test_size=0.3, random_state=42, stratify=np.array(labels))
    29. recognizer = cv2.face.FisherFaceRecognizer_create()
    30. recognizer.train(x_train, y_train)
    31. right = 0
    32. false = 0
    33. for cnt in range(len(y_test)):
    34. test_label = recognizer.predict(x_test[cnt])
    35. if (test_label == y_test[cnt]).any():
    36. right += 1
    37. else:
    38. false += 1
    39. return right/(right+false)
    40. if __name__ == '__main__':
    41. path = "../faces"
    42. imgList, labels = open_img(path)
    43. print('人脸识别的准确率为:', train_and_test(imgList, labels))