svm图像分类python代码实现续
这篇博客诗接上前面一篇svm图像分类得一篇续集
svm分类代码如下
#os.system("pause")
#Svm 训练:
import sys
import os
import cv2
import numpy as np
from sklearn.svm import SVC
from sklearn.model_selection import train_test_split
import time
import pickle
#help(SVC)
SHAPE = (30, 30)
def getImageData(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(extractFeaturesFromImage(root + d + "/" + image))
return np.asarray(feature_list), np.asarray(label_list)
def extractFeaturesFromImage(image_file):
img = cv2.imread(image_file)
img = cv2.resize(img, SHAPE, interpolation = cv2.INTER_CUBIC)
img = img.flatten()
img = img / np.mean(img)
return img
if __name__ == "__main__":
directory ="C:/learn_data/2021_car/image/"
feature_array, label_array = getImageData(directory)
X_train, X_test, y_train, y_test = train_test_split(feature_array, label_array, test_size = 0.2, random_state = 42)
if os.path.isfile("svm_model.pkl"):
svm = pickle.load(open("svm_model.pkl", "rb"))
else:
svm = SVC(kernel='rbf',gamma=0.001)
svm.fit(X_train, y_train)
pickle.dump(svm, open("C:/learn_data/2021_car/svm_model.pkl", "wb"))
print("Testing...\n")
right = 0
total = 0
for x, y in zip(X_test, y_test):
x = x.reshape(1, -1)
prediction = svm.predict(x)[0]
if y == prediction:
right += 1
total += 1
accuracy = float(right) / float(total)
print (str(accuracy) + "% accuracy")
print ("Manual Testing\n")
print("success")
os.system("pause")
标题
那么数据集是什么样的呢
这里我要说一下了,这一次做的三分类,数据集的文件结构如下:
也就是说,这里的image就是我们的训练集,里面分为三个子文件夹,这三个子文件夹里只能有图片,其他的任何文件都不能有
好的,那么对于文件没是没有要求的,那么如果你现在想要进行二分类,三分类,也就改变image下的子文件数量,这里应该能听懂
如果调用模型,在上一篇博客有着介绍可以参考。
博客链接在这里
这次的数据集已上传到我的资源,是三类车牌号数据。
版权声明:本文为weixin_43327597原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。