对先前识别人脸的代码进行简单的修改

  1. # # -*- coding:utf-8 -*-
  2. import cv2
  3. import os
  4. import numpy as np
  5. # 检测人脸
  6. def detect_face(img):
  7. # 将测试图像转换为灰度图像,因为opencv人脸检测器需要灰度图像
  8. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  9. # 加载OpenCV人脸检测分类器Haar
  10. face_cascade = cv2.CascadeClassifier('D:\\mypython\\workspace\\opencv-master\\opencv-master\\data\\haarcascades\\haarcascade_frontalface_default.xml')
  11. # 检测多尺度图像,返回值是一张脸部区域信息的列表(x,y,宽,高)
  12. faces = face_cascade.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=5)
  13. # 如果未检测到面部,则返回原始图像
  14. if (len(faces) == 0):
  15. return None, None
  16. # 目前假设只有一张脸,xy为左上角坐标,wh为矩形的宽高
  17. (x, y, w, h) = faces[0]
  18. # 返回图像的正面部分
  19. return gray[y:y + w, x:x + h], faces[0]
  20. # 该函数将读取所有的训练图像,从每个图像检测人脸并将返回两个相同大小的列表,分别为脸部信息和标签
  21. def prepare_training_data(data_folder_path):
  22. # 获取数据文件夹中的目录(每个主题的一个目录)
  23. dirs = os.listdir(data_folder_path)
  24. # 两个列表分别保存所有的脸部和标签
  25. faces = []
  26. labels = []
  27. # 浏览每个目录并访问其中的图像
  28. for dir_name in dirs:
  29. # dir_name(str类型)即标签
  30. label = int (dir_name)
  31. # 建立包含当前主题主题图像的目录路径
  32. subject_dir_path = data_folder_path + "/" + dir_name
  33. # 获取给定主题目录内的图像名称
  34. subject_images_names = os.listdir(subject_dir_path)
  35. # 浏览每张图片并检测脸部,然后将脸部信息添加到脸部列表faces[]
  36. for image_name in subject_images_names:
  37. # 建立图像路径
  38. image_path = subject_dir_path + "/" + image_name
  39. # 读取图像
  40. image = cv2.imread(image_path)
  41. # 显示图像0.1s
  42. cv2.imshow("Training on image...", image)
  43. cv2.waitKey(1000)
  44. # 检测脸部
  45. face, rect = detect_face(image)
  46. # 我们忽略未检测到的脸部
  47. if face is not None:
  48. # 将脸添加到脸部列表并添加相应的标签
  49. faces.append(face)
  50. labels.append(label)
  51. cv2.waitKey(1)
  52. cv2.destroyAllWindows()
  53. # 最终返回值为人脸和标签列表
  54. return faces, labels
  55. # 调用prepare_training_data()函数
  56. faces, labels = prepare_training_data("D:\\New_desktop\\train_data")
  57. # 创建LBPH识别器并开始训练,当然也可以选择Eigen或者Fisher识别器
  58. face_recognizer = cv2.face.LBPHFaceRecognizer_create()
  59. face_recognizer.train(faces, np.array(labels))
  60. # 根据给定的(x,y)坐标和宽度高度在图像上绘制矩形
  61. def draw_rectangle(img, rect):
  62. (x, y, w, h) = rect
  63. cv2.rectangle(img, (x, y), (x + w, y + h), (128, 128, 0), 2)
  64. # 根据给定的(x,y)坐标标识出人名
  65. def draw_text(img, text, x, y):
  66. cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
  67. # 建立标签与人名的映射列表(标签只能为整数)
  68. subjects = ["li na en","james"]
  69. # 此函数识别传递的图像中的人物并在检测到的脸部周围绘制一个矩形及其名称
  70. def predict(test_img):
  71. # 生成图像的副本,这样就能保留原始图像
  72. img = test_img.copy()
  73. # 检测人脸
  74. face, rect = detect_face(img)
  75. # 预测人脸
  76. label = face_recognizer.predict(face)
  77. # 获取由人脸识别器返回的相应标签的名称
  78. label_text = subjects[label[0]]
  79. # 在检测到的脸部周围画一个矩形
  80. draw_rectangle(img, rect)
  81. # 标出预测的名字
  82. draw_text(img, label_text, rect[0], rect[1] - 5)
  83. # 返回预测的图像
  84. return img
  85. def show_test(filepath):
  86. # 加载测试图像
  87. dirs = os.listdir(filepath)
  88. for path in dirs:
  89. image_path = filepath + "/" +path
  90. test_img1 = cv2.imread(image_path)
  91. # 执行预测
  92. predicted_img1 = predict(test_img1)
  93. # 显示两个图像
  94. cv2.imshow(subjects[0], predicted_img1)
  95. cv2.waitKey(0)
  96. cv2.destroyAllWindows()
  97. show_test("D:\\New_desktop\\test_data")

在每一类只有20张图片数据的左右,就有还可以的识别结果了

尝试加上摄像头的识别

  1. import cv2
  2. cap = cv2.VideoCapture(0)
  3. while(True):
  4. # Capture frame-by-frame
  5. ret, frame = cap.read()
  6. # Our operations on the frame come here
  7. gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
  8. xmlfile = 'D:\\mypython\\workspace\\opencv-master\\opencv-master\\data\\haarcascades\\haarcascade_frontalface_default.xml'
  9. face_cascade = cv2.CascadeClassifier(xmlfile)
  10. faces = face_cascade.detectMultiScale(
  11. gray,
  12. scaleFactor=1.15,
  13. minNeighbors=5,
  14. minSize=(5, 5),
  15. )
  16. print("发现{0}个目标!".format(len(faces)))
  17. for (x, y, w, h) in faces:
  18. cv2.rectangle(frame, (x, y), (x + w, y + w), (0, 255, 0), 2)
  19. cv2.imshow("frame", frame)
  20. # Display the resulting frame
  21. if cv2.waitKey(1) & 0xFF == ord('q'):
  22. break
  23. # When everything done, release the capture
  24. cap.release()
  25. cv2.destroyAllWindows()