Guest User

Untitled

a guest
Apr 26th, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. # Script to run a map classificatin using a classification tree.
  2.  
  3. import csv
  4. import os
  5. import numpy as np
  6. from sklearn import tree
  7. from osgeo import gdal
  8. import ospybook as pb
  9.  
  10. folder = r'D:\osgeopy-data\Landsat\Utah'
  11. raster_fns = ['LE70380322000181EDC02_60m.tif',
  12. 'LE70380322000181EDC02_TIR_60m.tif']
  13. out_fn = 'tree_prediction60.tif'
  14. train_fn = r'D:\osgeopy-data\Utah\training_data.csv'
  15. gap_fn = r'D:\osgeopy-data\Utah\landcover60.tif'
  16.  
  17. os.chdir(folder)
  18.  
  19. # Read the coordinates and actual classification from the csv.
  20. # This is the training data.
  21. xys = []
  22. classes = []
  23. with open(train_fn) as fp:
  24. reader = csv.reader(fp)
  25. next(reader)
  26. for row in reader:
  27. xys.append([float(n) for n in row[:2]])
  28. classes.append(int(row[2]))
  29.  
  30. # Calculate the pixel offsets for the coordinates obtained from
  31. # the csv.
  32. ds = gdal.Open(raster_fns[0])
  33. pixel_trans = gdal.Transformer(ds, None, [])
  34. offset, ok = pixel_trans.TransformPoints(True, xys)
  35. cols, rows, z = zip(*offset)
  36.  
  37. # Get the satellite data.
  38. data = pb.stack_bands(raster_fns)
  39.  
  40. # Sample the satellite data at the coordinates from the csv.
  41. sample = data[rows, cols, :]
  42.  
  43. # Fit the classification tree.
  44. clf = tree.DecisionTreeClassifier(max_depth=5)
  45. clf = clf.fit(sample, classes)
  46.  
  47. # Apply the new classification tree model to the satellite data.
  48. rows, cols, bands = data.shape
  49. data2d = np.reshape(data, (rows * cols, bands))
  50. prediction = clf.predict(data2d)
  51. prediction = np.reshape(prediction, (rows, cols))
  52.  
  53. # Set the pixels with no valid satellite data to 0.
  54. prediction[np.sum(data, 2) == 0] = 0
  55.  
  56. # Save the output.
  57. predict_ds = pb.make_raster(ds, out_fn, prediction, gdal.GDT_Byte, 0)
  58. predict_ds.FlushCache()
  59. levels = pb.compute_overview_levels(predict_ds.GetRasterBand(1))
  60. predict_ds.BuildOverviews('NEAREST', levels)
  61.  
  62. # Apply the color table from the SWReGAP landcover raster.
  63. gap_ds = gdal.Open(gap_fn)
  64. colors = gap_ds.GetRasterBand(1).GetRasterColorTable()
  65. predict_ds.GetRasterBand(1).SetRasterColorTable(colors)
  66.  
  67. del ds
Add Comment
Please, Sign In to add comment