影像處理案例03

山居秋暝LS發表於2024-08-03

@

目錄
  • 1. 步驟
  • 2 . 程式碼

1. 步驟

  1. 讀入資料,把資料劃分為訓練集和測試集
  2. 用hog提取特徵
  3. 用SVM訓練資料
  4. 測試、評價模型
  5. 儲存模型
  6. 載入模型,應用模型

2 . 程式碼

import os
import cv2
import sklearn
import numpy as np
from skimage.feature import hog
from skimage import data,exposure
from sklearn import svm
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import seaborn as sn
import pandas  as pd
from joblib import dump,load
from sklearn.metrics import confusion_matrix

# 1. 讀入資料
# 1.1 處理資料,獲取影像的地址和標籤,劃分訓練集、測試集,對資料集打亂順序
data_path = r'./hand_nums'
tmp_train = os.listdir(data_path+'/train')
tmp_test = os.listdir(data_path+'/test')
train_x ,test_x = [],[]
## 1.2 獲取影像的地址,把訓練集和測試集的特徵和標籤
test_y ,test_y = [],[]
for i in tmp_train:
    if i.endswith('.bmp'):
        train_x.append(data_path+'/train/'+i)
        train_y.append(int(i.split('-')[0]))
for i in tmp_test:
    if i.endswith('.bmp'):
        test_x.append(data_path+'/test/'+i)
        test_y.append(int(i.split('.')[0]))
## 1.3 打亂資料的順序
## 訓練集、測試集的下標
train_idx = np.arange(len(train_x))
test_idx = np.arange(len(test_x))
## 打亂順序
np.random.shuffle(train_idx)
np.random.shuffle(test_idx)
## 訓練集、測試集打亂順序
train_x = list(np.array(train_x)[train_idx])
test_x = list(np.array(test_x)[test_idx])
train_y = list(np.array(train_y)[train_idx])
test_y = list(np.array(test_y)[test_idx])

# 2. 用hog提取特徵
## 2.1 hog例項化
train_feature,test_feature = [],[]
## 獲取訓練集特徵
for i in train_x:
    img_gray = cv2.imread(i,0)
    fd , img_hog = hog(img_gray,orientations=9,pixels_per_cell=(8,8),
                     cells_per_block=(2,2),visualize=True)
    train_feature.append(img_hog.flatten())
## 獲取測試集特徵
for i in test_x:
    img_gray = cv2.imread(i,0)
    fd,img_hog = hog(img_gray,orientations=9,pixels_per_cell=(8,8),
                     cells_per_block=(2,2),visualize=True)
    test_feature.append(img_hog.flatten())

# 3 SVM訓練
clf = svm.SVC(decision_function_shape='ovo')
clf.fit(train_feature ,train_y)
# 4. 測試、評價模型
dec = clf.decision_function(test_feature)
pred_y = clf.predict(test_feature)
accuracy_score(pred_y,test_y)
# 5. 儲存模型
from joblib import dump,load
## 儲存模型
dump(clf,'./hand_nums/models/poly.joblib')
## 載入模型
new_cls = load('./hand_nums/models/poly.joblib')
pred_y = new_cls.predict(test_feature)
accuracy_score(pred_y,test_y)


# 6. 載入模型,應用模型
clf_poly = svm.SVC(decision_function_shape='ovo',kernel='poly')
clf_poly.fit(train_feature ,train_y)
dec = clf_poly.decision_function(test_feature)
pred_y = clf_poly.predict(test_feature)
accuracy_score(pred_y,test_y)

clf_linear = svm.SVC(decision_function_shape='ovo',kernel='linear')
clf_linear.fit(train_feature ,train_y)
dec = clf_linear.decision_function(test_feature)
pred_y = clf_linear.predict(test_feature)
accuracy_score(pred_y,test_y)
cm = confusion_matrix(test_y,pred_y)

df_cm = pd.Dataframe(cm,index=[i for i in ['0','1','2','3','4','5','6','7','8','9']],
                     columns = [i for i in ['0','1','2','3','4','5','6','7','8','9']])
plt.figure(figsize=(10,7))
sn.heatmap(df_cm,annot=True,cmap='Green',fmt='d')

準確率 1.0
嘻嘻😁
資料集:連結:https://pan.baidu.com/s/1yFCJvcswdSgGcAN6n9u-nA 密碼:ryqo

相關文章