Classification_Python Cheat Sheet

Cheat sheet of Land cover land use classification using python and others.

Introduction

filepath and open tif file

1
2
3
4
5
6
7
8
9
10
import rasterio

l8_path = '../data/landsat_image.tif'
labels_path = '../data/labels_image.tif'

full_dataset = rasterio.open(l8_path)
img_rows, img_cols = full_dataset.shape
img_bands = full_dataset.count
print(full_dataset.shape) # dimensions
print(full_dataset.count) # bands

Open our raster dataset

1
2
3
4

import rasterio

landsat_dataset = rasterio.open(l8_path)

How many bands does this image have?

1
2
num_bands = landsat_dataset.count
print('Number of bands in image: {n}\n'.format(n=num_bands))

How many rows and columns?

1
2
rows, cols = landsat_dataset.shape
print('Image size is: {r} rows x {c} columns\n'.format(r=rows, c=cols))

What driver was used to open the raster?

1
2
driver = landsat_dataset.driver
print('Raster driver: {d}\n'.format(d=driver))

What is the raster’s projection?

1
2
3
proj = landsat_dataset.crs
print('Image projection:')
print(proj)

Open up the dataset and read into memory

1
2
landsat_image = landsat_dataset.read()
landsat_image.shape

NDVI Calculate

1
2
3
4
bandNIR = landsat_image[4, :, :]
bandRed = landsat_image[3, :, :]

ndvi = np.clip((bandNIR.astype(float) - bandRed.astype(float)) / (bandNIR.astype(float) + bandRed.astype(float)), -1,1)

Histogram

1
2
3
4
5
6
7
import matplotlib.pyplot as plt

plt.hist(x = '需要处理的数据',bins = '需要分割的精度')
plt.xlabel('x轴标签')
plt.ylabel('y轴标签')
plt.title('总标题')
plt.show()

Classification_Python Cheat Sheet
https://mengyuchi.gitlab.io/2023/01/08/Classification-Python-Cheat-Sheet/
Author
Yuchi Meng
Posted on
January 8, 2023
Licensed under