def _merge_layers(rows,
                  cols,
                  geotransform,
                  spatialreference,
                  array1,
                  array2,
                  min1,
                  max1,
                  min2,
                  max2,
                  nodata1=None,
                  nodata2=None):
    path = create_tmp_filename('', ".tif")

    # find the indexes of the arrays
    index1 = (array1 > min1) & (array1 <= max1) & (array1 != nodata1)
    index2 = (array2 > min2) & (array2 <= max2) & (array2 != nodata2)

    # merge array indexes
    compound_index = index1 & index2
    del index1, index2

    # create a new raster
    output_raster = gdal.GetDriverByName('GTiff').Create(
        path, rows, cols, 1, gdal.GDT_Int16)  # Open the file
    output_raster.SetGeoTransform(geotransform)
    srs = SpatialReference(wkt=spatialreference)
    output_raster.SetProjection(srs.ExportToWkt())
    # create raster from the compound_index of the two rasters
    # TODO: the reshape slows the operation, use matrixes
    output_raster.GetRasterBand(1).WriteArray(
        compound_index.reshape(cols, rows))
    return path
Exemple #2
0
def transform_shape(shape, ssrs, tsrs):
    """ Transform shape from ssrs to tsrs (all wkt) and return as wkt """
    ogrgeom = CreateGeometryFromWkt(shape)
    trans = CoordinateTransformation(SpatialReference(ssrs),
                                     SpatialReference(tsrs))
    ogrgeom.Transform(trans)
    wkt = ogrgeom.ExportToWkt()
    ogrgeom = None
    return wkt
Exemple #3
0
 def get_attrs(self):
     from osr import SpatialReference
     attrs = self.ds.GetMetadata()
     try:
         sp = SpatialReference(wkt=self.ds.GetProjection())
         proj4 = sp.ExportToProj4()
     except:
         warn('Could not identify projection')
     else:
         attrs['proj4'] = proj4
     return FrozenOrderedDict(attrs)
Exemple #4
0
def parse_geotiff(gtiff_file):
    """Read a geotiff file and return the grid information in it.
    """
    from osgeo import gdal
    from osr import SpatialReference

    g = gdal.Open(gtiff_file)
    srs = SpatialReference(g.GetProjection())
    proj4_str = srs.ExportToProj4()
    gtransform = g.GetGeoTransform()
    origin_x, x_psize, _, origin_y, _, y_psize = gtransform
    width = g.RasterXSize
    height = g.RasterYSize
    return proj4_str, width, height, origin_x, origin_y, x_psize, y_psize
Exemple #5
0
def gdal_translate(src_filename,
                   dst_filename,
                   dst_format="GTiff",
                   bands=None,
                   nodata=None,
                   projection=None,
                   options=None):
    """
    Convert a raster image with the specified arguments (as if running from commandline)
    :param argstring: command line arguments as string
    :return: Result of gdal_translate process (success or failure)
    """
    from osgeo import gdal
    from osr import SpatialReference

    if not options:
        options = []

    # Open existing dataset, subsetting bands if necessary
    if bands:
        tmp_file = src_filename + ".sub"
        gdal_band_subset(src_filename, bands, tmp_file)
        src_ds = gdal.Open(tmp_file)
    else:
        src_ds = gdal.Open(src_filename)
    try:
        #Open output format driver, see gdal_translate --formats for list
        driver = gdal.GetDriverByName(dst_format)

        #Output to new format
        dst_ds = driver.CreateCopy(dst_filename, src_ds, 0, options)

        if projection:
            srs = SpatialReference()
            srs.SetWellKnownGeogCS(projection)
            dst_ds.SetProjection(srs.ExportToWkt())

        if nodata is not None:
            band = dst_ds.GetRasterBand(1)
            band.SetNoDataValue(nodata)

    finally:
        #Properly close the datasets to flush to disk
        dst_ds = None
        src_ds = None
        band = None
        if bands and tmp_file:
            os.remove(tmp_file)
Exemple #6
0
    def calc_elevation_models(self):
        for item in range(len(self.data_lst)):
            file_name = self.data_lst[item].strip(".xyz")
            self.outfile = os.path.join(self.outfolder, file_name + ".tif")
            x, y, z = np.loadtxt(self.data_lst[item], skiprows=1, unpack=True)
            xmin, xmax, ymin, ymax = [min(x), max(x), min(y), max(y)]
            #size of the grid
            nx = (int(xmax - xmin + 1))
            ny = (int(ymax - ymin + 1))

            # Generate a regular grid to interpolate the data.
            xi = np.linspace(xmin, xmax, nx)
            yi = np.linspace(ymin, ymax, ny)
            xi, yi = np.meshgrid(xi, yi)
            # adding the z - values
            zi = il.griddata((x, y), z, (xi, yi),
                             method='nearest')  # linear, cubic, nearest

            #---------------  Write to GeoTIFF ------------------------
            nrows, ncols = np.shape(zi)
            xres = (xmax - xmin) / float(ncols)
            yres = (ymax - ymin) / float(nrows)
            geotransform = (xmin, xres, 0, ymin, 0, yres)

            self.outDS = gdal.GetDriverByName('GTiff').Create(
                self.outfile, ncols, nrows, 1, gdal.GDT_Float32,
                ['TFW=YES', 'COMPRESS=PACKBITS'])
            self.outDS.SetGeoTransform(geotransform)  # Specify its coordinates
            srs = SpatialReference()  # Establish its coordinate encoding
            srs.ImportFromEPSG(self.epsg)  # WGS 84 / UTM zone 32N
            self.outDS.SetProjection(
                srs.ExportToWkt())  # Exports the coordinate system to the file
            self.outDS.GetRasterBand(1).WriteArray(
                zi)  # Writes my array to the raster
            #self.outDS.FlushCache()
            self.data_out_lst.append(self.outfile)
            self.outDS = None
            zi = None
            x, y, z = None, None, None
            nrows, ncols = None, None
        return [self.message, self.data_out_lst]
 def __init__(self, src):
     """
     initialize shapefile reader
     """
     if isinstance(src, unicode):
         src = src.encode('ascii', 'ignore')
     src = self.find_source(src)
     self.shpSrc = src
     self.sr = shapefile.Reader(src)
     self.recs = []
     self.shapes = {}
     self.load_records()
     self.proj = None
     # Check if there's a spatial reference
     prj_src = src[:-4] + '.prj'
     if exists(prj_src):
         prj_text = open(prj_src).read()
         srs = SpatialReference()
         if srs.ImportFromWkt(prj_text):
             raise ValueError("Error importing PRJ information from: %s" %
                              prj_file)
         if srs.IsProjected():
             self.proj = pyproj.Proj(srs.ExportToProj4())
             print srs.ExportToProj4()
Exemple #8
0
def SubbasinDelineation(np, workingDir, dem,outlet, threshold, mpiexeDir=None,exeDir=None):
    if not os.path.exists(workingDir):
        os.mkdir(workingDir)
    statusFile = workingDir + os.sep + "status_SubbasinDelineation.txt"
    fStatus = open(statusFile, 'w')
    tauDir = workingDir + os.sep + "taudir"
    if not os.path.exists(tauDir):
        os.mkdir(tauDir)
    
    status = "Fill DEM..."
    fStatus.write("%d,%s\n" % (10, status))
    fStatus.flush()
    print Fill(np, tauDir, dem, filledDem, mpiexeDir=mpiexeDir,exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)
    
    status = "Calculating D8 and Dinf flow direction..."
    fStatus.write("%d,%s\n" % (20, status))
    fStatus.flush()
    print FlowDirD8(np, tauDir, filledDem, flowDir, slope, mpiexeDir=mpiexeDir,exeDir=exeDir)
    print GenerateDinf(np, tauDir, filledDem, flowDirDinf, slopeDinf, dirCodeDinf, weightDinf,mpiexeDir=mpiexeDir,exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)
    
    status = "Generating stream skeleton..."
    fStatus.write("%d,%s\n" % (30, status))
    fStatus.flush()
    print StreamSkeleton(np, tauDir, filledDem, streamSkeleton,mpiexeDir=mpiexeDir, exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)    
    
    status = "D8 flow accumulation..."
    fStatus.write("%d,%s\n" % (40, status))
    fStatus.flush()
    print FlowAccD8(np, tauDir, flowDir, acc,outlet=None, streamSkeleton=None, mpiexeDir=mpiexeDir,exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)
    
    status = "Generating stream raster initially..."
    fStatus.write("%d,%s\n" % (50, status))
    fStatus.flush()
    if threshold != 0:
        print StreamRaster(np, tauDir, acc, streamRaster, threshold, mpiexeDir=mpiexeDir,exeDir=exeDir)
    else:
        accD8 = tauDir+os.sep+acc
        maxAccum, minAccum, meanAccum, STDAccum = util.GetRasterStat(accD8)
        print StreamRaster(np, tauDir, acc, streamRaster, meanAccum, mpiexeDir=mpiexeDir,exeDir=exeDir)
        print "[Output], %s, %s" % (workingDir, status)
        
    status = "Moving outlet to stream..."
    fStatus.write("%d,%s\n" % (60, status))
    fStatus.flush()
    print MoveOutlet(np, tauDir, flowDir, streamRaster, outlet, modifiedOutlet, mpiexeDir=mpiexeDir,exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)
    
    status = "Flow accumulation with outlet..."
    fStatus.write("%d,%s\n" % (70, status))
    fStatus.flush()
    print FlowAccD8(np, tauDir, flowDir, acc, modifiedOutlet, streamSkeleton, mpiexeDir=mpiexeDir, exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)
    
    if threshold == 0:
        status = "Drop analysis to select optimal threshold..."
        fStatus.write("%d,%s\n" % (75, status))
        fStatus.flush()
        if meanAccum - STDAccum < 0:
            minthresh = meanAccum
        else:
            minthresh = meanAccum - STDAccum
        maxthresh = meanAccum + STDAccum
        numthresh = 20
        logspace = 'true'
        drpFile = 'drp.txt'
        print DropAnalysis(np,tauDir,filledDem,flowDir,acc,acc,modifiedOutlet,minthresh,maxthresh,numthresh,logspace,drpFile, mpiexeDir=mpiexeDir,exeDir=exeDir)
        drpf = open(drpFile,"r")
        tempContents=drpf.read()
        (beg,threshold)=tempContents.rsplit(' ',1)
        print threshold
        drpf.close()
        print "[Output], %s, %s" % (workingDir, status)
        
    status = "Generating stream raster..."
    fStatus.write("%d,%s\n" % (80, status))
    fStatus.flush()
    print StreamRaster(np, tauDir, acc, streamRaster, float(threshold), mpiexeDir=mpiexeDir,exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)

    status = "Generating stream net..."
    fStatus.write("%d,%s\n" % (90, status))
    fStatus.flush()
    print StreamNet(np, tauDir, filledDem, flowDir, acc, streamRaster, modifiedOutlet, streamOrder, chNetwork, chCoord, streamNet, subbasin, mpiexeDir=mpiexeDir, exeDir=exeDir)
    print "[Output], %s, %s" % (workingDir, status)
        
    fStatus.write("100,subbasin delineation is finished!")
    fStatus.close()
    
    ds = gdal.Open(dem)
    configFile = workingDir + os.sep + 'ProjConfig.txt'
    f = open(configFile, 'w')
    f.write(dem + "\n")
    f.write(str(threshold) + "\n")
    projWkt = ds.GetProjection()
    srs = SpatialReference()
    srs.ImportFromWkt(projWkt)
    proj4Str = srs.ExportToProj4()
    f.write(proj4Str + "\n")
    f.close()