当前位置:   article > 正文

OpenCV人脸识别项目(训练+测试)

OpenCV人脸识别项目(训练+测试)

图片来自网上,如果侵权,告知则删除

>>>>>>>>批量修改文件名(常见文件操作,可以学习一下)

  1. import os
  2. path = './opencv/data/images'
  3. # 获取该目录下所有文件,存入列表中
  4. labelList = os.listdir(path)
  5. n = 0
  6. count = 1
  7. for label in labelList:
  8. print(label)
  9. dirPath = os.path.join(path,label)
  10. for img_name in os.listdir(dirPath):
  11. old_img_path = os.path.join(dirPath,img_name)
  12. # 设置新文件名
  13. name = str(n+1)+'.' + str(label) + '.'+ str(count) +'.jpg'
  14. # new_img_path = os.path.join(dirPath,name)
  15. new_img_path = dirPath + '/' + name
  16. print(old_img_path)
  17. print(new_img_path)
  18. os.rename(old_img_path, new_img_path)
  19. count +=1
  20. n+=1

>>>>>>>>进入正题 

(一)读取图片

  1. #导入cv模块
  2. import cv2 as cv
  3. #读取图片
  4. img = cv.imread('face1.png')
  5. #显示图片
  6. cv.imshow('read_img',img)
  7. #等待
  8. cv.waitKey(0)
  9. #释放内存
  10. cv.destroyAllWindows()

(二)灰度转换

  1. #导入cv模块
  2. import cv2 as cv
  3. #读取图片
  4. img = cv.imread('face1.png')
  5. #灰度转换
  6. gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
  7. #显示灰度图片
  8. cv.imshow('gray_img',gray_img)
  9. #保存灰度图片
  10. cv.imwrite('gray_face1.png',gray_img)
  11. #显示图片
  12. cv.imshow('read_img',img)
  13. #等待
  14. cv.waitKey(0)
  15. #释放内存
  16. cv.destroyAllWindows()

(三)修改尺寸

  1. #导入cv模块
  2. import cv2 as cv
  3. #读取图片
  4. img = cv.imread('face1.png')
  5. #修改尺寸
  6. resize_img = cv.resize(img,dsize=(200,200))
  7. #显示原图
  8. cv.imshow('img',img)
  9. #显示修改后的
  10. cv.imshow('resize_img',resize_img)
  11. #打印原图尺寸大小
  12. print('未修改',img.shape)
  13. #打印修改后的大小
  14. print('修改后',resize_img.shape)
  15. #等待
  16. while True:
  17. if ord('q') == cv.waitKey(0):
  18. break
  19. cv.waitKey(0)
  20. #灰度转换
  21. gray_img = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
  22. #显示灰度图片
  23. cv.imshow('gray_img',gray_img)
  24. #保存灰度图片
  25. cv.imwrite('gray_face1.png',gray_img)
  26. #显示图片
  27. cv.imshow('read_img',img)
  28. #等待
  29. cv.waitKey(0)
  30. #释放内存
  31. cv.destroyAllWindows()

(四)绘制矩形

  1. #导入cv模块
  2. import cv2 as cv
  3. #读取图片
  4. img = cv.imread('face1.png')
  5. #坐标
  6. x,y,w,h = 50,50,50,50
  7. #绘制矩形
  8. cv.rectangle(img,(x,y,x+w,y+h),color=(0,0,255),thickness=1)
  9. #绘制圆形
  10. cv.circle(img,center=(x+w,y+h),radius=50,color=(255,0,0),thickness=2)
  11. #显示
  12. cv.imshow('re_img',img)
  13. #等待
  14. while True:
  15. if ord('q') == cv.waitKey(0):
  16. break
  17. #释放内存
  18. cv.destroyAllWindows()

(五)人脸检测

  1. #导入cv模块
  2. import cv2 as cv
  3. def face_detect_demo(img):
  4. gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
  5. # 分类器
  6. face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
  7. face = face_detect.detectMultiScale(gray,1.01,5,0,(100,100),(300,300))
  8. for x,y,w,h in face:
  9. cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
  10. cv.imshow('res',img)
  11. # 读取图片
  12. img = cv.imread('face1.png')
  13. # 检测函数
  14. face_detect_demo(img)
  15. # 等待
  16. while True:
  17. if ord('q') == cv.waitKey(0):
  18. break
  19. # 释放内存
  20. cv.destroyAllWindows()

(六)检测多个人脸

  1. #导入cv模块
  2. import cv2 as cv
  3. def face_detect_demo(img):
  4. gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
  5. # 分类器
  6. # face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
  7. face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
  8. # face = face_detect.detectMultiScale(gray,1.1,5,0,(10,10),(100,100))
  9. face = face_detect.detectMultiScale(gray,1.1)
  10. for x,y,w,h in face:
  11. cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
  12. cv.imshow('res',img)
  13. # 读取图片
  14. img = cv.imread('multi_face1.png')
  15. # 检测函数
  16. face_detect_demo(img)
  17. # 等待
  18. while True:
  19. if ord('q') == cv.waitKey(0):
  20. break
  21. # 释放内存
  22. cv.destroyAllWindows()

(七)视频检测

  1. #导入cv模块
  2. import cv2 as cv
  3. def face_detect_demo(img):
  4. gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
  5. # 分类器
  6. # face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
  7. face_detect = cv.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_default.xml')
  8. # face = face_detect.detectMultiScale(gray,1.1,5,0,(10,10),(100,100))
  9. face = face_detect.detectMultiScale(gray,1.1)
  10. for x,y,w,h in face:
  11. cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
  12. cv.imshow('res',img)
  13. # 读取摄像头
  14. cap = cv.VideoCapture(0)
  15. # cap = cv.VideoCapture("face.mp4")
  16. # 循环
  17. while True:
  18. flag,frame = cap.read()
  19. if not flag:
  20. break
  21. face_detect_demo(frame)
  22. if ord('q') == cv.waitKey(0):
  23. break
  24. # 释放内存
  25. cv.destroyAllWindows()
  26. # 释放摄像头
  27. cap.release()

 (八)拍照保存

  1. # 导入模块
  2. import cv2
  3. import os
  4. # 摄像头
  5. cap = cv2.VideoCapture(0)
  6. num = 1
  7. while(cap.isOpened()):#检测是否在开启状态
  8. flag,frame = cap.read() # 得到每帧图像
  9. cv2.imshow("Capture_Test",frame) #显示图像
  10. k = cv2.waitKey(1) & 0xFF #按键判断
  11. if k == ord('s'):#保存
  12. path = os.path.join('E:/faceRecognition/save_img/',str(num)+"_name"+".jpg")
  13. print(path)
  14. cv2.imwrite(path,frame)
  15. print("success to save"+str(num)+".jpg")
  16. print("----------------")
  17. num+=1
  18. elif k == ord(' '):
  19. break
  20. # 释放摄像头
  21. cap.release()
  22. # 释放内存
  23. cv2.destroyAllWindows()

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>准备数据集>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

训练集train

 注意:第一个.前面是id,后面是label

测试集test

(九)数据训练

  1. import os
  2. import cv2
  3. from PIL import Image
  4. import numpy as np
  5. def getImageAndLabels(path):
  6. #存储人脸数据
  7. facesSamples = []
  8. # 储存姓名数据
  9. ids = []
  10. #储存图片信息
  11. # imagePaths = [(os.path.join(path,f) for f in os.listdir(path))]
  12. imagePaths = []
  13. for f in os.listdir(path):
  14. img_path = path+'/' + f
  15. imagePaths.append(img_path)
  16. #加载分类器
  17. face_detect = cv2.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
  18. # print(imagePaths)
  19. #遍历列表中的图片
  20. for imagePath in imagePaths:
  21. # print(imagePath)
  22. #打开图片,灰度化PIL有九种不同模式
  23. PIL_img = Image.open(imagePath).convert('L')
  24. #将图像转换为数组,以黑白深浅
  25. img_numpy = np.array(PIL_img,'uint8')
  26. #保存图片人脸检测
  27. faces = face_detect.detectMultiScale(img_numpy)
  28. #获取每张图片的id和姓名
  29. id = int(os.path.split(imagePath)[1].split('.')[0])
  30. #预测无面容的图片
  31. for x,y,w,h in faces:
  32. ids.append(id)
  33. facesSamples.append(img_numpy[y:y+h,x:x+w])
  34. #打开脸部特征和id
  35. # print('id:',id)
  36. # print('fs:',facesSamples)
  37. return facesSamples,ids
  38. if __name__ == '__main__':
  39. # 图片路径
  40. path = './opencv/data/images'
  41. # 获取该目录下所有文件,存入列表中
  42. labelList = os.listdir(path)
  43. facesList = []
  44. idsList = []
  45. for label in labelList:
  46. dirPath = path + '/' + str(label)
  47. # print('dirPath',dirPath)
  48. # 获取图像数组和id标签数组和姓名
  49. faces,ids = getImageAndLabels(dirPath)
  50. # print(faces)
  51. # print(ids)
  52. for face in faces:
  53. facesList.append(face)
  54. for id in ids:
  55. idsList.append(id)
  56. # # 加载识别器
  57. # recognizer = cv2.face.LBPHFaceRecognizer_create()
  58. # #训练
  59. # recognizer.train(faces,np.array(ids))
  60. # #保存文件
  61. # recognizer.write("trainer/trainer.yml")
  62. # print(facesList)
  63. # print(idsList)
  64. # 加载识别器
  65. recognizer = cv2.face.LBPHFaceRecognizer_create()
  66. #训练
  67. recognizer.train(facesList,np.array(idsList))
  68. #保存文件
  69. recognizer.write("trainer/trainer.yml")

(十)人脸识别

  1. import cv2
  2. import numpy as np
  3. import os
  4. # coding=utf-8
  5. import urllib
  6. import urllib.request
  7. import hashlib
  8. #加载训练数据集文件
  9. recogizer=cv2.face.LBPHFaceRecognizer_create()
  10. recogizer.read('trainer/trainer.yml')
  11. names=[]
  12. #准备识别的图片
  13. def face_detect_demo(img):
  14. gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)#转换为灰度
  15. face_detector = cv2.CascadeClassifier('F:/opencv/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
  16. # face=face_detector.detectMultiScale(gray,1.1,5,cv2.CASCADE_SCALE_IMAGE,(100,100),(300,300))
  17. face=face_detector.detectMultiScale(gray,1.1)
  18. for x,y,w,h in face:
  19. cv2.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
  20. cv2.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
  21. # 人脸识别
  22. ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
  23. print('标签id:',ids,'置信评分:', confidence)
  24. if confidence > 80:
  25. cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 0), 1)
  26. # cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
  27. else:
  28. # cv2.putText(img, str(names[ids - 1]), (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
  29. cv2.putText(img, 'unkonw', (x + 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
  30. cv2.namedWindow("result", cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
  31. cv2.resizeWindow("result", 400, 400)
  32. cv2.moveWindow("result", 500, 250) # 显示框位置,左上角为原点(0, 0)坐标,第一个是x坐标,第二个是y坐标
  33. cv2.imshow('result',img)
  34. #print('bug:',ids)
  35. cv2.waitKey(0)
  36. cv2.destroyAllWindows()
  37. def name():
  38. # path = './data/jm/'
  39. path = './opencv/data/images'
  40. names = []
  41. # 获取该目录下所有文件,存入列表中
  42. labelList = os.listdir(path)
  43. for label in labelList:
  44. names.append(label)
  45. print(names)
  46. return names
  47. names = name()
  48. path = './test'
  49. for img_name in os.listdir(path):
  50. img_path = path + '/' + img_name
  51. img = cv2.imread(img_path)
  52. face_detect_demo(img)
  53. # cap=cv2.VideoCapture('1.mp4')
  54. # while True:
  55. # flag,frame=cap.read()
  56. # if not flag:
  57. # break
  58. # face_detect_demo(frame)
  59. # if ord(' ') == cv2.waitKey(10):
  60. # break
  61. # cap.release()

 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>实验效果>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

本实验数据很少,做了个小demo,喜欢的话点个赞

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/116132
推荐阅读
相关标签