python使⽤SVM进⾏简单的图像分类1.⾸先进⾏数据处理
import numpy as np
from matplotlib import pyplot as plt
from sklearn import svm
from sklearn.datasets  import load_digits
del_selection  import train_test_split
ics import accuracy_score
import cv2
import os
import pickle
from PIL import Image
SHAPE=(30,30)
1.1⽂件的结构如下
图⽚不⽤太多,⼀类⼏张即可
替换成⾃⼰的图⽚以及⽬录即可
def getImageData(self,directory):
s =1
feature_list =list()
label_list =list()
num_classes =0
for root, dirs, files in os.walk(directory):
for d in dirs:
num_classes +=1
images = os.listdir(root + d)
for image in images:
s +=1
label_list.append(d)
feature_list.append(actFeaturesFromImage(root + d +"/"+ image)) return np.asarray(feature_list), np.asarray(label_list)
1.2接下来图⽚的预处理函数(上⽅有调⽤到)
def extractFeaturesFromImage(self,image_file):
import pickleimg = cv2.imread(image_file)
img = size(img, self.SHAPE, interpolation=cv2.INTER_CUBIC)
img = img.flatten()
img = img / np.mean(img)
return img
2.svm模型训练
def train(self,dir):
#数据获取,这⾥Svm_derection是⾃定义类的名称
feature_array, label_array = ImageData(self.directory)
#数据的分割
X_train, X_test, y_train, y_test =train_test_split(feature_array, label_array, test_size=0.2, random_state=42)
print("shape of raw image data: {0}".format(feature_array.shape))
print("shape of raw image data: {0}".format(X_train.shape))
print("shape of raw image data: {0}".format(X_test.shape))
#模型的选择
clf = svm.SVC(gamma=0.001,C=100., probability=True)
#模型的训练
clf.fit(X_train, y_train);
#模型测试
Ypred = clf.predict(X_test);
print("pre",Ypred)
print("test",y_test)
#模型保存
pickle.dump(clf,open("digits_svm.pkl","wb"))
3.模型读取使⽤
def test(self,path,img_file):
pkl_file =open(path,'rb')
clf=pickle.load(pkl_file)
Ypred = clf.actFeaturesFromImage(img_file),(1,2700)))
return Ypred
4.运⾏代码
path='digits_svm.pkl'
img_file='derection/f2/1.jpg'
sd=Svm_derection()
st(path,img_file)
print(t)
img = Image.open(os.path.join('derection/f1/1.jpg'))
plt.figure("Image") # 图像窗⼝名称
plt.imshow(img)
plt.axis('off') # 关掉坐标轴为 off
plt.title(t) # 图像题⽬
plt.show()
5.结果展⽰

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。