人脸识别在现在高科技的社会中,随处可见,作为一个初学者小白,根据老师上课的内容,完善了一个小型的人脸识别案例
import cv2
import os
import numpy as np
CASE_PATH="C:\\Users\Administrator\Anaconda3\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml"
RAM_IMAGE_DIR ='./me/'
DATASET_DIR='./images/' #数据集
face_cascade=cv2.CascadeClassifier(CASE_PATH)
def save_faces(img,name,x,y,width,height):
image=img[y:y+height,x:x+width]
if img.size == 0:#对于这种情况就不要用imwriter
cv2.imwrite(name,image)
image_list=os.listdir(RAM_IMAGE_DIR)#列出文件夹下面所有的文件
count=166
for image_path in image_list:
fullpath=RAM_IMAGE_DIR+image_path
image=cv2.imread(fullpath)
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
faces=face_cascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(5,5))
for(x,y,width,height)in faces:
save_faces(image,DATASET_DIR+image_path,x,y-30,width,height+30)
count+=1
前面的都是通用代码
对读取的图片进行处理
#为了方便后期卷积数据的输入,对切割出来的图片尺寸进行调整
def resize_without_deformation(image,size=(100,100)):
height,width,_=image.shape
longest_edge=max(height,width)
top,bottom,left,right=0,0,0,0
if height<longest_edge:
height_diff=longest_edge-height
top=int(height_diff/2)
bottom=height_diff-top
elif width<longest_edge:
width_diff=longest_e