赞
踩
1、简介:梯度直方图特征(HOG) 是一种对图像局部重叠区域的密集型描述符, 它通过计算局部区域的梯度方向直方图来构成特征。Hog特征结合SVM分类器已经被广泛应用于图像识别中,尤其在行人检测中获得了极大的成功。需要提醒的是,HOG+SVM进行行人检测的方法是法国研究人员Dalal在2005的CVPR上提出的,而如今虽然有很多行人检测算法不断提出,但基本都是以HOG+SVM的思路为主。
2、识别微笑表情的原理图
3、特征提取原理: HOG特征是一种局部区域描述符,它通过计算局部区域上的梯度方向直方图来构成人体特征,能够很好地描述人体的边缘,它对光照变化和小量的偏移不敏感。
图像中像素点(x,y)的梯度为
1、首先导入需要用到的包
# 导入包
import numpy as np
import cv2
import dlib
import random#构建随机测试集和训练集
from sklearn.svm import SVC #导入svm
from sklearn.svm import LinearSVC #导入线性svm
from sklearn.pipeline import Pipeline #导入python里的管道
import os
import joblib#保存模型
from sklearn.preprocessing import StandardScaler,PolynomialFeatures #导入多项式回归和标准化
import tqdm
2、获取图片路径
folder_path='E:/嵌入式、通信、人工智能/genki4k/'
label='labels.txt'#标签文件
pic_folder='files/'#图片文件路径
3、获得默认的人脸检测其和训练好的人脸68特征点检测器
#获得默认的人脸检测器和训练好的人脸68特征点检测器 def get_detector_and_predicyor(): #使用dlib自带的frontal_face_detector作为我们的特征提取器 detector = dlib.get_frontal_face_detector() """ 功能:人脸检测画框 参数:PythonFunction和in Classes in classes表示采样次数,次数越多获取的人脸的次数越多,但更容易框错 返回值是矩形的坐标,每个矩形为一个人脸(默认的人脸检测器) """ #返回训练好的人脸68特征点检测器 predictor = dlib.shape_predictor('E:/qq/shape_predictor_68_face_landmarks.dat') return detector,predictor #获取检测器 detector,predictor=get_detector_and_predicyor()
4、截取面部的函数
def cut_face(img,detector,predictor): #截取面部 img_gry=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) rects = detector(img_gry, 0) if len(rects)!=0: mouth_x=0 mouth_y=0 landmarks = np.matrix([[p.x, p.y] for p in predictor(img,rects[0]).parts()]) for i in range(47,67):#嘴巴范围 mouth_x+=landmarks[i][0,0] mouth_y+=landmarks[i][0,1] mouth_x=int(mouth_x/20) mouth_y=int(mouth_y/20) #裁剪图片 img_cut=img_gry[mouth_y-20:mouth_y+20,mouth_x-20:mouth_x+20] return img_cut else: return 0#检测不到人脸返回0
5、提取特征值的函数
#提取特征值 def get_feature(files_train,face,face_feature): for i in tqdm.tqdm(range(len(files_train))): img=cv2.imread(folder_path+pic_folder+files_train[i]) cut_img=cut_face(img,detector,predictor) if type(cut_img)!=int: face.append(True) cut_img=cv2.resize(cut_img,(64,64)) #padding:边界处理的padding padding=(8,8) winstride=(16,16) hogdescrip=hog.compute(cut_img,winstride,padding).reshape((-1,)) face_feature.append(hogdescrip) else: face.append(False)#没有检测到脸的 face_feature.append(0)
6、筛选函数
def filtrate_face(face,face_feature,face_site): #去掉检测不到脸的图片的特征并返回特征数组和相应标签 face_features=[] #获取标签 label_flag=[] with open(folder_path+label,'r') as f: lines=f.read().splitlines() #筛选出能检测到脸的,并收集对应的label for i in tqdm.tqdm(range(len(face_site))): if face[i]:#判断是否检测到脸 #pop之后要删掉当前元素,后面的元素也要跟着前移,所以每次提取第一位就行了 face_features.append(face_feature.pop(0)) label_flag.append(int(lines[face_site[i]][0])) else: face_feature.pop(0) datax=np.float64(face_features) datay=np.array(label_flag) return datax,datay
7、多项式核svm和高斯核svm
def PolynomialSVC(degree,c=10):#多项式svm
return Pipeline([
# 将源数据 映射到 3阶多项式
("poly_features", PolynomialFeatures(degree=degree)),
# 标准化
("scaler", StandardScaler()),
# SVC线性分类器
("svm_clf", LinearSVC(C=10, loss="hinge", random_state=42,max_iter=10000))
])
#svm高斯核
def RBFKernelSVC(gamma=1.0):
return Pipeline([
('std_scaler',StandardScaler()),
('svc',SVC(kernel='rbf',gamma=gamma))
])
8、训练函数
def train(files_train,train_site):#训练 ''' files_train:训练文件名的集合 train_site :训练文件在文件夹里的位置 ''' #是否检测到人脸 train_face=[] #人脸的特征数组 train_feature=[] #提取训练集的特征数组 get_feature(files_train,train_face,train_feature) #筛选掉检测不到脸的特征数组 train_x,train_y=filtrate_face(train_face,train_feature,train_site) svc=PolynomialSVC(degree=1) svc.fit(train_x,train_y) return svc#返回训练好的模型
9、测试函数
def test(files_test,test_site,svc):#预测,查看结果集 ''' files_train:训练文件名的集合 train_site :训练文件在文件夹里的位置 ''' #是否检测到人脸 test_face=[] #人脸的特征数组 test_feature=[] #提取训练集的特征数组 get_feature(files_test,test_face,test_feature) #筛选掉检测不到脸的特征数组 test_x,test_y=filtrate_face(test_face,test_feature,test_site) pre_y=svc.predict(test_x) ac_rate=0 for i in range(len(pre_y)): if(pre_y[i]==test_y[i]): ac_rate+=1 ac=ac_rate/len(pre_y)*100 print("准确率为"+str(ac)+"%") return ac
10、HOG特征提取器
#设置hog的参数
winsize=(64,64)
blocksize=(32,32)
blockstride=(16,16)
cellsize=(8,8)
nbin=9
#定义hog
hog=cv2.HOGDescriptor(winsize,blocksize,blockstride,cellsize,nbin)
#获取文件夹里有哪些文件
files=os.listdir(folder_path+pic_folder)
11、数据集中随机的9/10做为训练集,剩下的1/10做为测试集,进行十次
ac=float(0) for j in range(10): site=[i for i in range(4000)] #训练所用的样本所在的位置 train_site=random.sample(site,3600) #预测所用样本所在的位置 test_site=[] for i in range(len(site)): if site[i] not in train_site: test_site.append(site[i]) files_train=[] #训练集,占总数的十分之九 for i in range(len(train_site)): files_train.append(files[train_site[i]]) #测试集 files_test=[] for i in range(len(test_site)): files_test.append(files[test_site[i]]) svc=train(files_train,train_site) ac=ac+test(files_test,test_site,svc) save_path='F:/picture/train/second'+str(j)+'(hog).pkl' joblib.dump(svc,save_path) ac=ac/10 print("平均准确率为"+str(ac)+"%")
1、检测结果
2、写入检测函数
在这里插入代码片def test1(files_test,test_site,svc):#预测,查看结果集 ''' files_train:训练文件名的集合 train_site :训练文件在文件夹里的位置 ''' #是否检测到人脸 test_face=[] #人脸的特征数组 test_feature=[] #提取训练集的特征数组 get_feature(files_test,test_face,test_feature) #筛选掉检测不到脸的特征数组 test_x,test_y=filtrate_face(test_face,test_feature,test_site) pre_y=svc.predict(test_x) tp=0 tn=0 for i in range(len(pre_y)): if pre_y[i]==test_y[i] and pre_y[i]==1: tp+=1 elif pre_y[i]==test_y[i] and pre_y[i]==0: tn+=1 f1=2*tp/(tp+len(pre_y)-tn) print(f1)
3、加载刚刚保存本地模型然后调用检测函数查看结果
svc7=joblib.load('F:/picture/train/second9(hog).pkl') site=[i for i in range(4000)] #训练所用的样本所在的位置 train_site=random.sample(site,3600) #预测所用样本所在的位置 test_site=[] for i in range(len(site)): if site[i] not in train_site: test_site.append(site[i]) #测试集 files_test=[] for i in range(len(test_site)): files_test.append(files[test_site[i]]) test1(files_test,test_site,svc7)
测试结果
4、写入笑脸检测函数并进行图片检测
def smile_detector(img,svc): cut_img=cut_face(img,detector,predictor) a=[] if type(cut_img)!=int: cut_img=cv2.resize(cut_img,(64,64)) #padding:边界处理的padding padding=(8,8) winstride=(16,16) hogdescrip=hog.compute(cut_img,winstride,padding).reshape((-1,)) a.append(hogdescrip) result=svc.predict(a) a=np.array(a) return result[0] else : return 2 ##图片检测 pic_path='F:/picture/second/facesmile/mytest/xz3.jpg' img=cv2.imread(pic_path) result=smile_detector(img,svc7) if result==1: img=cv2.putText(img,'smile',(21,50),cv2.FONT_HERSHEY_COMPLEX,2.0,(0,255,0),1) elif result==0: img=cv2.putText(img,'no smile',(21,50),cv2.FONT_HERSHEY_COMPLEX,2.0,(0,255,0),1) else: img=cv2.putText(img,'no face',(21,50),cv2.FONT_HERSHEY_COMPLEX,2.0,(0,255,0),1) cv2.imshow('video', img) cv2.waitKey(0)
检测结果
5、调用摄像头实时检测并保持,按s键保存刚刚的识别的图片,按esc退出
camera = cv2.VideoCapture(0)#打开摄像头 ok=True flag=0 # 打开摄像头 参数为输入流,可以为摄像头或视频文件 while ok: ok,img = camera.read() # 转换成灰度图像 result=smile_detector(img,svc7) if result==1: img=cv2.putText(img,'smile',(21,50),cv2.FONT_HERSHEY_COMPLEX,2.0,(0,255,0),1) elif result==0: img=cv2.putText(img,'no smile',(21,50),cv2.FONT_HERSHEY_COMPLEX,2.0,(0,255,0),1) else: img=cv2.putText(img,'no face',(21,50),cv2.FONT_HERSHEY_COMPLEX,2.0,(0,255,0),1) cv2.imshow('video', img) k = cv2.waitKey(1) if k == X: # press 'ESC' to quit break elif k==115: pic_save_path='F:/picture/second/result/'+str(flag)+'.jpg' flag+=1 cv2.imwrite(pic_save_path,img) camera.release() cv2.destroyAllWindows()
通过人脸微笑的检测,进一步的加深对HOG算法的学习,了解该算法的优点,同时又对人脸68特征点的采集知识进行了复习。
参考:
https://blog.csdn.net/carson2005/article/details/7782726
https://blog.csdn.net/weixin_56102526/article/details/121926814?spm=1001.2014.3001.5501
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。