多光谱遥感分类(四):使用GLCM+RF

所用数据:多光谱遥感分类:使用CNN1(一)

提取纹理特征。


import numpy as np
import cv2
import os
from skimage.feature import greycomatrix, greycoprops
import pandas as pd


def get_inputs(s):
    res=[]
    input = cv2.imread(s,cv2.IMREAD_GRAYSCALE)
    glcm = greycomatrix(input, [1,2,8,16], [0,np.pi/4,np.pi/2,np.pi*3/4], 256, symmetric=True, normed=True)

    for prop in {'contrast', 'dissimilarity', 'homogeneity', 'energy', 'correlation', 'ASM'}:
        temp=greycoprops(glcm, prop)
        # temp=np.array(temp).reshape(-1)
        # print(prop,temp)
        res.append(temp)

    res=np.array(res).reshape(-1)
    return res#feather

def ext():
    res=[]
    org_dir="data/org/"

    for dir in os.listdir(org_dir):
        for d in os.listdir(org_dir + dir):
            print("dealing %s" % (org_dir+dir+"/"+d))
            feather=get_inputs(org_dir+dir+"/"+d)
            res.append(np.concatenate((feather,[dir])))

    df=pd.DataFrame(res)
    df.to_csv("data/feather.txt",header=False,index=None)

if __name__ == '__main__':
    ext()

RF分类。

from osgeo import gdal
import numpy as np
import shapefile
import cv2
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder


def rf_classify():
    data = pd.read_csv("data/feather.txt", header=None)

    x=data.iloc[:, :-1]
    print(x[:5])

    y = data.iloc[:, -1].values
    y = LabelEncoder().fit_transform(y).reshape(-1, 1)
    print(y[:5])
    # print(LabelEncoder().fit(y).inverse_transform([0, 1,2]))

    X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.33, random_state=2018)
    clf = RandomForestClassifier(n_estimators=10,  )
    clf.fit(X_train, y_train)

    score = clf.score(X_test, y_test)
    print(score)
    m = clf.predict(X_test)
    print(confusion_matrix(y_test, m))
    # joblib.dump(clf, "output/rf_model.pkl")


if __name__ == '__main__':

    rf_classify()

你可能感兴趣的:(python与人工睿智,机器学习入门与放弃)