图片分类-pca_svc

PCA_SVC训练

import os
from PIL import Image
import numpy as np
from sklearn.decomposition import PCA
from sklearn.svm import SVC
import time
import datetime
def load_Img(imgDir):
lable = os.listdir(imgDir)
#print(lable)
OK_name=os.listdir(imgDir+'/'+lable[0])
NG_name=os.listdir(imgDir+'/'+lable[1])
#print(NG_name)

label=[]
data=[]

for i in range(len(OK_name)):
start = datetime.datetime.now()

OK_path = imgDir + "/" + lable[0]+'/'+OK_name[i-1]
OK_img = Image.open(OK_path)

OK_img=OK_img.convert('L')
# print(OK_img.size)
end = datetime.datetime.now()
print(end - start)

OK_img = OK_img.resize((64,64))

OK_arr = np.asarray(OK_img, dtype="float32")

OK_arr = OK_arr.flatten()

data.append(OK_arr)



label.append(lable[0])
# label.append(1)

for j in range(len(NG_name)):

NG_path = imgDir + '/' + lable[1] + '/' + NG_name[j - 1]
NG_img = Image.open(NG_path)
NG_img=NG_img.convert('L')
# print(NG_img.size)
NG_img = NG_img.resize((64,64))

NG_arr = np.asarray(NG_img, dtype="float32")

NG_arr = NG_arr.flatten()

data.append(NG_arr)

# label.append(0)
label.append(lable[1])
return label ,data
craterDir = "E:\image\Result"

label,data = load_Img(craterDir)
#print(label)
#print(data)


#将数据分割训练数据与测试数据
from sklearn.model_selection import train_test_split
# 随机采样20%的数据构建测试样本,其余作为训练样本
X_train, X_test, y_train, y_test = train_test_split(data,label , random_state=33, test_size=0.2)

# 一个参数点(PCA维数为n)的模型训练和测试,得到该参数下模型在校验集上的预测性能
def n_component_analysis(n,C,gamma, X_train, y_train, X_val, y_val):
#start = time.time()
start = datetime.datetime.now()
pca = PCA(n_components=n)
print("PCA begin with n_components: {}".format(n));
pca.fit(X_train)

# 在训练集和测试集降维
X_train_pca = pca.transform(X_train)
X_val_pca = pca.transform(X_val)

# 利用SVC训练
print('SVC begin')
clf1 = SVC(C=C,gamma=gamma)
# clf1 = SVC(C=C,kernel='rbf',gamma=gamma)
clf1.fit(X_train_pca, y_train)

# 返回accuracy
accuracy = clf1.score(X_val_pca, y_val)
end = datetime.datetime.now()
# end = time.time()
print("accuracy: {},C:{},gamma:{} time elaps:{}".format(accuracy,C,gamma ,end - start))
return accuracy

# 设置超参数(PCA维数)搜索范围
n_s = np.linspace(0.70, 0.85, num=3)
#需要调优的参数
C_s = np.logspace(4,6, 3)# logspace(a,b,N)把10的a次方到10的b次方区间分成N份
gamma_s = np.logspace(-8, -6, 3)

accuracy = []

if __name__=='__main__':
for n in n_s:
for i, oneC in enumerate(C_s):
for j, gamma in enumerate(gamma_s):
tmp = n_component_analysis(n, oneC, gamma,X_train, y_train, X_test, y_test)
accuracy.append(tmp)

保存模型

# coding=utf-8
import os
import sys
from PIL import Image
import numpy as np
from sklearn.svm import SVC
import pickle
from sklearn.decomposition import PCA
#将数据分割训练数据与测试数据
from sklearn.model_selection import train_test_split
# 随机采样20%的数据构建测试样本,其余作为训练样本
def Gain_Img(imgDir):
lable = os.listdir(imgDir)
OK_name=os.listdir(imgDir+'/'+lable[0])
NG_name=os.listdir(imgDir+'/'+lable[1])
print(lable)
for i in range(len(OK_name)):


OK_path = imgDir + "/" + lable[0]+'/'+OK_name[i-1]
OK_img = Image.open(OK_path)
OK_img=OK_img.convert('L')
OK_img = OK_img.resize((256,256))
out1 = OK_img.rotate(90) # 逆时针旋转45度
if not os.path.exists('rotation/{}'.format(lable[0])):
os.makedirs('rotation/{}'.format(lable[0]))
if not os.path.exists('rotation/{}'.format(lable[1])):
os.makedirs('rotation/{}'.format(lable[1]))
out1.save("rotation\\{}\\{}_90_{}.bmp".format(lable[0],lable[0],i))
OK_img.save("rotation\\{}\\{}_{}.bmp".format(lable[0],lable[0],i))

for j in range(len(NG_name)):

NG_path = imgDir + '/' + lable[1] + '/' + NG_name[j - 1]
NG_img = Image.open(NG_path)
NG_img = NG_img.convert('L')
NG_img = NG_img.resize((256,256))
out2 = NG_img.rotate(90) # 逆时针旋转45度
out2.save("rotation\\{}\\{}_90_{}.bmp".format(lable[1],lable[1],j))
NG_img.save("rotation\\{}\\{}_{}.bmp".format(lable[1],lable[1],j))



def load_Img(imgDir):
lable = os.listdir(imgDir)

OK_name=os.listdir(imgDir+'/'+lable[0])
NG_name=os.listdir(imgDir+'/'+lable[1])

label=[]
data=[]

for i in range(len(OK_name)):

OK_path = imgDir + "/" + lable[0]+'/'+OK_name[i-1]
OK_img = Image.open(OK_path)
# OK_img = OK_img.convert('L')
# OK_img = OK_img.resize((64, 64))

OK_arr = np.asarray(OK_img, dtype="float32")

OK_arr = OK_arr.flatten()

data.append(OK_arr)

label.append(lable[0])

for j in range(len(NG_name)):

NG_path = imgDir + '/' + lable[1] + '/' + NG_name[j - 1]
NG_img = Image.open(NG_path)
# NG_img = NG_img.convert('L')
# NG_img = NG_img.resize((64, 64))

NG_arr = np.asarray(NG_img, dtype="float32")

NG_arr = NG_arr.flatten()

data.append(NG_arr)


label.append(lable[1])
return label ,data

def main(path,job_name):
try:
label, data = load_Img(path)
X_train, X_test, y_train, y_test = train_test_split(data,label , random_state=33, test_size=0.2)
pca = PCA(n_components=0.7)

pca.fit(X_train)

# 在训练集和测试集降维
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)

SVC4=SVC(C=10000,gamma=1e-06)
SVC4 = SVC4.fit(X_train_pca, y_train)
accuracy = SVC4.score(X_test_pca, y_test)
#保存模型
name=""+job_name+".pkl"

pickle.dump((pca,SVC4),open(name, 'wb'))
return str(accuracy)

except Exception as err:

return str(err)


if __name__ == '__main__':
# print(main("E:\image\SVM"))
arg1=""+sys.argv[1]
arg2=""+sys.argv[2]

gain = Gain_Img(arg1)

print(main("rotation",arg2))

实时测试

见TCP传输图片

------ 本文结束 🎉🎉 谢谢观看 ------
0%