对高光谱图像进行处理的一个代码示例-以SVM对KSC数据集进行分类为例

代码可直接跑通。

 

————————

个人技术公众号:解决方案工程师

欢迎同领域的朋友关注、相互交流。

————————

#coding: utf-8
import spectral
import matplotlib.pyplot  as plt
from sklearn.svm import SVC
import numpy as np
from scipy.io import loadmat
'''
get the KSC data

'''
import_image = loadmat(r'F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC.mat')['KSC']
output_image = loadmat(r'F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC_gt.mat')['KSC_gt']

# print import_image.shape
# print output_image.shape

np.unique(output_image)
# print np.unique(output_image)

'''
get the number of each class

'''

dict_k = {}

for i in range(output_image.shape[0]):
    for j in range(output_image.shape[1]):
        if output_image[i][j] in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]:
            if output_image[i][j] not in dict_k:
                dict_k[output_image[i][j]] = 0
            dict_k[output_image[i][j]] += 1
# print dict_k   #{1: 761, 2: 243, 3: 256, 4: 252, 5: 161, 6: 229, 7: 105, 8: 431, 9: 520, 10: 404, 11: 419, 12: 503, 13: 927}
# print reduce(lambda x,y:x+y, dict_k.values())
#add up all of the valuse in dictionary of dict_k

'''
show the picture of HSI
'''
# ground_truth = spectral.imshow(classes=output_image.astype(int), figsize=(5,5))
# ksc_color = np.array()
# ground_truth = spectral.imshow(classes= output_image.astype(int), figsize=(6,6))
# plt.show(ground_truth)    #  it shows the original picture


#if u want the picture shows differents colors , do next

# ksc_color = np.array([
#     [255,255,255],
#     [184,40,99],
#     [74,77,145],
#     [35,102,193],
#     [238,110,105],
#     [117,249,76],
#     [114,251,253],
#     [126,196,59],
#     [234,65,247],
#     [141,79,77],
#     [183,40,99],
#     [0,39,245],
#     [90,196,111],
# ])
# ground_truth = spectral.imshow(classes= output_image.astype(int), figsize=(9,9),colors = ksc_color)
# plt.show(ground_truth)

'''
change mat to csv
'''
#重构需要用到的类

need_label = np.zeros([output_image.shape[0],output_image.shape[1]])
new_datawithlabel_list = []
for i in range(output_image.shape[0]):
    for j in range (output_image.shape[1]):
        if output_image[i][j] != 0 :
            need_label[i][j]=output_image[i][j]

for i in range (output_image.shape[0]):
    for j in range (output_image.shape[1]):
            if need_label[i][j] != 0 :
                c2l = list (import_image[i][j])
                c2l.append (need_label[i][j])
                new_datawithlabel_list.append(c2l)

new_datawithlabel_array = np.array(new_datawithlabel_list)

#标准化数据并储存
from sklearn import preprocessing
data_D = preprocessing.StandardScaler().fit_transform(new_datawithlabel_array[:,:-1])
data_L = new_datawithlabel_array[:,-1]

import pandas as pd
new = np.column_stack((data_D,data_L))
new_ = pd.DataFrame(new)
new_.to_csv(r'F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC.csv',header = False , index = False)
#the above get the csv data

'''
Train the model , save the model

'''
import joblib
from sklearn.model_selection import KFold , train_test_split
from sklearn import metrics

#split train and test data
data = pd.read_csv('F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC.csv', header= None)
data = data.as_matrix()
data_D = data [:,:-1]
data_L = data[:,-1]
data_train, data_test, label_train, label_test = train_test_split(data_D,data_L,test_size= 0.5)

#train the model
clf = SVC(kernel= 'rbf', gamma = 0.125, C= 16)
clf.fit(data_train,label_train)
pred = clf.predict(data_test)
accuracy = metrics.accuracy_score(label_test,pred)*100
print accuracy

#储存学习模型
joblib.dump(clf,'KSC_MODEL.m')


'''

模型预测,在图中标记

'''
#
testdata = np.genfromtxt('F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC.csv',delimiter= ',')
# mat文件的导入
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
import spectral


# KSC
input_image = loadmat('F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC.mat')['KSC']
output_image = loadmat('F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC_gt.mat')['KSC_gt']


testdata = np.genfromtxt('F:\AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\Python_codes\shixiongdechengxu\HSIdata\KSC.csv',delimiter=',')
data_test = testdata[:,:-1]
label_test = testdata[:,-1]

# /Users/mrlevo/Desktop/CBD_HC_MCLU_MODEL.m
clf = joblib.load("KSC_MODEL.m")

predict_label = clf.predict(data_test)
accuracy = metrics.accuracy_score(label_test, predict_label)*100

print accuracy # 97.1022836308


# 将预测的结果匹配到图像中
new_show = np.zeros((output_image.shape[0],output_image.shape[1]))
k = 0
for i in range(output_image.shape[0]):
    for j in range(output_image.shape[1]):
        if output_image[i][j] != 0 :
            new_show[i][j] = predict_label[k]
            k +=1

# print new_show.shape

# 展示地物
ground_truth = spectral.imshow(classes = output_image.astype(int),figsize =(9,9))
ground_predict = spectral.imshow(classes = new_show.astype(int), figsize =(9,9))
plt.show(ground_truth)
plt.show(ground_predict)

print 'Done'
Matlab是一种强大的编程语言和开发环境,可用于高光谱图像处理和分析。支持向量机(SVM)是一种常用的机器学习方法,可以用于图像分类。 在Matlab中,我们可以使用内置的函数和工具箱来进行高光谱SVM图像分类。首先,我们需要加载图像和相应的标签数据。可以使用imread函数读取图像,使用imresize函数调整图像尺寸,以适应SVM算法的输入要求。 接下来,我们需要提取图像的特征。对于高光谱图像,可以使用各种特征提取方法,如主成分分析(PCA)或线性判别分析(LDA)。这些方法可以帮助我们降低数据维度,并保留最具代表性的特征。 然后,我们可以使用svmtrain函数训练SVM分类器。这个函数需要输入训练样本的特征和相应的标签。可以根据实际情况选择适当的参数和核函数类型。训练结束后,将得到一个训练好的SVM分类器。 最后,我们可以使用svmclassify函数对新的高光谱图像进行分类预测。这个函数需要输入测试样本的特征和之前训练得到的SVM分类器。函数将返回测试样本的分类结果。 在进行高光谱SVM图像分类时,我们还可以使用交叉验证来评估分类器的性能。可以使用crossval函数来实现。通过交叉验证,我们可以确定分类器的准确性,并调整参数以提高分类性能。 总之,利用Matlab的图像处理机器学习工具,可以方便地进行高光谱SVM图像分类。关键是选择合适的特征提取方法、调整参数以及评估分类器的性能,以获得准确而可靠的分类结果。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值