对高光谱图像进行处理的一个代码示例-以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'
### 高光谱图像分类数据集 #### Indian Pines 数据集 Indian Pines 是一个广泛使用的高光谱图像 (HSI) 数据集,适用于多种遥感应用中的分类任务。该数据集由美国印第安纳州西北部的一片农田区域获取而来,包含了丰富的农业用地信息。数据集中共有 16 类地物覆盖类型,如玉米、大豆等农作物以及草地和其他自然植被[^2]。 ```python import numpy as np from sklearn.model_selection import train_test_split # 假设 X 是特征矩阵,y 是标签向量 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) print(f"Training set size: {len(y_train)}") print(f"Testing set size: {len(y_test)}") ``` #### Caltech-UCSD Birds-200-2011 数据集 虽然主要用于细粒度视觉分类领域,但 Caltech-UCSD Birds-200-2011(CUB)也可作为多模态学习的一部分来辅助高光谱图像的研究工作。此数据集提供了详细的标注信息,包括边界框位置、部分标记和属性描述等内容,有助于提升模型对于特定物种识别的能力。不过需要注意的是,在实际应用于 HSI 场景之前可能需要额外处理步骤以适应不同传感器特性之间的差异[^4]。 #### 不平衡数据集挑战 在面对像高光谱这样的复杂场景时,类别不平衡是一个常见问题。某些类别的样本数量远少于其他类别,这可能导致训练过程中少数类被忽视,从而影响整体性能表现。解决这一难题的方法通常涉及重采样技术、调整各类权重或是采用代价敏感的学习策略等措施[^3]。
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值