SVM算法人脸微笑识别

这篇博客详细介绍了如何运用支持向量机(SVM)进行人脸识别,特别是微笑的识别。首先,它涵盖了从导入必要的Python库,获取人脸特征点,定义截取面部的函数,到提取HOG特征和构建SVM模型的全过程。通过10折交叉验证训练和测试模型,最终实现了笑脸检测功能。文中还引用了相关参考文献以供深入研究。
摘要由CSDN通过智能技术生成

一、代码部分

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:/phone/PH/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:\\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,(
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值