Created
June 1, 2017 17:07
-
-
Save nishadhka/4a19bf0eb7ee15e74c6e5e7da0da4f96 to your computer and use it in GitHub Desktop.
Reading, editing and visualizing Raster tiffs in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import rasterio | |
from numpy import copy, random, arange | |
import numpy as np | |
from matplotlib import pyplot | |
from matplotlib.colors import LinearSegmentedColormap | |
#Reading | |
dataset = rasterio.open('raster.tif') | |
#example raster is from https://daac.ornl.gov/VEGETATION/guides/Decadal_LULC_India.html | |
data=dataset.read(1) | |
#this data is a numpy 2D array with 20 classes from 0-19 with no value as 127 | |
#Editing | |
#to replace the class values to make only two classe values, 0 for urban and 1 for other classes, 3 is urban in tiff numpy array | |
# based on [this](https://stackoverflow.com/questions/3403973/fast-replacement-of-values-in-a-numpy-array) | |
d = {3: 0, 2: 1, 7: 1, 10: 1, 11: 1, 1: 1, 4: 1, 5: 1, 12: 1,14:1,15:1,16:1,19:1,6:1,8:1,13:1,18:1,9:1,17:1,127:1} | |
dk = d.keys() | |
dv = d.values() | |
def f1(a, d): | |
b = copy(a) | |
for k, v in d.iteritems(): | |
b[a==k] = v | |
return b | |
data1=f1(data,d) | |
#to get the statics of raster, the tiff each pixel is 100 meters, so each numpy array element is 100 meters, | |
#to get the statsics of classes in the numpy array, gives the report in dict | |
unique, counts = np.unique(data1, return_counts=True) | |
dattif=dict(zip(unique, counts)) | |
dattif | |
#visualize | |
# a custom color map is requered to have simple two colour visualization based on [this](https://stackoverflow.com/questions/32524471/custom-colormap-in-python) | |
cmap = LinearSegmentedColormap.from_list('mycmap', ['red', 'black']) | |
pyplot.imshow(data1, cmap=cmap) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment