opencv(8)--摄像头探测人脸(haar)、人脸识别

级联分类器

Haar特征+Adaboost级联分类器

以 Haar特征分类器为基础的对象检测技术是一种非常有效的对象检测技术,多用于人脸检测、行人检测等。Haar-like特征是计算机视觉领域一种常用的特征描述算子,也称为Haar特征。Haar特征就是用算子中黑色矩形所有像素值的和减去白色矩形所有像素值的和。

def face_detect(image):
    detector=cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')#加载haar级联分类器
    rects=detector.detectMultiScale(image,scaleFactor=1.1,minNeighbors=3,minSize=(10,10),flags=cv2.CASCADE_SCALE_IMAGE)#scaleFactor=1.1 每次缩小图像比例,minNeighbors=3,当有三个矩形框同时存在时才认为匹配成功,minSize=(10,10),匹配最小尺寸,flags=cv2.CASCADE_SCALE_IMAGE,正常比例检测,cv2.CASCADE_FIND_BIGGEST_OBJECT(只检测就大物体),CASCADE_DO_CANNY_PRUNING(利用canny边缘检测来排除一些边缘很少或者很多的图像区域),CASCADE_DO_ROUGH_SEARCH(初略的检测) 
    for (x,y,w,h) in rects:
        cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
    return image
cap=cv2.VideoCapture(0)
while(True):
    ret,frame=cap.read()
    image=face_detect(frame)
    cv2.imshow('frame',image)
    if cv2.waitKey(10) & 0xff ==ord('q'):
        break
cap.release()
cv2.destroyAllWindows()

人脸识别

采集样本

import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
import imghdr #判断文件类型

def imread(image_path):
    image=cv2.imread(image_path)
    image=cv2.cvtColor(image,cv2.COLOR_BGR2RGB)
    return image
def show(image):
    plt.imshow(image)
    plt.axis('off')
    plt.show()

def predict_face(path,output):	#检测并截取人脸
    if not os.path.exists(output):	#创建文件夹
        os.makedirs(output)
    for files in os.listdir(path):	#遍历文件夹
        if os.path.isdir(os.path.join(path,files)):  #如果是文件仍是文件夹
            output2=os.path.join(output,files)		#创建二级文件夹
            if not os.path.exists(output2):        
                os.makedirs(output2)
            files=os.path.join(path,files)   		#图片上级路径
            for file in os.listdir(files):			#遍历图片
                file=os.path.join(files,file)      	#图片完整路径
                facedetect(file,output2)
                
def facedetect(image_path,output):      
    name=os.path.basename(image_path)		#获取图片名
    image=cv2.imread(image_path)			
    image=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    detector=cv2.CascadeClassifier("haarcascade_frontalface_alt.xml")	
    rects=detector.detectMultiScale(image,minSize=(10,10),flags=cv2.CASCADE_SCALE_IMAGE)
    for (x,y,w,h) in rects:
        f=cv2.resize(image[y:y+h,x:x+w],(200,200))
        cv2.imwrite(os.path.join(output,name),f)
            
predict_face('faces','predict_faces')	#得到样本截取完人脸的文件夹

生成label

def get_label(path):		
    label=0
    fh=open('label.txt','w')
    for (root,dirs,files) in os.walk(path):	#遍历整个文件夹
        for subdir in dirs:			
            if os.path.isdir(os.path.join(root,subdir)):
                subdir_path=os.path.join(root,subdir)	
                for file in os.listdir(subdir_path):		#遍历子文件夹
                    file_path=os.path.join(subdir_path,file)
                    imgtype=imghdr.what(file_path)			#判断文件格式
                    if imgtype=='jpeg'or imgtype=='png':
                        fh.write(file_path)
                        fh.write(';')			#以;为分隔符
                        fh.write(str(label))	
                        fh.write('\n')
                label+=1
    fh.close()

训练模型

image=[]			#保存图片
label=[]			#保存标签
fh =open('label.txt')
for line in fh:
    arr=line.split(';')
    img=cv2.imread(arr[0],0)   #保存单通道的图片数据
    image.append(img)			
    label.append(int(arr[1]))
model = cv2.face.EigenFaceRecognizer_create()	#三个内置人脸检测模型
# model = cv2.face.FisherFaceRecognizer_create()
# model = cv2.face.LBPHFaceRecognizer_create()
model.train(np.array(image),np.array(label))
model.save("predict_face.xml")		

测试模型

name=['a','b']
model=cv2.face.EigenFaceRecognizer_create()	#人脸检测模型
model.read('predict_face.xml')	
for file in os.listdir('test'):				
    file=os.path.join('test',file)
    imgtype=imghdr.what(file)
    if imgtype=='jpeg'or imgtype=='png':
        image = imread(file)
        gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)
        detector=cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
        rects=detector.detectMultiScale(gray,scaleFactor=1.1, minNeighbors=3, minSize=(20, 20), flags=cv2.CASCADE_SCALE_IMAGE)
        for (x,y,w,h) in rects:
            cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
            face = cv2.resize(gray[y:y+h,x:x+w], (200,200)) #截取人脸部分
            params = model.predict(face)					#进行预测,返回标签及直信度
            cv2.putText(image,name[params[0]],(x,y-20),cv2.FONT_HERSHEY_SIMPLEX,1,(255,0,0),2)
        show(image)																
            
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值