def gdaldem(self, Input1, Operation, OutputFilePath): """ Creates an aspect layer from a digital elevation model by identifing the compass direction that the downhill slope faces for each location (returns with a value between 0-360 degrees) Parameters: Input1: An SpaDatasetRaster object OR a string representing the path to the raster file OutputFilePath: A file path for the output raster Return: A SpaDatasetRaster object depicting aspect """ Input1 = SpaBase.GetInput(Input1) NewDataset = None # if a file path is specified, use it. Otherwise, use the regular TempFilePath TempFilePath = None if (OutputFilePath == None): TempFilePath = SpaBase.GetTempFolderPath() if not os.path.exists(TempFilePath): os.makedirs(TempFilePath) TempFilePath += "Test.tif" else: TempFilePath = OutputFilePath GDALDataset1 = Input1.GDALDataset gdal.DEMProcessing(TempFilePath, GDALDataset1, Operation) if (OutputFilePath == None): NewDataset = SpaRasters.SpaDatasetRaster() NewDataset.Load(TempFilePath) NewDataset.NoDataValue = -9999 return (NewDataset)
def Show(TheDataset, width=800, height=800): # IF a file path is specified, load the dataset if (type(TheDataset) is str): filename, file_extension = os.path.splitext(TheDataset) file_extension = file_extension.lower() if (file_extension == ".shp"): TheDataset = SpaVectors.Load( TheDataset) # load the contents of the layer else: TheDataset = SpaRasters.Load(TheDataset) # Create the view TheView = SpaView(width, height) # Set the bounds of the view to match the dataset TheBounds = TheDataset.GetBounds() TheView.SetBounds(TheBounds) # Render the dataset into the view if (isinstance(TheDataset, SpaRasters.SpaDatasetRaster)): TheView.RenderRaster(TheDataset) elif (isinstance(TheDataset, SpaVectors.SpaDatasetVector)): TheView.RenderVectors(TheDataset) TheView.Show()
def Hillshade(self, Input1, azimuth=315, altitude=45): """ Creates a hillshade layer from a digital elevation model by determining hypothetical illumination values for each cell based on provided azimuth and altitude values Parameters: Input1: An SpaDatasetRaster object OR a string representing the path to the raster file Return: A SpaDatasetRaster object depicting hillshade """ NewDataset = SpaRasters.SpaDatasetRaster() NewDataset.CopyPropertiesButNotData(Input1) array = Input1.TheBands[0] azimuth = 360.0 - azimuth x, y = numpy.gradient(array) slope = numpy.pi / 2. - numpy.arctan(numpy.sqrt(x * x + y * y)) aspect = numpy.arctan2(-x, y) azimuthrad = azimuth * numpy.pi / 180. altituderad = altitude * numpy.pi / 180. shaded = numpy.sin(altituderad) * numpy.sin(slope) + numpy.cos( altituderad) * numpy.cos(slope) * numpy.cos( (azimuthrad - numpy.pi / 2.) - aspect) shaded = 255 * (shaded + 1) / 2 NewDataset.TheBands = [shaded] return (NewDataset)
def GetInput(InputFile): """ Return an object that can be used for transforming. This is typically a layer object @Protected Parameters: InputFile: File to be used in transform (vector or raster file) Returns: a SpaDatasetRaster or SpaDatasetVector object """ #print(type(InputFile)) if (isinstance(InputFile, str)): Extension = os.path.splitext(InputFile)[1] Extension = Extension.lower() if (Extension == ".shp"): FilePath = InputFile InputFile = SpaVectors.SpaDatasetVector() InputFile.Load(FilePath) else: FilePath = InputFile InputFile = SpaRasters.SpaDatasetRaster() InputFile.Load(FilePath) return (InputFile)
def Contour(self, Input1, ContourInterval=100, contourBase=0, OutputFilePath=None): """ Creates a vector dataset with contour lines from a DEM. Parameters: Input1: An SpaDatasetRaster object OR a string representing the path to the raster file Return: A SpaDatasetRaster object depicting aspect """ Input1 = SpaBase.GetInput(Input1) NewDataset = SpaRasters.SpaDatasetRaster() NewDataset.CopyPropertiesButNotData(Input1) UseNoData = 0 NoDataValue = 0 if (Input1.GetNoDataValue() != None): UseNoData = 1 NoDataValue = Input1.GetNoDataValue() TheBand = Input1.GDALDataset.GetRasterBand(1) #Generate layer to save Contourlines in #TheDataset=SpaVectors.SpaDatasetVector() #create a new layer ## add a square geometry in at 0,0 #TheDataset.AddAttribute("ID","int") #TheDataset.AddAttribute("elev","float") ## Save the result #TheDataset.Save(OutputFolderPath+"NewBox.shp") ogr_ds = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource( OutputFilePath) contour_shp = ogr_ds.CreateLayer('contour') field_defn = ogr.FieldDefn("ID", ogr.OFTInteger) contour_shp.CreateField(field_defn) field_defn = ogr.FieldDefn("elev", ogr.OFTReal) contour_shp.CreateField(field_defn) #ContourGenerate(Band srcBand, double contourInterval, double contourBase, int fixedLevelCount, int useNoData, double noDataValue, Layer dstLayer, int idField, int elevField, GDALProgressFunc callback=0, void * callback_data=None) gdal.ContourGenerate(TheBand, ContourInterval, contourBase, [], UseNoData, NoDataValue, contour_shp, 0, 1) ogr_ds = None return (NewDataset)
def TransformRaster(self, TheObject, OutputFilePath): # Create the destination SRS """ Projects a raster dataset Parameters: TheRaster: Raster dataset to be projected OutputFilePath: File path to location where output will be stored Returns: Projected raster dataset """ #Settings=self.GetSettings(SpaProj) self.Initialize() #self.TheProjection=GetProjection(,LatNewPole,Settings["Parameters"]) #ProjectionCode=Settings["ProjectionCode"] #Parameters=Settings["Parameters"] #ToCRS=pyproj.CRS.from_user_input(self.ToCRS) DesitnationSRS = self.ToCRS.to_proj4() # Version to convert dictionary to proj4 string #Parameters=self.ToCRS #DesitnationSRS="" #"+proj="+ProjectionCode #for key in Parameters: # DesitnationSRS+=" +"+key+"="+format(Parameters[key]) #DesitnationSRS=self.ToCRS # Create the new dataset NewDataset = SpaRasters.SpaDatasetRaster() NewDataset.CopyPropertiesButNotData(TheObject) NewDataset.AllocateArray() NewDataset.Save( OutputFilePath ) # this is ugly but it is the only way we could figure out to create a GDALDataset #NewDataset.Load(OutputFilePath) InputGDALDataset = TheObject.GDALDataset #OutputGDALDataset = NewDataset.GDALDataset GDALDataset = gdal.Warp(OutputFilePath, InputGDALDataset, dstSRS=DesitnationSRS) NewDataset.Load(OutputFilePath) return (NewDataset)
def RenderRaster(self, TheRasterDataset, Stretch=True): ######################################################################## # Crop the raster to the vewing area if needed TheRasterBounds = TheRasterDataset.GetBounds( ) # upper left, lower right (XMin,YMax,XMax,YMin) TheViewBounds = self.GetBounds() RasterXMin = TheRasterBounds[0] RasterYMin = TheRasterBounds[1] RasterXMax = TheRasterBounds[2] RasterYMax = TheRasterBounds[3] DoCrop = False if (TheRasterBounds[0] < TheViewBounds[0]): # crop left side RasterXMin = TheViewBounds[0] DoCrop = True if (TheRasterBounds[1] < TheViewBounds[1]): # crop bottom RasterYMin = TheViewBounds[1] DoCrop = True if (TheRasterBounds[2] > TheViewBounds[2]): # crop right RasterXMax = TheViewBounds[2] DoCrop = True if (TheRasterBounds[3] > TheViewBounds[3]): # crop top RasterYMax = TheViewBounds[3] DoCrop = True if (DoCrop): TheRasterDataset = SpaRasters.Crop( TheRasterDataset, [RasterXMin, RasterYMin, RasterXMax, RasterYMax]) TheRasterBounds = TheRasterDataset.GetBounds() RasterXMin = TheRasterBounds[0] RasterYMin = TheRasterBounds[1] RasterXMax = TheRasterBounds[2] RasterYMax = TheRasterBounds[3] ############################################# # Scale the raster to match the view XFactor = (RasterXMax - RasterXMin) / TheRasterDataset.GetWidthInPixels() ChangeFactor = XFactor / self.Factor if (ChangeFactor != 1): TheRasterDataset = SpaRasters.Resample(TheRasterDataset, ChangeFactor) ############################################# # Stretch the raster if needed TheBands = TheRasterDataset.GetBands() WidthInPixels = TheRasterDataset.GetWidthInPixels() HeightInPixels = TheRasterDataset.GetHeightInPixels() RasterSize = WidthInPixels * HeightInPixels TheBand = TheBands[0] if (Stretch): Min, Max = TheRasterDataset.GetMinMax(0) # Min=numpy.amin(TheBand) # Max=numpy.amax(TheBand) super_threshold_indices = TheBand < 0.00000001 TheBand[super_threshold_indices] = 0 Min = numpy.amin(TheBand) Factor = 255 / Max TheBand = TheBand * Factor TheRasterImage = PIL.Image.fromarray(numpy.uint8(TheBand)) ########################################### # Draw the raster into the view TheImage = self.GetImage() PixelXMin = self.GetPixelXFromRefX(RasterXMin) PixelYMin = self.GetPixelYFromRefY(RasterYMax) PixelXMin = int(PixelXMin) PixelYMin = int(PixelYMin) PixelXMax = PixelXMin + WidthInPixels PixelYMax = PixelYMin + HeightInPixels TheImage.paste(TheRasterImage, (PixelXMin, PixelYMin, PixelXMax, PixelYMax))
UTMToGeographic = SpaReferencing.Transform(Dataset_UTMZone10North, 4326) SpaView.Show(UTMToGeographic) UTMToGeographic.Save(OutputFolderPath + "Geographic.shp") # Project to NAD83 / California zone 1 UTMToStatePlane = SpaReferencing.Transform(Dataset_UTMZone10North, 26941) SpaView.Show(UTMToStatePlane) # Project to Albers Equal Area AlbersEqualArea = SpaReferencing.Transform(CountriesDataset, AlbersEqualArea_Parameters) SpaView.Show(AlbersEqualArea) ####################################################################### BlueMarbleRaster = SpaRasters.SpaDatasetRaster() #create a new layer BlueMarbleRaster.Load(NASABlueMarble) # load the contents of the layer #SpaView.Show(BlueMarbleRaster) # Currently, we are using a GDAL function that requires an output path for the projected raster file so there is a different function to projecting rasters AlbersEqualArea = SpaReferencing.TransformRaster( BlueMarbleRaster, OutputFolderPath + "BlueMarble_Albers.tif", AlbersEqualArea_Parameters) SpaView.Show(AlbersEqualArea) # Project to UTM AlbersEqualArea = SpaReferencing.TransformRaster( BlueMarbleRaster, OutputFolderPath + "BlueMarble_UTM.tif", 32610) SpaView.Show(AlbersEqualArea)
############################################################################ # Globals ############################################################################ OutputFolderPath = "../Temp/" RasterFilePath = "../Data/MtStHelens/Mt St Helens Post Eruption DEM Int16.tif" #RasterFilePath2="../Data/MtStHelens/Mt St Helens PreEruption DEM Float32.tif" Path1 = "../Data/MtStHelens/Mt St Helens PreEruption DEM Float32.tif" #Path2="../Data/MtStHelens/Mt St Helens Post Eruption DEM.tif" ############################################################################ # SpaView Tests ############################################################################ TheDataset = SpaRasters.Load(Path1) SpaTopo.Contour(Path1, OutputFilePath=OutputFolderPath + "Countours.shp") #SpaView.Show(OutputFolderPath+"Countours.shp") SpaTopo.TRI(Path1, OutputFilePath=OutputFolderPath + "TRI.tif") SpaView.Show(OutputFolderPath + "TRI.tif") # deal with no data values #TRIDataset.Save(OutputFolderPath+"TRI.tif") SpaTopo.Slope(TheDataset, OutputFilePath=OutputFolderPath + "Slope.tif") SpaView.Show(OutputFolderPath + "Slope.tif") SpaTopo.Aspect(TheDataset, OutputFilePath=OutputFolderPath + "Aspect.tif") SpaView.Show(OutputFolderPath + "Aspect.tif") SlopeDataset = SpaRasters.Load(OutputFolderPath + "Slope.tif") AspectDataset = SpaRasters.Load(OutputFolderPath + "Aspect.tif")
############################################################################ # Globals ############################################################################ RasterFilePath="../Data/MtStHelens/Mt St Helens PreEruption DEM Float32.tif" RasterFilePath2="../Data/MtStHelens/Mt St Helens Post Eruption DEM Float32.tif" TempFolderPath="../Temp/" ######################################################################### # Raster opterations ######################################################################### TheDataset =SpaRasters.SpaDatasetRaster() TheDataset.Load(RasterFilePath2) print("____________________________________") print("Loading Raster: "+RasterFilePath) print(TheDataset.GetDriverNames()) print("Width in pixels: "+format(TheDataset.GetWidthInPixels())) print("Height in pixels: "+format(TheDataset.GetHeightInPixels())) print("Pixel Type: "+format(TheDataset.GetType())) #print("CRS:"+format(TheDataset.GetCRS())) # returns a WKT string
TheDataset = SpaReferencing.Transform( TheDataset, 32610) # EPSG Number for UTM Zone 10 North TheDataset.Save(OutputFolderPath + "UTMZone10North.shp") # Get the view to write out a PNG and display the dataset in a tkinter window TheView = GetViewForDataset(TheDataset, 800, 800, (-160, -90, -90, 90)) TheView.Save(OutputFolderPath + "UTMZone10North.png") TheView.Show() ######################################################################### # Project a dataset based on a EPSG number if (True): TheDataset = SpaRasters.SpaDatasetRaster() TheDataset.Load(RasterFilePath) TheView = SpaView.SpaView(800, 800) TheBounds = TheDataset.GetBounds() TheView.SetBounds(TheBounds) TheView.RenderRaster(TheDataset) TheView.Save(OutputFolderPath + "Raster.png") TheView.Show() ####################################################################### # find missing area of mt st helens