def apply_shdi_300(in_fn, out_fn300): in_ds = gdal.Open(in_fn) in_band = in_ds.GetRasterBand(1) in_data = in_band.ReadAsArray() slices = pb.make_slices(in_data, (21, 21)) stacked_data = np.ma.dstack(slices) rows, cols = in_band.YSize, in_band.XSize out_data = np.ones((rows, cols), np.int32) * -99 out_data[10:-10, 10:-10] = np.mean(stacked_data, 2) pb.make_raster(in_ds, out_fn300, out_data, gdal.GDT_Int32, -99) del in_ds print("shdi 300 executed")
# follow the method shown in listing 10.2. os.chdir(os.path.join(data_dir, 'Massachusetts')) in_fn = 'm_4207162_ne_19_1_20140718_20140923.tif' out_fn = 'ndvi2.tif' ds = gdal.Open(in_fn) red = ds.GetRasterBand(1).ReadAsArray().astype(np.float) nir = ds.GetRasterBand(4).ReadAsArray() red = np.ma.masked_where(nir + red == 0, red) # This is the first method shown in the text. ndvi = (nir - red) / (nir + red) ndvi = np.where(np.isnan(ndvi), -99, ndvi) ndvi = np.where(np.isinf(ndvi), -99, ndvi) pb.make_raster(ds, 'ndvi2.tif', ndvi, gdal.GDT_Float32, -99) # This is the second method shown in the text. ndvi = np.where(nir + red > 0, (nir - red) / (nir + red), -99) pb.make_raster(ds, 'ndvi3.tif', ndvi, gdal.GDT_Float32, -99) del ds ########################### 10.2.2 Focal Analyses ########################### indata = np.array([ [3, 5, 6, 4, 4, 3], [4, 5, 8, 9, 6, 5], [2, 2, 5, 7, 6, 4], [5, 7, 9, 8, 9, 7],
# Script to smooth an elevation dataset. import numpy as np from osgeo import gdal import ospybook as pb in_fn = "../dati/osgeopy-data/Nepal/everest.tif" out_fn = 'everest_smoothed_edges.tif' in_ds = gdal.Open(in_fn) in_band = in_ds.GetRasterBand(1) in_data = in_band.ReadAsArray() # Stack the slices slices = pb.make_slices(in_data, (3, 3)) stacked_data = np.ma.dstack(slices) rows, cols = in_band.YSize, in_band.XSize # Initialize an output array to the NoData value (-99) out_data = np.ones((rows, cols), np.int32) * -99 # Put the result into the middle of the output, leaving the # outside rows and columns alone, so they still have -99. out_data[1:-1, 1:-1] = np.mean(stacked_data, 2) pb.make_raster(in_ds, out_fn, out_data, gdal.GDT_Int32, -99) del in_ds
(8 * cell_height) run = ((data[2] + (2 * data[5]) + data[8]) - (data[0] + (2 * data[3]) + data[6])) / \ (8 * cell_width) dist = np.sqrt(np.square(rise) + np.square(run)) return np.arctan(dist) * 180 / np.pi # Read the data as floating point. in_ds = gdal.Open(in_fn) in_band = in_ds.GetRasterBand(1) in_data = in_band.ReadAsArray().astype(np.float32) cell_width = in_ds.GetGeoTransform()[1] cell_height = in_ds.GetGeoTransform()[5] # Pass your slope function, along with the pixel size, to the # generic_filter function. This will apply your function to # each window, and each time it will pass the extra arguments # in to the function along with the data. out_data = scipy.ndimage.filters.generic_filter(in_data, slope, size=3, mode='nearest', extra_arguments=(cell_width, cell_height)) # Save the output pb.make_raster(in_ds, out_fn, out_data, gdal.GDT_Float32) del in_ds
# Script to compute NDVI. import os import numpy as np from osgeo import gdal import ospybook as pb os.chdir(r'D:\osgeopy-data\Massachusetts') in_fn = 'm_4207162_ne_19_1_20140718_20140923.tif' out_fn = 'ndvi2.tif' ds = gdal.Open(in_fn) red = ds.GetRasterBand(1).ReadAsArray().astype(np.float) nir = ds.GetRasterBand(4).ReadAsArray() # Mask the red band. red = np.ma.masked_where(nir + red == 0, red) # Do the calculation. ndvi = (nir - red) / (nir + red) # Fill the empty cells. ndvi = ndvi.filled(-99) # Set NoData to the fill value when creating the new raster. out_ds = pb.make_raster(ds, out_fn, ndvi, gdal.GDT_Float32, -99) overviews = pb.compute_overview_levels(out_ds.GetRasterBand(1)) out_ds.BuildOverviews('average', overviews) del ds, out_ds
data - 1D array containing the 9 pixel values, starting in the upper left and going left to right and down cell_width - pixel width in the same units as the data cell_height - pixel height in the same units as the data """ rise = ((data[6] + (2 * data[7]) + data[8]) - (data[0] + (2 * data[1]) + data[2])) / (8 * cell_height) run = ((data[2] + (2 * data[5]) + data[8]) - (data[0] + (2 * data[3]) + data[6])) / (8 * cell_width) dist = np.sqrt(np.square(rise) + np.square(run)) return np.arctan(dist) * 180 / np.pi # Read the data as floating point. in_ds = gdal.Open(in_fn) in_band = in_ds.GetRasterBand(1) in_data = in_band.ReadAsArray().astype(np.float32) cell_width = in_ds.GetGeoTransform()[1] cell_height = in_ds.GetGeoTransform()[5] # Pass your slope function, along with the pixel size, to the # generic_filter function. This will apply your function to # each window, and each time it will pass the extra arguments # in to the function along with the data. out_data = scipy.ndimage.filters.generic_filter( in_data, slope, size=3, mode="nearest", extra_arguments=(cell_width, cell_height) ) # Save the output pb.make_raster(in_ds, out_fn, out_data, gdal.GDT_Float32) del in_ds
folder = r"D:\osgeopy-data\Landsat\Utah" raster_fns = ["LE70380322000181EDC02_60m.tif", "LE70380322000181EDC02_TIR_60m.tif"] out_fn = "kmeans_prediction_60m.tif" # Function from list 10.10. def stack_bands(filenames): """Returns a 3D array containing all band data from all files.""" bands = [] for fn in raster_fns: ds = gdal.Open(fn) for i in range(1, ds.RasterCount + 1): bands.append(ds.GetRasterBand(i).ReadAsArray()) return np.dstack(bands) # Stack the bands and run the analysis. os.chdir(folder) data = pb.stack_bands(raster_fns) classes, centers = spectral.kmeans(data) # Save the output. ds = gdal.Open(raster_fns[0]) out_ds = pb.make_raster(ds, out_fn, classes, gdal.GDT_Byte) levels = pb.compute_overview_levels(out_ds.GetRasterBand(1)) out_ds.BuildOverviews("NEAREST", levels) out_ds.FlushCache() out_ds.GetRasterBand(1).ComputeStatistics(False) del out_ds, ds
'LE70380322000181EDC02_60m.tif', 'LE70380322000181EDC02_TIR_60m.tif' ] out_fn = 'kmeans_prediction_60m.tif' # Function from list 10.10. def stack_bands(filenames): """Returns a 3D array containing all band data from all files.""" bands = [] for fn in raster_fns: ds = gdal.Open(fn) for i in range(1, ds.RasterCount + 1): bands.append(ds.GetRasterBand(i).ReadAsArray()) return np.dstack(bands) # Stack the bands and run the analysis. os.chdir(folder) data = pb.stack_bands(raster_fns) classes, centers = spectral.kmeans(data) # Save the output. ds = gdal.Open(raster_fns[0]) out_ds = pb.make_raster(ds, out_fn, classes, gdal.GDT_Byte) levels = pb.compute_overview_levels(out_ds.GetRasterBand(1)) out_ds.BuildOverviews('NEAREST', levels) out_ds.FlushCache() out_ds.GetRasterBand(1).ComputeStatistics(False) del out_ds, ds
data = pb.stack_bands(raster_fns) # Sample the satellite data at the coordinates from the csv. sample = data[rows, cols, :] # Fit the classification tree. clf = tree.DecisionTreeClassifier(max_depth=5) clf = clf.fit(sample, classes) # Apply the new classification tree model to the satellite data. rows, cols, bands = data.shape data2d = np.reshape(data, (rows * cols, bands)) prediction = clf.predict(data2d) prediction = np.reshape(prediction, (rows, cols)) # Set the pixels with no valid satellite data to 0. prediction[np.sum(data, 2) == 0] = 0 # Save the output. predict_ds = pb.make_raster(ds, out_fn, prediction, gdal.GDT_Byte, 0) predict_ds.FlushCache() levels = pb.compute_overview_levels(predict_ds.GetRasterBand(1)) predict_ds.BuildOverviews("NEAREST", levels) # Apply the color table from the SWReGAP landcover raster. gap_ds = gdal.Open(gap_fn) colors = gap_ds.GetRasterBand(1).GetRasterColorTable() predict_ds.GetRasterBand(1).SetRasterColorTable(colors) del ds
import os import numpy as np from osgeo import gdal import ospybook as pb os.chdir(r'D:\osgeopy-data\Massachusetts') in_fn = 'm_4207162_ne_19_1_20140718_20140923_clip.tif' out_fn = 'ndvi.tif' ds = gdal.Open(in_fn) red = ds.GetRasterBand(1).ReadAsArray().astype(np.float) nir = ds.GetRasterBand(4).ReadAsArray() # Mask the red band. red = np.ma.masked_where(nir + red == 0, red) # Do the calculation. ndvi = (nir - red) / (nir + red) # Fill the empty cells. ndvi = ndvi.filled(-99) # Set NoData to the fill value when creating the new raster. out_ds = pb.make_raster( ds, out_fn, ndvi, gdal.GDT_Float32, -99) overviews = pb.compute_overview_levels(out_ds.GetRasterBand(1)) out_ds.BuildOverviews('average', overviews) del ds, out_ds
# Script to smooth an elevation dataset. import os import numpy as np from osgeo import gdal import ospybook as pb in_fn = r"D:\osgeopy-data\Nepal\everest.tif" out_fn = r'D:\Temp\everest_smoothed_edges.tif' in_ds = gdal.Open(in_fn) in_band = in_ds.GetRasterBand(1) in_data = in_band.ReadAsArray() # Stack the slices slices = pb.make_slices(in_data, (3, 3)) stacked_data = np.ma.dstack(slices) rows, cols = in_band.YSize, in_band.XSize # Initialize an output array to the NoData value (-99) out_data = np.ones((rows, cols), np.int32) * -99 # Put the result into the middle of the output, leaving the # outside rows and columns alone, so they still have -99. out_data[1:-1, 1:-1] = np.mean(stacked_data, 2) pb.make_raster(in_ds, out_fn, out_data, gdal.GDT_Int32, -99) del in_ds
data = pb.stack_bands(raster_fns) # Sample the satellite data at the coordinates from the csv. sample = data[rows, cols, :] # Fit the classification tree. clf = tree.DecisionTreeClassifier(max_depth=5) clf = clf.fit(sample, classes) # Apply the new classification tree model to the satellite data. rows, cols, bands = data.shape data2d = np.reshape(data, (rows * cols, bands)) prediction = clf.predict(data2d) prediction = np.reshape(prediction, (rows, cols)) # Set the pixels with no valid satellite data to 0. prediction[np.sum(data, 2) == 0] = 0 # Save the output. predict_ds = pb.make_raster(ds, out_fn, prediction, gdal.GDT_Byte, 0) predict_ds.FlushCache() levels = pb.compute_overview_levels(predict_ds.GetRasterBand(1)) predict_ds.BuildOverviews('NEAREST', levels) # Apply the color table from the SWReGAP landcover raster. gap_ds = gdal.Open(gap_fn) colors = gap_ds.GetRasterBand(1).GetRasterColorTable() predict_ds.GetRasterBand(1).SetRasterColorTable(colors) del ds