1、安装libsvm
在虚拟环境中pip install -U libsvm-official
测试代码:
from libsvm.svmutil import *
from libsvm.svm import *
y, x = [1, -1], [{
1: 1, 2: 2}, {
1: 1, 2: 0}]
prob = svm_problem(y, x)
param = svm_parameter('-t 0 -c 4 -b 1')
model = svm_train(prob, param)
yt = [1]
xt = [{
1: 2, 2: 3}]
p_label, p_acc, p_val = svm_predict(yt, xt, model)
print(p_label)
结果图:
2、代码
参考:python使用libsvm
python 使用 libsvm
from libsvm.svmutil import *
import joblib
from skimage.feature import local_binary_pattern
import cv2
from skimage.feature import hog
import numpy as np
def get_image_list(dirname,size): #加载图片
img_list = []
for i in range(size):
path = dirname+ str(i) +'.png' #图片存放路径
img = cv2.imread(path) #调用opencv的imread函数读取图片,得到一个通道为三的数组
img_list.append(img)
path = dirname
return img_list
def write(label,save_path,feature): #保存特征 ###大概是这样的。自己摸索的,不知道对不对,反正能训练
###例:标签(1)+空格(‘ ’)+ 序号(从1开始str(j + 1))+冒号(‘:’)+特征值+空格(‘ ’)换行('\n')
###例如1 1:31.077399380804952 2:71.24458204334366 3:214.22600619195046 4:5.040721180244506 5:9.946245307810633 6:27.205359467206083 7:5.467070774735018 8:11.444525326546477 9:29.464294388212977
### 1 1:0.04953560371517028 2:0.05263157894736842 3:0.02476780185758514 4:0.018575851393188854 5:0.0 6:0.030959752321981424 7:0.021671826625386997 8:0.03715170278637771 9:0.058823529411764705 10:0.05263157894736842 11:0.09907120743034056 12:0.0804953560371517 13:0.06191950464396285 14:0.04953560371517028 15:0.018575851393188854 16:0.021671826625386997 17:0.009287925696594427 18:0.01238390092879257 19:0.009287925696594427 20:0.0030959752321981426 21:0.0 22:0.01238390092879257 23:0.0030959752321981426 24:0.006191950464396285 25:0.01238390092879257 26:0.25386996904024767
###一张图片的标签在最前方。之后是特征值,每张图片的特征值在一行,下一张图片需要换行。例如纹理特征,有9个值,序号就从1-9。hog有12480个值,序号就从1-12480.
with open(save_path,