diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3afd8ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +.vscode +data diff --git a/.vscode/settings.json b/.vscode/settings.json index 694b5d3..7a31496 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,5 @@ { - "terminal.integrated.shellArgs.windows": ["/K", "C:\\Users\\marsmith\\miniconda\\Scripts\\activate.bat C:\\Users\\marsmith\\miniconda & conda activate delineate"], - "python.pythonPath": "C:\\Users\\marsmith\\miniconda\\envs\\delineate1\\python.exe", + "python.pythonPath": "C:\\Users\\marsmith\\miniconda\\envs\\delineate\\python.exe", "python.terminal.activateEnvironment": true, "python.testing.unittestArgs": [ "-v", @@ -12,4 +11,5 @@ "python.testing.pytestEnabled": false, "python.testing.nosetestsEnabled": false, "python.testing.unittestEnabled": true, + "liveServer.settings.port": 5501, } \ No newline at end of file diff --git a/__pycache__/app.cpython-37.pyc b/__pycache__/app.cpython-37.pyc new file mode 100644 index 0000000..01ae32f Binary files /dev/null and b/__pycache__/app.cpython-37.pyc differ diff --git a/__pycache__/delineate.cpython-37.pyc b/__pycache__/delineate.cpython-37.pyc new file mode 100644 index 0000000..2af857f Binary files /dev/null and b/__pycache__/delineate.cpython-37.pyc differ diff --git a/flask_app.py b/app.py similarity index 94% rename from flask_app.py rename to app.py index 552d2fa..ee7a2ca 100644 --- a/flask_app.py +++ b/app.py @@ -32,7 +32,7 @@ def main(): lng = float(request.args.get('lng')) print(region,lat,lng) - dataPath = 'c:/temp/' + dataPath = 'C:/NYBackup/GitHub/ss-delineate/data/' #start main program results = delineate.Watershed(lat,lng,region,dataPath) diff --git a/delineate.py b/delineate.py index 1115b61..e51bae9 100644 --- a/delineate.py +++ b/delineate.py @@ -67,6 +67,7 @@ def split_catchment(self, flow_dir, geom, x, y): #method to use catchment bounding box instead of exact geom minX, maxX, minY, maxY = geom.GetEnvelope() + print('HERE', minX, minY, maxX, maxY) gdal.Warp('/vsimem/fdr.tif', flow_dir, outputBounds=[minX, minY, maxX, maxY]) #start pysheds catchment delineation @@ -501,9 +502,9 @@ def cleanup(self): timeBefore = time.perf_counter() #test site - point = (42.17209,-73.87555) #point produces zero area splitCatchment + point = (44.00683,-73.74586) region = 'ny' - dataPath = 'c:/temp/' + dataPath = 'C:/NYBackup/GitHub/ss-delineate/data/' #start main program delineation = Watershed(point[0],point[1],region,dataPath) diff --git a/nldi_delineate.py b/nldi_delineate.py new file mode 100644 index 0000000..7d5bab0 --- /dev/null +++ b/nldi_delineate.py @@ -0,0 +1,286 @@ +## NLDI split catchment delineation script + +# ----------------------------------------------------- +# Martyn Smith USGS +# 10/29/2020 +# NLDI Delineation script +# ----------------------------------------------------- + +# list of required python packages: +# gdal, pysheds, requests + +###### CONDA CREATE ENVIRONMENT COMMAND +#conda create -n delineate python=3.6.8 gdal pysheds requests +###### CONDA CREATE ENVIRONMENT COMMAND + +from osgeo import ogr, osr, gdal +from pysheds.grid import Grid +import requests +import time +import json + +#arguments +NLDI_URL = 'https://labs.waterdata.usgs.gov/api/nldi/linked-data/comid/' +NLDI_GEOSERVER_URL = 'https://labs.waterdata.usgs.gov/geoserver/wmadata/ows' +OUT_PATH = 'C:/NYBackup/GitHub/ss-delineate/data/' +IN_FDR = 'C:/NYBackup/GitHub/ss-delineate/data/nhd_fdr.tif' +OUT_FDR = 'C:/NYBackup/GitHub/ss-delineate/data/catch_fdr.tif' + +class Watershed: + + ogr.UseExceptions() + gdal.UseExceptions() + + def __init__(self, x=None, y=None): + + self.x = x + self.y = y + self.catchment_identifier = None + self.catchmentGeom = None + self.splitCatchmentGeom = None + self.upstreamBasinGeom = None + self.mergedCatchmentGeom = None + + #input point spatial reference + self.sourceprj = osr.SpatialReference() + self.sourceprj.ImportFromProj4('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs') + + # Getting spatial reference of input raster + tif = gdal.Open(IN_FDR, gdal.GA_ReadOnly) + self.Projection = tif.GetProjectionRef() + self.targetprj = osr.SpatialReference(wkt = tif.GetProjection()) + + #create transform + self.transformToRaster = osr.CoordinateTransformation(self.sourceprj, self.targetprj) + self.transformToWGS = osr.CoordinateTransformation(self.targetprj, self.sourceprj) + + #kick off + self.transform_click_point() + +## helper functions + def geom_to_geojson(self, in_geom, name, simplify_tolerance, in_ref, out_ref, write_output=False): + in_geom = in_geom.Simplify(simplify_tolerance) + out_ref.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER) + + transform = osr.CoordinateTransformation(in_ref, out_ref) + + #don't want to affect original geometry + transform_geom = in_geom.Clone() + + #trasnsform geometry from whatever the local projection is to wgs84 + transform_geom.Transform(transform) + json_text = transform_geom.ExportToJson() + + #add some attributes + geom_json = json.loads(json_text) + + #get area in local units + area = in_geom.GetArea() + + print('processing: ' + name + ' area: ' + str(area*0.00000038610)) + + geojson_dict = { + "type": "Feature", + "geometry": geom_json, + "properties": { + "area": area + } + } + + if write_output: + f = open('C:/NYBackup/GitHub/ss-delineate/data/' + name + '.geojson','w') + f.write(json.dumps(geojson_dict)) + f.close() + print('Exported geojson:', name) + + return geojson_dict + + + def geom_to_shapefile(self, geom, name): + + #write out shapefile + # set up the shapefile driver + driver = ogr.GetDriverByName("ESRI Shapefile") + + # create the data source + data_source = driver.CreateDataSource(OUT_PATH + name + '.shp') + layer = data_source.CreateLayer(name, self.targetprj, ogr.wkbPolygon) + feature = ogr.Feature(layer.GetLayerDefn()) + + # Set the feature geometry using the point + feature.SetGeometry(geom) + # Create the feature in the layer (shapefile) + layer.CreateFeature(feature) + # Dereference the feature + feature = None + + +## main functions + def transform_click_point(self): + + print('Input X,Y:', self.x, self.y) + self.projectedLng, self.projectedLat, z = self.transformToRaster.TransformPoint(self.x,self.y) + print('Projected X,Y:',self.projectedLng, ',', self.projectedLat) + + self.get_local_catchment_geom() + + def get_local_catchment_geom(self): + + wkt_point = "POINT(%f %f)" % (self.x , self.y) + cql_filter = "INTERSECTS(the_geom, %s)" % (wkt_point) + + payload = { + 'service': 'wfs', + 'version': '1.0.0', + 'request': 'GetFeature', + 'typeName': 'wmadata:catchmentsp', + 'outputFormat': 'application/json', + 'srsName': 'EPSG:4326', + 'CQL_FILTER': cql_filter + } + + #request catchment geometry from point in polygon query from NLDI geoserver + # https://labs.waterdata.usgs.gov/geoserver/wmadata/ows?service=wfs&version=1.0.0&request=GetFeature&typeName=wmadata%3Acatchmentsp&outputFormat=application%2Fjson&srsName=EPSG%3A4326&CQL_FILTER=INTERSECTS%28the_geom%2C+POINT%28-73.745860+44.006830%29%29 + r = requests.get(NLDI_GEOSERVER_URL, params=payload) + resp = r.json() + + #print(r.text) + + #get catchment id + self.catchment_identifier = json.dumps(resp['features'][0]['properties']['featureid']) + + #get main catchment geometry polygon + gj_geom = json.dumps(resp['features'][0]['geometry']) + self.catchmentGeom = ogr.CreateGeometryFromJson(gj_geom) + + #transform catchment geometry + self.catchmentGeom.Transform(self.transformToRaster) + + self.geom_to_shapefile(self.catchmentGeom, 'catchment') + + #get extent of transformed polygon + minX, maxX, minY, maxY = self.catchmentGeom.GetEnvelope() # Get bounding box of the shapefile feature + bounds = [minX, minY, maxX, maxY] + + print('projected bounds', bounds) + + self.splitCatchmentGeom = self.split_catchment(bounds, self.projectedLng,self.projectedLat) + + #get upstream basin + self.upstreamBasinGeom = self.get_upstream_basin() + + + def get_local_catchment_id(self): + + #request local catchment identifier from NLDI + # https://labs.waterdata.usgs.gov/api/nldi/linked-data/comid/position?f=json&coords=POINT(-89.35%2043.0864) + wkt_point = wkt = "POINT(%f %f)" % (self.x , self.y) + payload = {'f': 'json', 'coords': wkt_point} + + #get comid of catchment point is in + r = requests.get(NLDI_URL + 'position', params=payload) + + resp = r.json() + self.catchment_identifier = resp['features'][0]['properties']['identifier'] + + #print('identifier: ', self.catchment_identifier) + + self.get_upstream_basin() + + def get_upstream_basin(self): + + #request upstream basin + + payload = {'f': 'json', 'simplified': 'false'} + + #request upstream basin from NLDI using comid of catchment point is in + r = requests.get(NLDI_URL + self.catchment_identifier + '/basin', params=payload) + + #print('upstream basin', r.text) + resp = r.json() + + #convert geojson to ogr geom + gj_geom = json.dumps(resp['features'][0]['geometry']) + self.upstreamBasinGeom = ogr.CreateGeometryFromJson(gj_geom) + self.upstreamBasinGeom.Transform(self.transformToRaster) + + self.geom_to_shapefile(self.upstreamBasinGeom, 'upstreamBasin') + + self.mergeGeoms() + + def mergeGeoms(self): + + #create new cloned geom + self.mergedCatchmentGeom = self.upstreamBasinGeom.Clone() + + #remove downstream catchment + diff = self.catchmentGeom.Difference(self.splitCatchmentGeom.Buffer(10).Buffer(-10)) + + self.mergedCatchmentGeom = self.mergedCatchmentGeom.Difference(diff).Simplify(30) + + # #add split catchment + # self.mergedCatchmentGeom.AddGeometry(self.splitCatchmentGeom) + + # self.mergedCatchmentGeom = self.mergedCatchmentGeom.UnionCascaded() + + # self.mergedCatchmentGeom = self.mergedCatchmentGeom.Simplify(30) + + #write out + self.geom_to_shapefile(self.mergedCatchmentGeom, 'xxFinalBasinxx') + + def split_catchment(self, bounds, x, y): + + RasterFormat = 'GTiff' + PixelRes = 30 + + #method to use catchment bounding box instead of exact geom + gdal.Warp(OUT_FDR, IN_FDR, format=RasterFormat, outputBounds=bounds, xRes=PixelRes, yRes=PixelRes, dstSRS=self.Projection, resampleAlg=gdal.GRA_NearestNeighbour, options=['COMPRESS=DEFLATE']) + + #start pysheds catchment delineation + grid = Grid.from_raster(OUT_FDR, data_name='dir') + + #compute flow accumulation to snap to + dirmap = (64, 128, 1, 2, 4, 8, 16, 32) + grid.accumulation(data='dir', dirmap=dirmap, out_name='acc', apply_mask=False) + + grid.to_raster('acc', 'C:/NYBackup/GitHub/ss-delineate/data/acc.tif', view=False, blockxsize=16, blockysize=16) + + #snap the pourpoint to + xy = (x, y) + new_xy = grid.snap_to_mask(grid.acc > 50, xy, return_dist=False) + + #get catchment with pysheds + grid.catchment(data='dir', x=new_xy[0], y=new_xy[1], out_name='catch', recursionlimit=15000, xytype='label') + + # Clip the bounding box to the catchment + grid.clip_to('catch') + + #some sort of strange raster to polygon conversion using rasterio method + shapes = grid.polygonize() + + #get split Catchment geometry + print('Split catchment complete') + split_geom = ogr.Geometry(ogr.wkbPolygon) + + for shape in shapes: + split_geom = split_geom.Union(ogr.CreateGeometryFromJson(json.dumps(shape[0]))) + + #write out shapefile + self.geom_to_shapefile(split_geom, 'splitCatchment') + + return split_geom + + +if __name__=='__main__': + + timeBefore = time.perf_counter() + + #test site + point = (-73.74586, 44.00683) + + #start main program + delineation = Watershed(point[0],point[1]) + + timeAfter = time.perf_counter() + totalTime = timeAfter - timeBefore + print("Total Time:",totalTime) \ No newline at end of file diff --git a/splitCatchment.geojson b/splitCatchment.geojson new file mode 100644 index 0000000..c694285 --- /dev/null +++ b/splitCatchment.geojson @@ -0,0 +1 @@ +{"type": "Feature", "geometry": {"type": "Polygon", "coordinates": [[[-73.74600553494398, 44.00677064364619], [-73.74564034772175, 44.006708220257686], [-73.7458145778786, 44.00618486187204], [-73.74617976245392, 44.0062472847174], [-73.74626687520464, 44.00598560536642], [-73.74663205912603, 44.00604802694228], [-73.74671916988382, 44.00578634739527], [-73.74708435315124, 44.005848767701586], [-73.74717146191612, 44.005587087958546], [-73.74753664452956, 44.00564950699539], [-73.74762375130155, 44.005387827056396], [-73.747988933261, 44.0054502448237], [-73.74807603804011, 44.00518856468874], [-73.74844121934557, 44.00525098118656], [-73.74852832213182, 44.00498930085563], [-73.74889350278325, 44.005051716083926], [-73.74898060357667, 44.004790035556994], [-73.74934578357406, 44.004852449515774], [-73.74943288237465, 44.00459076879292], [-73.74979806171798, 44.004653181482276], [-73.74988515852577, 44.004391500563415], [-73.75025033721504, 44.00445391198326], [-73.75033743203005, 44.00419223086852], [-73.75070261006525, 44.004254641018825], [-73.75078970288747, 44.00399295970815], [-73.75152005831899, 44.0041177764719], [-73.75143296814363, 44.004379458325516], [-73.75106778876977, 44.004317050171174], [-73.75098069660166, 44.00457873182886], [-73.75061551657367, 44.00451632240503], [-73.75052842241277, 44.00477800386682], [-73.75016324173069, 44.004715593173515], [-73.75007614557698, 44.00497727443939], [-73.74971096424083, 44.00491486247661], [-73.74962386609431, 44.005176543546455], [-73.74925868410406, 44.005114130314205], [-73.74917158396471, 44.00537581118811], [-73.74880640132044, 44.0053133966863], [-73.74871929918821, 44.0055750773643], [-73.7483541158899, 44.005512661593016], [-73.74826701176481, 44.00577434207502], [-73.74790182781246, 44.00571192503426], [-73.74781472169447, 44.00597360532026], [-73.74744953708813, 44.00591118700994], [-73.74736242897723, 44.00617286709999], [-73.74699724371689, 44.006110447520136], [-73.74691013361307, 44.00637212741429], [-73.74654494769875, 44.00630970656482], [-73.74645783560199, 44.006571386263005], [-73.7460926490337, 44.00650896414398], [-73.74600553494398, 44.00677064364619]]]}, "properties": {"area": 22499.99999999255}} \ No newline at end of file diff --git a/test.py b/test.py new file mode 100644 index 0000000..043f605 --- /dev/null +++ b/test.py @@ -0,0 +1,124 @@ +import geojson as gj +from osgeo import ogr, osr, gdal +import os +os.environ['PROJ_LIB'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share/proj' +os.environ['GDAL_DATA'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share' + +FDR = 'C:/NYBackup/GitHub/ss-delineate/data/nhdplus/NHDPlusMA/NHDPlus02/NHDPlusFdrFac02b/fdr' +#FDR = 'C:/NYBackup/GitHub/ss-delineate/data/ny/archydro/02020001/fdr' + +# Enable GDAL/OGR exceptions +gdal.UseExceptions() + + +# GDAL & OGR memory drivers +GDAL_MEMORY_DRIVER = gdal.GetDriverByName('MEM') +OGR_MEMORY_DRIVER = ogr.GetDriverByName('Memory') + + +def cut_by_geojson(input_file, output_file, shapefile): + + VectorFormat = 'ESRI Shapefile' + VectorDriver = ogr.GetDriverByName(VectorFormat) + VectorDataset = VectorDriver.Open(shapefile, 0) # 0=Read-only, 1=Read-Write + feature = VectorDataset.GetLayer()[0] + wkt_geom = feature.GetGeometryRef() + min_x, max_x, min_y, max_y = wkt_geom.GetEnvelope() + + print('bounds1:', min_x, max_x, min_y, max_y) + + # Get coords for bounding box + # x, y = zip(*gj.utils.coords(gj.loads(shape_geojson))) + # min_x, max_x, min_y, max_y = min(x), max(x), min(y), max(y) + + # Open original data as read only + dataset = gdal.Open(input_file, gdal.GA_ReadOnly) + + bands = dataset.RasterCount + print('raster bands:', bands) + + + # Getting georeference info + transform = dataset.GetGeoTransform() + projection = dataset.GetProjection() + xOrigin = transform[0] + yOrigin = transform[3] + pixelWidth = transform[1] + pixelHeight = -transform[5] + + # Getting spatial reference of input raster + srs = osr.SpatialReference() + srs.ImportFromWkt(projection) + + # WGS84 projection reference + OSR_WGS84_REF = osr.SpatialReference() + OSR_WGS84_REF.ImportFromEPSG(4326) + + # OSR transformation + wgs84_to_image_trasformation = osr.CoordinateTransformation(OSR_WGS84_REF,srs) + XYmin = wgs84_to_image_trasformation.TransformPoint(min_x, max_y) + XYmax = wgs84_to_image_trasformation.TransformPoint(max_x, min_y) + + # Computing Point1(i1,j1), Point2(i2,j2) + i1 = int((XYmin[0] - xOrigin) / pixelWidth) + j1 = int((yOrigin - XYmin[1]) / pixelHeight) + i2 = int((XYmax[0] - xOrigin) / pixelWidth) + j2 = int((yOrigin - XYmax[1]) / pixelHeight) + new_cols = i2 - i1 + 1 + new_rows = j2 - j1 + 1 + + # New upper-left X,Y values + new_x = xOrigin + i1 * pixelWidth + new_y = yOrigin - j1 * pixelHeight + new_transform = (new_x, transform[1], transform[2], new_y, transform[4], transform[5]) + + wkt_geom.Transform(new_transform) + + print('bounds:', wkt_geom.GetEnvelope()) + + target_ds = GDAL_MEMORY_DRIVER.Create('', new_cols, new_rows, 1, gdal.GDT_Byte) + target_ds.SetGeoTransform(new_transform) + target_ds.SetProjection(projection) + + # Create a memory layer to rasterize from. + ogr_dataset = OGR_MEMORY_DRIVER.CreateDataSource('shapemask') + ogr_layer = ogr_dataset.CreateLayer('shapemask', srs=srs) + ogr_feature = ogr.Feature(ogr_layer.GetLayerDefn()) + ogr_feature.SetGeometryDirectly(ogr.Geometry(wkt=wkt_geom.ExportToWkt())) + ogr_layer.CreateFeature(ogr_feature) + + gdal.RasterizeLayer(target_ds, [1], ogr_layer, burn_values=[1], options=["ALL_TOUCHED=TRUE"]) + + # Create output file + driver = gdal.GetDriverByName('GTiff') + outds = driver.Create(output_file, new_cols, new_rows, bands, gdal.GDT_Float32) + + # Read in bands and store all the data in bandList + mask_array = target_ds.GetRasterBand(1).ReadAsArray() + band_list = [] + + for i in range(bands): + print('i:', i) + band_list.append(dataset.GetRasterBand(i + 1).ReadAsArray(i1, j1, new_cols, new_rows)) + + for j in range(bands): + data = np.where(mask_array == 1, band_list[j], mask_array) + outds.GetRasterBand(j + 1).SetNoDataValue(0) + outds.GetRasterBand(j + 1).WriteArray(data) + + outds.SetProjection(projection) + outds.SetGeoTransform(new_transform) + + target_ds = None + dataset = None + outds = None + ogr_dataset = None + + +shapefile = 'C:/NYBackup/GitHub/ss-delineate/data/OGRGeoJSON.shp' +driver = ogr.GetDriverByName("ESRI Shapefile") +dataSource = driver.Open(shapefile, 0) +feature = dataSource.GetLayer()[0] +geom = feature.GetGeometryRef() + +cut_by_geojson(FDR, 'C:/NYBackup/GitHub/ss-delineate/data/fdr.tif', shapefile) \ No newline at end of file diff --git a/test2.py b/test2.py new file mode 100644 index 0000000..60a0b39 --- /dev/null +++ b/test2.py @@ -0,0 +1,56 @@ + +import os, numpy +os.environ['PROJ_LIB'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share/proj' +os.environ['GDAL_DATA'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share' + +from osgeo import ogr, gdal, osr + +InputImage = 'C:/NYBackup/GitHub/ss-delineate/data/nhd_fdr.tif' +Shapefile = 'C:/NYBackup/GitHub/ss-delineate/data/OGRGeoJSON.shp' +OutImage = 'C:/NYBackup/GitHub/ss-delineate/data/fdr2.tif' +RasterFormat = 'GTiff' +PixelRes = 30 +VectorFormat = 'ESRI Shapefile' + +#tif with projections I want +tif = gdal.Open(InputImage) +Projection = tif.GetProjectionRef() +targetprj = osr.SpatialReference(wkt = tif.GetProjection()) + +VectorDriver = ogr.GetDriverByName(VectorFormat) +VectorDataset = VectorDriver.Open(Shapefile, 0) # 0=Read-only, 1=Read-Write +layer = VectorDataset.GetLayer() +feature = layer[0] +geom = feature.GetGeometryRef() +sourceprj = layer.GetSpatialRef() + +# WGS84 projection reference +sourprjFromEPSG = osr.SpatialReference() +sourprjFromEPSG.ImportFromProj4('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ') + +# print('1\n', sourceprj.ExportToPrettyWkt()) +# print('2\n', sourprjFromEPSG.ExportToPrettyWkt()) + +transform1 = osr.CoordinateTransformation(sourprjFromEPSG, targetprj) +transform2 = osr.CoordinateTransformation(sourceprj, targetprj) + +print('geom before:', geom.GetEnvelope()) + +print('geom from service:', '[-73.7655, 43.9866, -73.6975, 44.0203]') + +minX, maxX, minY, maxY = geom.GetEnvelope() + +geom.Transform(transform1) + +minX, maxX, minY, maxY = geom.GetEnvelope() # Get bounding box of the shapefile feature + +bounds = [minX, minY, maxX, maxY] +print('bounds:', bounds) + +OutTile = gdal.Warp(OutImage, InputImage, format=RasterFormat, outputBounds=bounds, xRes=PixelRes, yRes=PixelRes, dstSRS=Projection, resampleAlg=gdal.GRA_NearestNeighbour, options=['COMPRESS=DEFLATE']) +OutTile = None # Close dataset + +# Close datasets +Raster = None +VectorDataset.Destroy() +print("Done.") \ No newline at end of file diff --git a/test3.py b/test3.py new file mode 100644 index 0000000..594a0b6 --- /dev/null +++ b/test3.py @@ -0,0 +1,46 @@ +from osgeo import ogr, gdal, osr +import os, json +os.environ['PROJ_LIB'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share/proj' +os.environ['GDAL_DATA'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share' + +InputImage = 'C:/NYBackup/GitHub/ss-delineate/data/nhd_fdr.tif' +inputBounds = {'minX':-73.7655,'minY': 43.9866,'maxX':-73.6975,'maxY': 44.0203} +geojson = {"type":"FeatureCollection","features":[{"type":"Feature","id":"catchmentsp.70847","geometry":{"type":"MultiPolygon","coordinates":[[[[-73.7531,43.992],[-73.7557,43.9936],[-73.7575,43.9953],[-73.7592,43.9959],[-73.7603,43.9967],[-73.7604,43.9983],[-73.7609,43.9992],[-73.761,44.001],[-73.7626,44.0012],[-73.7632,44.0016],[-73.7646,44.0015],[-73.7651,44.0012],[-73.7653,44.0013],[-73.7655,44.0021],[-73.7653,44.0033],[-73.7634,44.0064],[-73.7608,44.0089],[-73.7596,44.0113],[-73.7602,44.0127],[-73.7578,44.0142],[-73.7565,44.0151],[-73.7537,44.0155],[-73.7513,44.0162],[-73.7501,44.0173],[-73.7502,44.018],[-73.7497,44.0178],[-73.7482,44.0159],[-73.7463,44.0155],[-73.7442,44.017],[-73.7423,44.0197],[-73.7394,44.0203],[-73.7375,44.0196],[-73.7359,44.0188],[-73.7283,44.0172],[-73.7267,44.0157],[-73.7302,44.0139],[-73.73,44.0126],[-73.7233,44.0053],[-73.7191,44.0043],[-73.7181,44.0038],[-73.7165,44.0031],[-73.7158,44.0015],[-73.7154,44.0003],[-73.715,43.9999],[-73.7123,44.0002],[-73.7092,44.0009],[-73.7087,44.0006],[-73.7086,44],[-73.7075,43.9995],[-73.7063,43.9985],[-73.7038,43.9992],[-73.7024,43.9986],[-73.7004,43.9966],[-73.6975,43.9954],[-73.6975,43.9945],[-73.6981,43.9936],[-73.699,43.9934],[-73.7004,43.9923],[-73.7004,43.9912],[-73.7022,43.9907],[-73.7034,43.9899],[-73.7044,43.99],[-73.7059,43.9901],[-73.7073,43.989],[-73.7087,43.9889],[-73.7104,43.9898],[-73.7126,43.989],[-73.714,43.9889],[-73.7154,43.9875],[-73.7167,43.9866],[-73.7187,43.9885],[-73.7212,43.9888],[-73.7223,43.9904],[-73.7264,43.9904],[-73.7282,43.9895],[-73.7294,43.9893],[-73.732,43.9899],[-73.7336,43.9901],[-73.7359,43.9908],[-73.7385,43.9909],[-73.7402,43.9918],[-73.7423,43.9925],[-73.7453,43.9939],[-73.7479,43.9948],[-73.7507,43.9946],[-73.752,43.9933],[-73.7529,43.992],[-73.7531,43.992]]]]},"geometry_name":"the_geom","properties":{"gridcode":1663570,"featureid":22304091,"sourcefc":"NHDFlowline","areasqkm":10.508532,"shape_length":0.180994304773454,"shape_area":0.00117919874683051,"bbox":[-73.7655,43.9866,-73.6975,44.0203]}}],"totalFeatures":1,"numberMatched":1,"numberReturned":1,"timeStamp":"2020-11-03T01:10:06.559Z","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:EPSG::4326"}},"bbox":[-73.7655,43.9866,-73.6975,44.0203]} +OutImage = 'C:/NYBackup/GitHub/ss-delineate/data/fdr3.tif' +RasterFormat = 'GTiff' +PixelRes = 30 + +#tif with projections I want +tif = gdal.Open(InputImage) +Projection = tif.GetProjectionRef() +targetprj = osr.SpatialReference(wkt = tif.GetProjection()) + +# WGS84 projection reference +sourprjFromEPSG = osr.SpatialReference() +sourprjFromEPSG.ImportFromProj4('+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs ') + +transform = osr.CoordinateTransformation(sourprjFromEPSG,targetprj) + +#grab geom from first feature +gj_geom = json.dumps(geojson['features'][0]['geometry']) +print('test', gj_geom ) +polyogr = ogr.CreateGeometryFromJson(gj_geom) +polyogr.Transform(transform) + + +minX, maxX, minY, maxY = polyogr.GetEnvelope() + +# [-73.7655,43.9866,-73.6975,44.0203] +print('bounds:', minX, maxX, minY, maxY) +# 1760643.1007263518 1766141.231241892 2540598.51252413 2543922.278361059 good albers bounds for clip + +#print('bounds:', minX, maxX, minY, maxY) + +# Create raster +OutTile = gdal.Warp(OutImage,InputImage, format=RasterFormat, outputBounds=[minX, minY, maxX, maxY], xRes=PixelRes, yRes=PixelRes, dstSRS=Projection, resampleAlg=gdal.GRA_NearestNeighbour, options=['COMPRESS=DEFLATE']) +OutTile = None # Close dataset + +# Close datasets +Raster = None +#VectorDataset.Destroy() +print("Done.") \ No newline at end of file diff --git a/test4.py b/test4.py new file mode 100644 index 0000000..d0f4643 --- /dev/null +++ b/test4.py @@ -0,0 +1,18 @@ +from osgeo import ogr +from osgeo import osr +import os +os.environ['PROJ_LIB'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share/proj' +os.environ['GDAL_DATA'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share' + +source = osr.SpatialReference() +source.ImportFromEPSG(4326) + +target = osr.SpatialReference() +target.ImportFromEPSG(5070) + +transform = osr.CoordinateTransformation(source, target) + +point = ogr.CreateGeometryFromWkt("POINT ( 43.9866 -73.7655)") +point.Transform(transform) + +print(point.ExportToWkt()) \ No newline at end of file diff --git a/test5_working.py b/test5_working.py new file mode 100644 index 0000000..bb8309c --- /dev/null +++ b/test5_working.py @@ -0,0 +1,42 @@ +from osgeo import ogr, gdal, osr +import os +os.environ['PROJ_LIB'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share/proj' +os.environ['GDAL_DATA'] = 'C:/Users/marsmith/miniconda/envs/delineate/Library/share' + +InputImage = 'C:/NYBackup/GitHub/ss-delineate/data/nhd_fdrCopy.tif' +Shapefile = 'C:/NYBackup/GitHub/ss-delineate/data/OGRGeoJSON.shp' +OutImage = 'C:/NYBackup/GitHub/ss-delineate/data/fdr2.tif' +RasterFormat = 'GTiff' +PixelRes = 30 + +#tif with projections I want +tif = gdal.Open(InputImage) +Projection = tif.GetProjectionRef() + +driver = ogr.GetDriverByName("ESRI Shapefile") +dataSource = driver.Open(Shapefile, 1) +layer = dataSource.GetLayer() +feature = layer[0] + +#set spatial reference and transformation +sourceprj = layer.GetSpatialRef() +targetprj = osr.SpatialReference(wkt = tif.GetProjection()) +transform = osr.CoordinateTransformation(sourceprj, targetprj) + +#apply transformation +transformed = feature.GetGeometryRef() +transformed.Transform(transform) +geom = ogr.CreateGeometryFromWkb(transformed.ExportToWkb()) + +minX, maxX, minY, maxY = geom.GetEnvelope() # Get bounding box of the shapefile feature + +bounds1 = [minX, minY, maxX, maxY] +print('bounds1:', bounds1) + +# Create raster +OutTile = gdal.Warp(OutImage, InputImage, format=RasterFormat, outputBounds=bounds1, xRes=PixelRes, yRes=PixelRes, dstSRS=Projection, resampleAlg=gdal.GRA_NearestNeighbour, options=['COMPRESS=DEFLATE']) +OutTile = None # Close dataset + +# Close datasets +Raster = None +print("Done.") \ No newline at end of file diff --git a/tests/__pycache__/test_delineate.cpython-37.pyc b/tests/__pycache__/test_delineate.cpython-37.pyc new file mode 100644 index 0000000..3fddbde Binary files /dev/null and b/tests/__pycache__/test_delineate.cpython-37.pyc differ