SVM算法应用综合练习

一.基于LibSVM得到决策函数

1.下载Libsvm

地址:https://www.csie.ntu.edu.tw/~cjlin/libsvm/.

2.解压后导入

1.下载好的zip文件解压得到下方的文件
在这里插入图片描述
2.在idea中新建java文件,引入解压后得到得Java文件内容
在这里插入图片描述
在这里插入图片描述

3.准备需要实验的数据

1.打开libsvm文件下的windows文件里面的svm-toy程序
在这里插入图片描述
2.点击run
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

4.进行训练

1.新建Main的class的类用于训练
在这里插入图片描述
2.输入以下代码:

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {
        // write your code here

        //存放数据以及保存模型文件路径
        String filepath = "D:\\32\\";
        /**
         * -s 设置svm类型:默认值为0
         *          0– C-SVC
         *          1 – v-SVC
         *          2 – one-class-SVM
         *          3 –ε-SVR
         *          4 – n - SVR
         *
         * -t 设置核函数类型,默认值为2
         *          0 --线性核
         *          1 --多项式核
         *          2 -- RBF核
         *          3 -- sigmoid核
         *
         * -d degree:设置多项式核中degree的值,默认为3
         *
         * -c cost:设置C-SVC、ε-SVR、n - SVR中从惩罚系数C,默认值为1;
         */
        String[] arg = {"-s","0","-c","10","-t","0",filepath+"data.txt",filepath+"line.txt"};
        System.out.println("----------------线性-----------------");
        //训练函数
        svm_train.main(arg);

        arg[5]="1";
        arg[7]=filepath+"poly.txt";//输出文件路径
        System.out.println("---------------多项式-----------------");
        svm_train.main(arg);

        arg[5]="2";
        arg[7]=filepath+"RBF.txt";
        System.out.println("---------------高斯核-----------------");
        svm_train.main(arg);
    }
}

3.点击运行,得到结果
在这里插入图片描述

5.输出文件

data.txt训练数据
line.txt线性模型
poly多项式模型
RBF高斯核模型
在这里插入图片描述

1.线性模型

在这里插入图片描述

2.多项式模型

在这里插入图片描述

3.高斯核模型

在这里插入图片描述

6.决策函数

根据公式f(x)=wT*x+b以及模型数据可以求得最终的决策函数。wT为向量的转置矩阵,即为模型数据中的SV
b为偏置常数,即为数据模型中的rho.

二.人脸识别数据集的建立

1.人脸数据采集

import numpy as np
import cv2
import dlib
import os
import sys
import random
# 存储位置
output_dir = 'C:/Users/DELL/face'
size = 64
 
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
# 改变图片的亮度与对比度
 
def relight(img, light=1, bias=0):
    w = img.shape[1]
    h = img.shape[0]
    #image = []
    for i in range(0,w):
        for j in range(0,h):
            for c in range(3):
                tmp = int(img[j,i,c]*light + bias)
                if tmp > 255:
                    tmp = 255
                elif tmp < 0:
                    tmp = 0
                img[j,i,c] = tmp
    return img
 
#使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()
# 打开摄像头 参数为输入流,可以为摄像头或视频文件
camera = cv2.VideoCapture(0)
#camera = cv2.VideoCapture('C:/Users/CUNGU/Videos/Captures/wang.mp4')
ok = True

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('D:/27/shape_predictor_68_face_landmarks.dat')

index=1

while ok:
    if (index <= 20):#存储20张人脸特征图像
        print('Being processed picture %s' % index)
        # 从摄像头读取照片
        success, img = camera.read()
        # 转为灰度图片
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 使用detector进行人脸检测
        dets = detector(gray_img, 1)
 
        for i, d in enumerate(dets):
            x1 = d.top() if d.top() > 0 else 0
            y1 = d.bottom() if d.bottom() > 0 else 0
            x2 = d.left() if d.left() > 0 else 0
            y2 = d.right() if d.right() > 0 else 0
 
            face = img[x1:y1,x2:y2]
            
 
            face = cv2.resize(face, (size,size))
 
            cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)

    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    rects = detector(img_gray, 0)
    
    for i in range(len(rects)):
        landmarks = np.matrix([[p.x, p.y] for p in predictor(img,rects[i]).parts()])
        for idx, point in enumerate(landmarks):
            # 68点的坐标
            pos = point[0, 0], point[0, 1]
            print(idx,pos)
            
            if (index <= 20):
                file = open('D:/27/'+str(index)+'.txt', 'a')
                s=str(pos)
                s = s.replace("(", "")
                s = s.replace(")", "")
                s = s.replace(",","")
                file.write(s+'\n')
                
            
            # 利用cv2.circle给每个特征点画一个圈,共68个
            cv2.circle(img, pos, 2, color=(0, 255, 0))
            # 利用cv2.putText输出1-68
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(img, str(idx+1), pos, font, 0.2, (0, 0, 255), 1,cv2.LINE_AA)
    cv2.imshow('video', img)
    
    index += 1
    
    if index == 20:   
        break
    
camera.release()
cv2.destroyAllWindows()

在这里插入图片描述
在这里插入图片描述

2.数据集的建立

# 从人脸图像文件中提取人脸特征存入 CSV
# Features extraction from images and save into features_all.csv

# return_128d_features()          获取某张图像的128D特征
# compute_the_mean()              计算128D特征均值

from cv2 import cv2 as cv2
import os
import dlib
from skimage import io
import csv
import numpy as np

# 要读取人脸图像文件的路径
path_images_from_camera ="D:/28/"

# Dlib 正向人脸检测器
detector = dlib.get_frontal_face_detector()

# Dlib 人脸预测器
predictor = dlib.shape_predictor("D:/27/shape_predictor_68_face_landmarks.dat")

# Dlib 人脸识别模型
# Face recognition model, the object maps human faces into 128D vectors
face_rec = dlib.face_recognition_model_v1("D:/27/dlib_face_recognition_resnet_model_v1.dat")


# 返回单张图像的 128D 特征
def return_128d_features(path_img):
    img_rd = io.imread(path_img)
    img_gray = cv2.cvtColor(img_rd, cv2.COLOR_BGR2RGB)
    faces = detector(img_gray, 1)

    print("%-40s %-20s" % ("检测到人脸的图像 / image with faces detected:", path_img), '\n')

    # 因为有可能截下来的人脸再去检测,检测不出来人脸了
    # 所以要确保是 检测到人脸的人脸图像 拿去算特征
    if len(faces) != 0:
        shape = predictor(img_gray, faces[0])
        face_descriptor = face_rec.compute_face_descriptor(img_gray, shape)
    else:
        face_descriptor = 0
        print("no face")

    return face_descriptor


# 将文件夹中照片特征提取出来, 写入 CSV
def return_features_mean_personX(path_faces_personX):
    features_list_personX = []
    photos_list = os.listdir(path_faces_personX)
    if photos_list:
        for i in range(len(photos_list)):
            # 调用return_128d_features()得到128d特征
            print("%-40s %-20s" % ("正在读的人脸图像 / image to read:", path_faces_personX + "/" + photos_list[i]))
            features_128d = return_128d_features(path_faces_personX + "/" + photos_list[i])
            #  print(features_128d)
            # 遇到没有检测出人脸的图片跳过
            if features_128d == 0:
                i += 1
            else:
                features_list_personX.append(features_128d)
                i1=str(i+1)
                add="D:/29/face_feature"+i1+".csv"
                print(add)
                with open(add, "w", newline="") as csvfile:
                    writer1 = csv.writer(csvfile)
                    writer1.writerow(features_128d)
    else:
        print("文件夹内图像文件为空 / Warning: No images in " + path_faces_personX + '/', '\n')

    # 计算 128D 特征的均值
    # N x 128D -> 1 x 128D
    if features_list_personX:
        features_mean_personX = np.array(features_list_personX).mean(axis=0)
    else:
        features_mean_personX = '0'

    return features_mean_personX


# 读取某人所有的人脸图像的数据
people = os.listdir(path_images_from_camera)
people.sort()

with open("D:/29/features2_all.csv", "w", newline="") as csvfile:
    writer = csv.writer(csvfile)
    for person in people:
        print("##### " + person + " #####")
        # Get the mean/average features of face/personX, it will be a list with a length of 128D
        features_mean_personX = return_features_mean_personX(path_images_from_camera + person)
        writer.writerow(features_mean_personX)
        print("特征均值 / The mean of features:", list(features_mean_personX))
        print('\n')
    print("所有录入人脸数据存入 / Save all the features of faces registered into: D:/29/features_all2.csv")

在这里插入图片描述
在这里插入图片描述

三.总结

通过本次实验,我学习到了如何使用libSVM处理决策函数以及采集到本人脸信息的基本过程,并将把采集到的人脸信息后续运用到人脸识别中去。

四.参考文献

https://blog.csdn.net/qq_47281915/article/details/121307709?spm=1001.2014.3001.5501.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值