Exemplo n.º 1
0
    def reproject(self, src_fn, match_fn, dst_fn, lidar=False):
        src_filename = src_fn
        src = gdal.Open(src_filename, gdalconst.GA_ReadOnly)
        src_proj = src.GetProjection()
        src_geotrans = src.GetGeoTransform()

        # We want a section of source that matches this:
        match_filename = match_fn
        match_ds = gdal.Open(match_filename, gdalconst.GA_ReadOnly)
        match_proj = match_ds.GetProjection()
        match_geotrans = match_ds.GetGeoTransform()
        wide = match_ds.RasterXSize
        high = match_ds.RasterYSize

        # Output / destination
        dst_filename = dst_fn
        dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, 1, gdalconst.GDT_Float32)
        dst.SetGeoTransform( match_geotrans )
        dst.SetProjection( match_proj)
        dst.GetRasterBand(1).SetNoDataValue(-9999.0)
        a = np.ndarray(shape=(high, wide))
        a.fill(-9999.0)
        dst.GetRasterBand(1).WriteArray(a)
        if not lidar:
            gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_Bilinear)
        else:
            gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_Average)
        del dst
Exemplo n.º 2
0
def reproject_dataset_example(dataset, dataset_example, method=1):

    # open dataset that must be transformed
    try:
        if dataset.split('.')[-1] == 'tif':
            g = gdal.Open(dataset)
        else:
            g = dataset
    except:
        g = dataset
    epsg_from = Get_epsg(g)

    # open dataset that is used for transforming the dataset
    try:
        if dataset_example.split('.')[-1] == 'tif':
            gland = gdal.Open(dataset_example)
        else:
            gland = dataset_example
    except:
        gland = dataset_example
    epsg_to = Get_epsg(gland)

    # Set the EPSG codes
    osng = osr.SpatialReference()
    osng.ImportFromEPSG(epsg_to)
    wgs84 = osr.SpatialReference()
    wgs84.ImportFromEPSG(epsg_from)

    # Get shape and geo transform from example
    geo_land = gland.GetGeoTransform()
    col = gland.RasterXSize
    rows = gland.RasterYSize

    # Create new raster
    mem_drv = gdal.GetDriverByName('MEM')
    dest1 = mem_drv.Create('', col, rows, 1, gdal.GDT_Float32)
    dest1.SetGeoTransform(geo_land)
    dest1.SetProjection(osng.ExportToWkt())

    # Perform the projection/resampling
    if method is 1:
        gdal.ReprojectImage(g, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(),
                            gdal.GRA_NearestNeighbour)
    if method is 2:
        gdal.ReprojectImage(g, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(),
                            gdal.GRA_Bilinear)
    if method is 3:
        gdal.ReprojectImage(g, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(),
                            gdal.GRA_Lanczos)
    if method is 4:
        gdal.ReprojectImage(g, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(),
                            gdal.GRA_Average)
    return (dest1)
Exemplo n.º 3
0
def reproject_clip_sca_abo(src_fn, match_fn, dst_fn, src_proj_boolean=False):
    # Source
    src_filename = src_fn
    src = gdal.Open(src_filename, GA_ReadOnly)
    src_proj = src.GetProjection()
    src_geotrans = src.GetGeoTransform()

    abo_20120101 = gdal.Open("SCA/2012/abo2012_rs/abo20120101/hdr.adf")
    proj = abo_20120101.GetProjection()

    if src_proj_boolean == True:
        proj = src_proj

    # We want a section of source that matches this:
    match_filename = match_fn
    match_ds = gdal.Open(match_filename, GA_ReadOnly)
    match_proj = match_ds.GetProjection()
    match_geotrans = match_ds.GetGeoTransform()
    wide = match_ds.RasterXSize
    high = match_ds.RasterYSize

    # Output / destination
    dst_filename = dst_fn
    dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, 1,
                                               GDT_Float32)
    dst.SetGeoTransform(match_geotrans)
    dst.SetProjection(match_proj)

    # Do the work
    gdal.ReprojectImage(src, dst, proj, match_proj, GRA_Bilinear)
Exemplo n.º 4
0
def resample_raster(src_name, to_name, dst):
    """
    Resamples and reprojects raster 'src_name' to match raster 'to_name'.
    It stores the resulting raster in 'dst'.
    All the parameters are filepaths.
    """
    src = gdal.Open(src_name, gdalconst.GA_ReadOnly)
    src_proj = src.GetProjection()
    src_geotrans = src.GetGeoTransform()

    match_ds = gdal.Open(to_name, gdalconst.GA_ReadOnly)
    match_proj = match_ds.GetProjection()
    match_geotrans = match_ds.GetGeoTransform()
    wide = match_ds.RasterXSize
    high = match_ds.RasterYSize

    dst_filename = dst
    dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, 1,
                                               gdalconst.GDT_Float32)
    dst.SetGeoTransform(match_geotrans)
    dst.SetProjection(match_proj)

    gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_Bilinear)

    dst = None  # Flush
    return dst_filename
Exemplo n.º 5
0
def reproject_file(input_file_path,
                   gt_out = None,
                   prj_out = None,
                   shape_out = None,
                   outname = 'MEM',
                   resampling = gdal.gdalconst.GRA_NearestNeighbour):


    infid =  gdal.Open(input_file_path, gdal.GA_ReadOnly)
    prj_in = infid.GetProjection()
    gt_in =  infid. GetGeoTransform()
    data = infid.GetRasterBand(1).ReadAsArray().astype(np.uint8)

    if not gt_out:
        gt_out = gt_in
        
    if not prj_out:
        prj_out = prj_in
    
    if not shape_out:
        shape_out = data.shape
    
    
    outfid = save_img(np.empty(shape_out)*np.nan, 
                         gt_out, 
                         prj_out, 
                         outname,
                         dtype = gdal.GDT_UInt16)
                         
    gdal.ReprojectImage(infid, outfid, prj_in, prj_out, resampling)
    del infid
    del outfid    
Exemplo n.º 6
0
def gdal_resize(raster, dimensions, projection, transform):
    """
    Transform a dataset to the specified dimensions and projection/bounds

    :param dataset: Dataset to be resized
    :param dimensions: dimensions to resize to (X, Y)
    :param projection: Projection of of resized dataset
    :param transform: Geotransform of resized dataset
    :return: Resized dataset
    """
    dataset = get_dataset(raster)
    datatype = dataset.GetRasterBand(1).DataType
    resized_ds = gdal.GetDriverByName('MEM').Create('', dimensions[0],
                                                    dimensions[1],
                                                    dataset.RasterCount,
                                                    datatype)
    for i in range(1, resized_ds.RasterCount + 1):
        nodatavalue = dataset.GetRasterBand(i).GetNoDataValue()
        resized_band = resized_ds.GetRasterBand(i)
        resized_arr = resized_band.ReadAsArray()
        if nodatavalue:
            resized_arr[resized_arr == 0] = nodatavalue
            resized_band.SetNoDataValue(nodatavalue)
        resized_band.WriteArray(resized_arr)
    resized_ds.SetGeoTransform(transform)
    resized_ds.SetProjection(projection)

    gdal.ReprojectImage(dataset, resized_ds)
    return resized_ds
Exemplo n.º 7
0
def reproject_raster(inputRaster,
                     outFilename,
                     srs_or_refRas=None,
                     px_size=None,
                     driver='GTiff',
                     resampling=None):
    '''
    Raster reprojection. Use Spatial Reference object and provide pixel size or reference raster. If reference raster is
    provided, the output raster will have exactly the same GT.

    :param inputRaster: gdal.Datasource
    :param outFilename: filename of reprojected raster
    :param srs_or_refRas: osr.SpatialReference or gdal.Datasource
    :param px_size: int - Pixel Size in unit of target projection
    :param driver: char
    :param resampling: gdal.GRA resampling method
    :return: None - writes raster dataset to disk
    '''
    import gdal
    from geotools.vector import reproject_xy_coords
    import osr

    if resampling is None:
        resampling = gdal.GRA_Bilinear

    in_srs = get_srs_ras(inputRaster)
    in_gt = inputRaster.GetGeoTransform()

    # use reference gdal.Dataset to extract SRS, GT, pixel size - output extent will match reference
    if isinstance(srs_or_refRas, gdal.Dataset):
        refRas = srs_or_refRas
        out_srs = get_srs_ras(refRas)
        out_gt = refRas.GetGeoTransform()
        xSize = refRas.RasterXSize
        ySize = refRas.RasterYSize

    # use spatial reference and reproject whole image - create GeoTransform values and x-/y-size for reprojected raster
    if isinstance(srs_or_refRas, osr.SpatialReference):
        out_srs = srs_or_refRas
        in_gt = inputRaster.GetGeoTransform()
        ul_x, ul_y = reproject_xy_coords(in_gt[0], in_gt[3], in_srs, out_srs)
        lr_x, lr_y = reproject_xy_coords(
            in_gt[0] + in_gt[1] * inputRaster.RasterXSize,
            in_gt[3] + in_gt[5] * inputRaster.RasterYSize, in_srs, out_srs)
        out_gt = (ul_x, px_size, in_gt[2], ul_y, in_gt[4], -px_size)
        xSize = int((lr_x - ul_x) / px_size)
        ySize = int((ul_y - lr_y) / px_size)

    in_dtype = inputRaster.GetRasterBand(1).DataType
    n_bands = inputRaster.RasterCount
    out_ras = gdal.GetDriverByName(driver).Create(outFilename, xSize, ySize,
                                                  n_bands, in_dtype)
    out_ras.SetGeoTransform(out_gt)
    out_ras.SetProjection(out_srs.ExportToWkt())

    gdal.ReprojectImage(inputRaster, out_ras, in_srs.ExportToWkt(),
                        out_srs.ExportToWkt(), resampling)

    del out_ras
    return gdal.Open(outFilename)
Exemplo n.º 8
0
def ReprojectRaster(inRaster, refProj):
    drvMemR = gdal.GetDriverByName('MEM')
# (1) Build the coordinate transformation for the geotransform
    inPR = osr.SpatialReference()
    inPR.ImportFromWkt(inRaster.GetProjection())
    outPR = osr.SpatialReference()
    outPR.ImportFromWkt(refProj)
    transform = osr.CoordinateTransformation(inPR, outPR)
# (2) Build the output Geotransform, pixelsize and imagesize
    inGT = inRaster.GetGeoTransform()
    cols = inRaster.RasterXSize
    rows = inRaster.RasterYSize
    ulx, uly, ulz = transform.TransformPoint(inGT[0], inGT[3])
    lrx, lry, lrz = transform.TransformPoint(inGT[0] + inGT[1] * cols, inGT[3] + inGT[5] * rows)
    pxSize = int(lrx - ulx) / cols
    newcols = int((lrx - ulx)/ pxSize)
    newrows = int((uly - lry)/ pxSize)
    outGT = (ulx, pxSize, inGT[2], uly, inGT[4], -pxSize)
# (3) Create the new file and reproject
    dtype = inRaster.GetRasterBand(1).DataType
    outfile = drvMemR.Create('', newcols, newrows, 1, dtype)
    outfile.SetProjection(refProj)
    outfile.SetGeoTransform(outGT)
    res = gdal.ReprojectImage(inRaster, outfile, inPR.ExportToWkt(), refProj, gdal.GRA_NearestNeighbour)
    return outfile
Exemplo n.º 9
0
def reproject_image_to_master(master, slave, res=None):

    slave_ds = gdal.Open(slave)
    if slave_ds is None:
        raise IOError
    slave_proj = slave_ds.GetProjection()
    slave_geotrans = slave_ds.GetGeoTransform()
    data_type = slave_ds.GetRasterBand(1).DataType
    n_bands = slave_ds.RasterCount

    master_ds = gdal.Open(master)
    if master_ds is None:
        raise IOError
    master_proj = master_ds.GetProjection()
    master_geotrans = master_ds.GetGeoTransform()
    w = master_ds.RasterXSize
    h = master_ds.RasterYSize
    if res is not None:
        master_geotrans[1] = float(res)
        master_geotrans[-1] = -float(res)

    dst_filename = slave.replace(".tif", "_crop.tif")
    dst_ds = gdal.GetDriverByName('GTiff').Create(dst_filename, w, h, n_bands,
                                                  data_type)
    dst_ds.SetGeoTransform(master_geotrans)
    dst_ds.SetProjection(master_proj)

    gdal.ReprojectImage(slave_ds, dst_ds, slave_proj, master_proj,
                        gdal.GRA_NearestNeighbour)
    dst_ds = None  # Flush to disk
    return dst_filename
def reproject_resample_scaled(src_filename,
                              match_filename,
                              scale,
                              dst_dirc=None):
    src = gdal.Open(src_filename, gdalconst.GA_ReadOnly)
    src_proj = src.GetProjection()
    src_geotrans = src.GetGeoTransform()
    # We want a section of source that matches this:
    match_ds = gdal.Open(match_filename, gdalconst.GA_ReadOnly)
    match_proj = match_ds.GetProjection()
    match_geotrans = match_ds.GetGeoTransform()
    # match_ds is the naip at 1 m resolution.
    wide = int(np.floor(match_ds.RasterXSize / scale))
    high = int(np.floor(match_ds.RasterYSize / scale))
    bands = src.RasterCount
    # Output / destination
    # include the match file index
    index = match_filename.split('_')[4]
    dst_filename = '%s/%s_%s' % (dst_dirc, index,
                                 os.path.basename(src_filename))
    dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, bands, \
            gdalconst.GDT_Float32)
    dst.SetGeoTransform(
        [match_geotrans[0], scale, 0, match_geotrans[3], 0, -scale])
    dst.SetProjection(match_proj)
    #dst.GetRasterBand(1).WriteArray()
    # Do the work
    gdal.ReprojectImage(src, dst, src_proj, match_proj,
                        gdalconst.GRA_NearestNeighbour)
    del dst
    return (print('wrote %s' % dst_filename))
Exemplo n.º 11
0
def _warpTo(source, target, func, max_error=0.125):

    if func is None:
        raise TypeError(
            "Resampling method {} not available in your GDAL version".format(
                func))

    target = np.atleast_2d(target)
    if target.ndim < source.ndim:
        target = np.broadcast_to(target,
                                 source.shape[:-len(target.shape)] +
                                 target.shape,
                                 subok=True)

    target = np.ma.array(target,
                         mask=target == target.fill_value,
                         dtype=source.dtype,
                         copy=True,
                         subok=True)

    target[target.mask] = source.fill_value
    target.fill_value = source.fill_value

    out = _getDataset(target, True)

    gdal.ReprojectImage(_getDataset(source), out, None, None,
                        _RESAMPLING[func], 0.0, max_error)

    return _fromDataset(out)
Exemplo n.º 12
0
def resample( src_ds, target_ds, resolution=True, projection=False):

    src_ds = 'HDF4_EOS:EOS_GRID:%s:MOD_Grid_BRDF:BRDF_Albedo_Parameters_shortwave'%src_ds
    if type(src_ds) != gdal.Dataset:
        src_ds = gdal.Open(src_ds)
        if src_ds is None:
            raise ValueError
    src_proj = src_ds.GetProjection()
    src_geoT = src_ds.GetGeoTransform()

    if type(target_ds) != gdal.Dataset:
        target_ds = gdal.Open(target_ds)
        if target_ds is None:
            raise ValueError
        target_proj = target_ds.GetProjection()
        target_geoT = target_ds.GetGeoTransform()

    dst = gdal.GetDriverByName("MEM").Create("", src_ds.RasterXSize,
            src_ds.RasterYSize, target_ds.RasterCount, gdal.GDT_UInt16)
    dst.SetGeoTransform(src_geoT)
    dst.SetProjection(src_proj)

    gdal.ReprojectImage(target_ds, dst, src_proj,
                        src_proj, gdal.GRA_NearestNeighbour)
    data = dst.ReadAsArray()
    return data
Exemplo n.º 13
0
    def copy_resolution(self, refobj, resampling=3):
        """
        Copy resolution and projection from other GridObj
        Results are saved in a virtual raster
        
        INPUTS
         refobj        [instance] reference GridObj
         resampling    [int] resampling method
                        [0] Nearest Neighbour
                        [1] Averange
                        [2] Bilinear
                        [3] Cubic (default)
                        [4] Cubic Spline
        OUTPUTS
         newobj       [GridObj] resampled and reprojected new GridObj
        """
        if type(self.driver) is not _gdal.Dataset:  # it is a valid gdal dataset?
            raise TypeError('You must connect with a raster file!')
        if type(refobj.driver) is not _gdal.Dataset:  # it is a valid gdal dataset?
            raise TypeError('refobj is not a gdal Dataset!')

        # Default resampling methods
        methods = [
            _gdalconst.GRA_NearestNeighbour,
            _gdalconst.GRA_Average,
            _gdalconst.GRA_Bilinear,
            _gdalconst.GRA_Cubic,
            _gdalconst.GRA_CubicSpline
        ]
        resampling = int(resampling)
        assert 0 <= resampling <= 4
        method = methods[resampling]

        # Create memory layer
        band_data = self.driver.GetRasterBand(1)
        driver = _gdal.GetDriverByName('MEM')
        dest = driver.Create('', refobj.xsize, refobj.ysize, self.bands,
                             band_data.DataType)
        dest.SetGeoTransform(refobj.geotransform)
        dest.SetProjection(refobj.projectionref)

        # Reproject image
        _gdal.ReprojectImage(self.driver, dest, self.projectionref,
                             refobj.projectionref, method)

        # Create new grid obj
        newobj = GridObj()  # create new grid object
        newobj.driver = dest  # set connection
        newobj.filename = ''
        newobj.divername = 'MEM'
        newobj.bands = dest.RasterCount
        newobj.geotransform = dest.GetGeoTransform()
        newobj.projectionref = dest.GetProjectionRef()
        newobj.xsize = dest.RasterXSize
        newobj.ysize = dest.RasterYSize

        # Close files
        del (dest)
        band_data = None
        return(newobj)  # copy_resolution()
def reproject_resample_tif(in_raster, out_raster, ref_raster):
    ''' Reprojects the inout raster to match the CRS and cell size of the reference raster.'''
    ''' Resampling method: Nearest Neighbour.'''
    print('Reprojecting and resampling tif...')

    theinput = gdal.Open(in_raster, gdal.GA_ReadOnly)
    inputProj = theinput.GetProjection()
    inputTrans = theinput.GetGeoTransform()

    reference = gdal.Open(ref_raster, gdal.GA_ReadOnly)
    referenceProj = reference.GetProjection()
    referenceTrans = reference.GetGeoTransform()
    bandreference = reference.GetRasterBand(1)
    x = reference.RasterXSize
    y = reference.RasterYSize

    # Chceck if raster exists. If yes, delete.
    if os.path.exists(out_raster):
        print('Raster exists, deleting')
        os.remove(out_raster)

    driver = gdal.GetDriverByName('GTiff')
    output = driver.Create(out_raster, x, y, 1, bandreference.DataType)
    output.SetGeoTransform(referenceTrans)
    output.SetProjection(referenceProj)

    gdal.ReprojectImage(theinput, output, inputProj, referenceProj,
                        gdal.GRA_NearestNeighbour)
    print('Tif reprojected and resampled')

    del theinput, output, reference
Exemplo n.º 15
0
def resample_array (data,
                   gt_in,
                   prj_in,
                   gt_out = None,
                   prj_out = None,
                   shape_out = None,
                   outname = 'MEM',
                   resampling = gdal.gdalconst.GRA_Bilinear):
    
    infid = save_img (data, 
                      gt_in, 
                      prj_in, 
                      'MEM', 
                      noDataValue = np.nan, 
                      dtype=gdal.GDT_Float32)
    if not gt_out:
        gt_out = gt_in
        
    if not prj_out:
        prj_out = prj_in
    
    if not shape_out:
        shape_out = data.shape
    
    
    outfid = save_img(np.empty(shape_out)*np.nan, gt_out, prj_out, outname)
    gdal.ReprojectImage(infid, outfid, prj_in, prj_out, resampling)
    infid = None    

    data = outfid.GetRasterBand(1).ReadAsArray()
    return data
Exemplo n.º 16
0
def convertProjection(data, filename):
    landsatData = gdal.Open(filename, GA_ReadOnly)

    oldRef = osr.SpatialReference()
    oldRef.ImportFromWkt(data.GetProjectionRef())

    newRef = osr.SpatialReference()
    newRef.ImportFromWkt(landsatData.GetProjectionRef())

    transform = osr.CoordinateTransformation(oldRef, newRef)

    tVect = data.GetGeoTransform()
    nx, ny = data.RasterXSize, data.RasterYSize
    (ulx, uly, ulz) = transform.TransformPoint(tVect[0], tVect[3])
    (lrx, lry, lrz) = transform.TransformPoint(tVect[0] + tVect[1] * nx,
                                               tVect[3] + tVect[5] * ny)

    memDrv = gdal.GetDriverByName('MEM')

    dataOut = memDrv.Create('name', int((lrx - ulx) / dx), int(
        (uly - lry) / dx), 1, gdal.GDT_Float32)

    newtVect = (ulx, dx, tVect[2], uly, tVect[4], -dx)

    dataOut.SetGeoTransform(newtVect)
    dataOut.SetProjection(newRef.ExportToWkt())

    # Perform the projection/resampling
    res = gdal.ReprojectImage(data, dataOut, oldRef.ExportToWkt(),
                              newRef.ExportToWkt(), gdal.GRA_Cubic)

    return dataOut
def prep_calc(filename, path_to_ortho, path_to_slope, path_to_aspect,
              path_to_output):
    #open orthophoto and extract information
    ortho = gdal.Open(path_to_ortho, gdalconst.GA_ReadOnly)
    ortho_proj = ortho.GetProjection()

    #########################################################################################################################

    #open aspect raster and extract information
    aspect = gdal.Open(path_to_aspect, gdalconst.GA_ReadOnly)
    aspect_XSize = aspect.RasterXSize
    aspect_YSize = aspect.RasterYSize
    aspect_proj = aspect.GetProjection()
    aspect_geotransform = aspect.GetGeoTransform()

    ###########################################################################################################################

    #Preform resampling on orthophoto to match extent and resolution of aspect and slope rasters

    # Create Output / destination
    dst_filename = path_to_output + filename[:-4] + '_warped.tif'
    dst = gdal.GetDriverByName('GTiff').Create(dst_filename, aspect_XSize,
                                               aspect_YSize, 1,
                                               gdalconst.GDT_Float32)
    dst.SetGeoTransform(aspect_geotransform)
    dst.SetProjection(aspect_proj)

    # Do the work
    gdal.ReprojectImage(ortho, dst, ortho_proj, aspect_proj)

    del dst
    del aspect
    del ortho  # Flush

    return dst_filename
def resample_raster(inputfile_path,
                    referencefile_path,
                    outputfile_path,
                    band_num=1):

    input_raster = gdal.Open(inputfile_path, gdalconst.GA_ReadOnly)
    input_band = input_raster.GetRasterBand(band_num)
    inputProj = input_raster.GetProjection()
    inputTrans = input_raster.GetGeoTransform()

    reference = gdal.Open(referencefile_path, gdalconst.GA_ReadOnly)
    referenceProj = reference.GetProjection()
    referenceTrans = reference.GetGeoTransform()
    bandreference = reference.GetRasterBand(1)
    x = reference.RasterXSize
    y = reference.RasterYSize

    driver = gdal.GetDriverByName('GTiff')
    output = driver.Create(outputfile_path, x, y, 1, bandreference.DataType)
    output.SetGeoTransform(referenceTrans)
    output.SetProjection(referenceProj)

    gdal.ReprojectImage(input_raster, output, inputProj, referenceProj,
                        gdalconst.GRA_Bilinear)

    del output
Exemplo n.º 19
0
def egm96_to_wgs84_heights(dem, geoid):
    """
    Convert heights above the EGM96 geoid to heights above the WGS84 ellipsoid,
    for example, as required to use the RADARSAT-2 rational function model.        
    """

    dem_ds = gdal.Open(dem, gdal.GA_Update)
    # Load the EGM96 dataset (DEM ds is passed as an argument)
    #egm96_ds = gdal.Open(os.path.join(os.path.dirname(ag.__file__), "etc", "WW15MGH_copy.tif"))  # File is located in the software directory
    egm96_ds = gdal.Open(geoid)

    # Setup an in-memory raster using the DEM as a template
    driver = gdal.GetDriverByName("MEM")
    resamp_ds = driver.Create("", dem_ds.RasterXSize, dem_ds.RasterYSize, 1,
                              gdal.GDT_Float32)
    resamp_ds.SetProjection(dem_ds.GetProjection())
    resamp_ds.SetGeoTransform(dem_ds.GetGeoTransform())

    # Reproject / resample the EGM96 data to the DEM resolution / space.
    gdal.ReprojectImage(egm96_ds, resamp_ds, egm96_ds.GetProjection(),
                        dem_ds.GetProjection(), gdal.GRA_Cubic)

    # Add (subtract) the difference between EGM96 and WGS84 and return the resulting DEM.
    egm96 = resamp_ds.ReadAsArray()
    dem = dem_ds.ReadAsArray().astype(np.float32)
    dem[dem != -32768] += egm96[dem != -32768]

    # re-write DEM
    dem_ds.GetRasterBand(1).WriteArray(dem)
    del dem_ds
Exemplo n.º 20
0
    def reproject_dataset(self,
                          dataset,
                          pixel_spacing=None,
                          epsg_from=None,
                          epsg_to=None):
        """
        A sample function to reproject and resample a GDAL dataset from within
        Python. The idea here is to reproject from one system to another, as well
        as to change the pixel size. The procedure is slightly long-winded, but
        goes like this:

        1. Set up the two Spatial Reference systems.
        2. Open the original dataset, and get the geotransform
        3. Calculate bounds of new geotransform by projecting the UL corners
        4. Calculate the number of pixels with the new projection & spacing
        5. Create an in-memory raster dataset
        6. Perform the projection
        """
        # Define the UK OSNG, see <http://spatialreference.org/ref/epsg/27700/>
        out = osr.SpatialReference()
        out.ImportFromEPSG(epsg_to)
        sinu = osr.SpatialReference()
        # wgs84.ImportFromEPSG ( epsg_from )
        sinu.ImportFromWkt(epsg_from)
        tx = osr.CoordinateTransformation(sinu, out)
        # Up to here, all  the projection have been defined, as well as a
        # transformation from the from to the  to :)
        # We now open the dataset
        # g = gdal.Open ( dataset )

        # Get the Geotransform vector
        geo_t = dataset.GetGeoTransform()
        x_size = dataset.RasterXSize  # Raster xsize
        y_size = dataset.RasterYSize  # Raster ysize

        # Work out the boundaries of the new dataset in the target projection
        (ulx, uly, ulz) = tx.TransformPoint(geo_t[0], geo_t[3])
        (lrx, lry, lrz) = tx.TransformPoint(geo_t[0] + geo_t[1] * x_size,
                                            geo_t[3] + geo_t[5] * y_size)
        # print ulx, uly, ulz
        # print lrx, lry, lrz
        # See how using 27700 and WGS84 introduces a z-value!
        # Now, we create an in-memory raster
        mem_drv = gdal.GetDriverByName('MEM')
        # The size of the raster is given the new projection and pixel spacing
        # Using the values we calculated above. Also, setting it to store one band
        # and to use Float32 data type.
        dest = mem_drv.Create('', int((lrx - ulx) / pixel_spacing),
                              int((uly - lry) / pixel_spacing), 1,
                              gdal.GDT_Float32)
        # Calculate the new geotransform
        new_geo = (ulx, pixel_spacing, geo_t[2], uly, geo_t[4], -pixel_spacing)
        # Set the geotransform
        dest.SetGeoTransform(new_geo)
        dest.SetProjection(out.ExportToWkt())
        # Perform the projection/resampling
        res = gdal.ReprojectImage(dataset, dest, sinu.ExportToWkt(),
                                  out.ExportToWkt(), gdal.GRA_NearestNeighbour)

        return dest
def rasterReproject():
    # 获取源数据及栅格信息
    gdal.AllRegister()
    src_data = gdal.Open("smallaster.img")
    # 获取源的坐标信息
    srcSRS_wkt = src_data.GetProjection()
    srcSRS = osr.SpatialReference()
    srcSRS.ImportFromWkt(srcSRS_wkt)
    # 获取栅格尺寸
    src_width = src_data.RasterXSize
    src_height = src_data.RasterYSize
    src_count = src_data.RasterCount
    # 获取源图像的仿射变换参数
    src_trans = src_data.GetGeoTransform()
    OriginLX_src = src_trans[0]
    OriginTY_src = src_trans[3]
    pixl_w_src = src_trans[1]
    pixl_h_src = src_trans[5]

    OriginRX_src = OriginLX_src + pixl_w_src * src_width
    OriginBY_src = OriginTY_src + pixl_h_src * src_height
    # 创建输出图像
    driver = gdal.GetDriverByName("GTiff")
    driver.Register()
    dst_data = driver.Create("tpix1.tif", src_width, src_height, src_count)
    # 设置输出图像的坐标
    dstSRS = osr.SpatialReference()
    dstSRS.ImportFromEPSG(4326)
    # 投影转换
    ct = osr.CoordinateTransformation(srcSRS, dstSRS)
    # 计算目标影像的左上和右下坐标,即目标影像的仿射变换参数
    OriginLX_dst, OriginTY_dst, temp = ct.TransformPoint(
        OriginLX_src, OriginTY_src)
    OriginRX_dst, OriginBY_dst, temp = ct.TransformPoint(
        OriginRX_src, OriginBY_src)

    pixl_w_dst = (OriginRX_dst - OriginLX_dst) / src_width
    pixl_h_dst = (OriginBY_dst - OriginTY_dst) / src_height
    dst_trans = [OriginLX_dst, pixl_w_dst, 0, OriginTY_dst, 0, pixl_h_dst]
    # print outTrans
    dstSRS_wkt = dstSRS.ExportToWkt()
    # 设置仿射变换系数及投影
    dst_data.SetGeoTransform(dst_trans)
    dst_data.SetProjection(dstSRS_wkt)
    # 重新投影
    gdal.ReprojectImage(src_data, dst_data, srcSRS_wkt, dstSRS_wkt,
                        GRA_Bilinear)
    # 创建四级金字塔
    gdal.SetConfigOption('HFA_USE_RRD', 'YES')
    dst_data.BuildOverviews(overviewlist=[2, 4, 8, 16])
    # 计算统计值
    for i in range(0, src_count):
        band = dst_data.GetRasterBand(i + 1)
        band.SetNoDataValue(-99)
        print
        band.GetStatistics(0, 1)
Exemplo n.º 22
0
    def reprojectMatch(self, referenceFile, reduce_zone=True):
        """ Permet de reprojeter, découper, aligner et rééchantillonner une image à partir d'une image de référence.
                Args:
                    referenceFile (str): Path du fichier de l'image de référence à utiliser.
                    reduce_zone (bool): Indicateur permettant de choisir si on souhaite réduire la zone d'étude
                                        sur laquelle les images sont "matchées". Ceci est utile pour éviter des
                                        problèmes avec des valeurs nulles sur les bords des images qui s'alignent
                                        sur le referenceFile. Par défaut, cette option est égale à True (donc, on
                                        effectue le rétrécissement de zone).
                Returns:
                    outputfile (str): Path du fichier de l'image reprojetée.
        """
        inputFile = self.filename  # path de l'image à reprojeter

        # Ouvrir l'image de référence et obtenir sa projection ses paramètres de transformation affine
        reference = gdal.Open(referenceFile, gdalconst.GA_ReadOnly)
        referenceProj = reference.GetProjection()
        referenceTrans = reference.GetGeoTransform()
        bandreference = reference.GetRasterBand(1)

        # Transformer les paramètres de la transformation de tuples vers list afin de pouvoir les modifier.
        # On additionne la résolution des pixels aux coordonnées du coin en haut à gauche du pixel en haut à gauche
        # afin d'avoir une zone de référence plus petite que la zone de l'input file
        referenceTrans = list(referenceTrans)
        referenceTrans[0] = referenceTrans[0] + referenceTrans[1]
        referenceTrans[3] = referenceTrans[3] + referenceTrans[5]
        referenceTrans = tuple(referenceTrans)

        # on réduit la zone de 2 lignes et 2 colonnes (au bords de l'image) si reduce_zone = True
        if reduce_zone:
            x = reference.RasterXSize - 2
            y = reference.RasterYSize - 2
        else:
            x = reference.RasterXSize
            y = reference.RasterYSize

        # Créer le outputfile avec le format de l'image de référence
        if inputFile.endswith(".TIF"):  # .TIF si l'image provient de earthdata
            outputfile = inputFile.replace(".TIF", "_reproject.TIF")
        else:
            outputfile = inputFile.replace(".tif", "_reproject.tif")

        driver = gdal.GetDriverByName('GTiff')
        output = driver.Create(
            outputfile, x, y, 1, gdal.GDT_Float32
        )  # originalement bandreference.DataType au lieu de GDT_Float32
        output.SetGeoTransform(referenceTrans)
        output.SetProjection(referenceProj)

        # Reprojeter l'image
        gdal.ReprojectImage(self.dataset, output, self.proj, referenceProj,
                            gdalconst.GRA_Average)

        del output
        return outputfile
Exemplo n.º 23
0
    def coarsen(self, pixel_size, func='average'):
        """
        Constructs new field with lower granularity.

        NOTES: 

        * Resampling seems unnecessarily complicated using the GDAL python wrapper.
        The command-line 'gdalwarp' is the C++ option, but there is no similar function in 
        python.  This approach is inspired by:

        http://gis.stackexchange.com/questions/139906/replicating-result-of-gdalwarp-using-gdal-python-bindings
        
        @param pixel_size - the desired pixel size (use FieldGranularity in future?)
        @param func - the name of the function used t aggergate
        @return - a new coarser field
        """

        if func in ('average', 'mean'):
            func = gdal.GRA_Average
        elif func == 'bilinear':
            func = gdal.GRA_Bilinear
        elif func == 'cubic':
            func = gdal.GRA_Cubic
        elif func == 'cubic_spline':
            func = gdal.GRA_CubicSpline
        elif func == 'lanczos':
            func = gdal.GRA_Lanczos
        elif func == 'mode':
            func = gdal.GRA_Mode
        elif func == 'nearest_neighbor':
            func = gdal.GRA_NearestNeighbour
        else:
            raise ValueError("@func not a valid value.")

        #get bounds of current raster
        minx, miny, maxx, maxy = self.bounds()

        dest_nrows = abs(int((maxx - minx) / float(pixel_size)))
        dest_ncols = abs(int((maxy - miny) / float(pixel_size)))

        #note: seems like there is a maximum number of rows X columns (if exceeded, will return None)
        driver = gdal.GetDriverByName('MEM').Create('', dest_nrows, dest_ncols,
                                                    1, gdal.GDT_Byte)

        dest_transform = (minx, pixel_size, 0, maxy, 0, -pixel_size)
        dest.SetGeoTransform(dest_transform)
        dest.SetProjection(self.projection)

        orig_dataset = self.to_gdal_dataset()

        gdal.ReprojectImage(orig_dataset, dst, self.projection,
                            self.projection, func)

        return from_gdal_dataset(dst)
Exemplo n.º 24
0
def aggregate_grid(input_file, scale, year):
    """ Create grid that land cover data is saved in when aggregating from smaller scale to larger scale

    :param input_file:      Full path and filename of input land cover
    :type input_file:       String

    :param scale:           Resolution to aggregate data to in meters, suggested at 1000 or 3000
    :type scale:            Int

    :param year:            Year that land cover is being initialized from
    :type year:             Int

    :return:                New land cover raster at a specified resolution
    :type:                  Tiff

    """

    # Open the GeoTiff based on the input path and file
    src_ds = gdal.Open(input_file)

    # Create the name of the output file by modifying the input file
    gcam_write_file = 'gcam_' + str(int(scale)) + '_domain_' + str(
        int(year)) + '.tiff'

    # Get key info on the source data set
    src_ncols = src_ds.RasterXSize
    src_nrows = src_ds.RasterYSize

    src_geot = src_ds.GetGeoTransform()
    src_proj = src_ds.GetProjection()
    src_res = src_ds.GetGeoTransform()[1]

    agg_factor = scale / src_res

    dst_ncols = int(src_ncols / agg_factor)
    dst_nrows = int(src_nrows / agg_factor)

    dst_driver = gdal.GetDriverByName('Gtiff')
    output = os.path.join(os.path.dirname(input_file), gcam_write_file)
    dst_ds = dst_driver.Create(output, dst_ncols, dst_nrows, 1,
                               gdal.GDT_Float32)

    dst_geot = (src_geot[0], src_geot[1] * agg_factor, src_geot[2],
                src_geot[3], src_geot[4], src_geot[5] * agg_factor)

    dst_ds.SetGeoTransform(dst_geot)
    dst_ds.SetProjection(src_proj)

    gdal.ReprojectImage(src_ds, dst_ds, src_proj, src_proj, gdal.GRA_Mode)

    src_ds = None
    dst_ds = None

    return
Exemplo n.º 25
0
 def ReprojectRaster(valRaster, GEOMraster):
     vasRaster_sub = drvMemR.Create('', GEOMraster.RasterXSize,
                                    GEOMraster.RasterYSize, 1,
                                    gdal.GDT_Float32)
     vasRaster_sub.SetGeoTransform(GEOMraster.GetGeoTransform())
     vasRaster_sub.SetProjection(GEOMraster.GetProjection())
     gdal.ReprojectImage(valRaster, vasRaster_sub,
                         valRaster.GetProjection(),
                         GEOMraster.GetProjection(),
                         gdal.GRA_NearestNeighbour)
     return vasRaster_sub
Exemplo n.º 26
0
def reproject_image_to_master(master, src, dst):
    """This function reprojects an image (``src``) to
    match the extent, resolution and projection of another
    (``master``) using GDAL. The newly reprojected image
    is a GDAL VRT file for efficiency. A different spatial
    resolution can be chosen by specifyign the optional
    ``res`` parameter. The function returns the new file's
    name.
    
    *Parameters*
    
    master: str 
        A filename (with full path if required) with the 
        master image (that that will be taken as a reference)
    src: str 
        A filename (with path if needed) with the image
        that will be reprojected
    res: float, optional
        The desired output spatial resolution, if different 
        to the one in ``master``.
    
    *Returns*
    
    The reprojected filename
    
    code credit: https://github.com/jgomezdans/eoldas_ng_observations
    """
    src_ds = gdal.Open(src)
    if src_ds is None:
        raise IOError("GDAL could not open src file {}".format(src))
    src_proj = src_ds.GetProjection()
    src_geotrans = src_ds.GetGeoTransform()
    data_type = src_ds.GetRasterBand(1).DataType
    n_bands = src_ds.RasterCount

    master_ds = gdal.Open(master)
    if master_ds is None:
        raise IOError("GDAL could not open master file {}".format(master))

    master_proj = master_ds.GetProjection()
    master_geotrans = master_ds.GetGeoTransform()
    w = master_ds.RasterXSize
    h = master_ds.RasterYSize

    dst_filename = dst
    dst_ds = gdal.GetDriverByName('GTiff').Create(dst_filename, w, h, n_bands,
                                                  data_type)
    dst_ds.SetGeoTransform(master_geotrans)
    dst_ds.SetProjection(master_proj)

    gdal.ReprojectImage(src_ds, dst_ds, src_proj, master_proj,
                        gdal.GRA_NearestNeighbour)
    dst_ds = None  # Flush to disk
    return dst_filename
Exemplo n.º 27
0
    def align_raster(self, raster2align_path):
        gdal.AllRegister()
        logging.info(' *** -- aligning raster ... ')
        input = gdal.Open(raster2align_path, gdalconst.GA_ReadOnly)
        input_proj = input.GetProjection()

        try:
            if not self.reference_set:
                logging.info('        -- setting up reference raster ... ')
                self.set_reference_raster()
                logging.info('           > OK -- cooling down ... ')
                time.sleep(60)
        except:
            logging.info(
                'WARNING: Could not set reference raster for alignment.')

        try:
            outputfile = raster2align_path.split(
                '.tif')[0] + 'a.tif'  # Path to output file
        except:
            logging.info('WARNING: Invalid raster path for alignment: ' +
                         str(raster2align_path))

        try:
            if os.path.exists(outputfile):
                try:
                    logging.info('        -- removing existing file (' +
                                 outputfile + ') ... ')
                    os.remove(outputfile)
                except:
                    logging.info('WARNING: Cannot write aligned output (' +
                                 outputfile + ' is locked).')
            logging.info('        -- set driver ...')
            driver = gdal.GetDriverByName('GTiff')
            driver.Register()
            output = driver.Create(outputfile, self.x_ref, self.y_ref, 1,
                                   self.band_ref.DataType)
            logging.info('        -- apply transformation ...')
            output.SetGeoTransform(self.reference_trans)
            logging.info('        -- apply projection ...')
            output.SetProjection(self.reference_proj)
            logging.info('        -- project image ..')
            gdal.ReprojectImage(input, output, input_proj, self.reference_proj,
                                gdalconst.GRA_Bilinear)
            # dst_ds = driver.CreateCopy(destFile, output, 0)
            new_path = outputfile
            logging.info(' *** -- OK - aligned raster path: ' + new_path +
                         '... cooling down ...')
            time.sleep(5)
        except:
            logging.info('ERROR: Alignment failed.')
            new_path = 'none'
        return new_path
Exemplo n.º 28
0
def Raster_to_Array(input_tiff,
                    ll_corner,
                    x_ncells,
                    y_ncells,
                    values_type='float32'):
    """
    Loads a raster into a numpy array
    """
    # Input
    inp_lyr = gdal.Open(input_tiff)
    inp_srs = inp_lyr.GetProjection()
    inp_transform = inp_lyr.GetGeoTransform()
    inp_band = inp_lyr.GetRasterBand(1)
    inp_data_type = inp_band.DataType

    cellsize_x = inp_transform[1]
    rot_1 = inp_transform[2]
    rot_2 = inp_transform[4]
    cellsize_y = inp_transform[5]
    NoData_value = inp_band.GetNoDataValue()

    ll_x = ll_corner[0]
    ll_y = ll_corner[1]

    top_left_x = ll_x
    top_left_y = ll_y - cellsize_y * y_ncells

    # Change start point
    temp_path = tempfile.mkdtemp()
    temp_driver = gdal.GetDriverByName('GTiff')
    temp_tiff = os.path.join(temp_path, os.path.basename(input_tiff))
    temp_source = temp_driver.Create(temp_tiff, x_ncells, y_ncells, 1,
                                     inp_data_type)
    temp_source.GetRasterBand(1).SetNoDataValue(NoData_value)
    temp_source.SetGeoTransform(
        (top_left_x, cellsize_x, rot_1, top_left_y, rot_2, cellsize_y))
    temp_source.SetProjection(inp_srs)

    # Snap
    gdal.ReprojectImage(inp_lyr, temp_source, inp_srs, inp_srs,
                        gdal.GRA_Bilinear)
    temp_source = None

    # Read array
    d_type = pd.np.dtype(values_type)
    out_lyr = gdal.Open(temp_tiff)
    array = out_lyr.ReadAsArray(0, 0, out_lyr.RasterXSize,
                                out_lyr.RasterYSize).astype(d_type)
    array[pd.np.isclose(array, NoData_value)] = pd.np.nan
    out_lyr = None

    return array
Exemplo n.º 29
0
def resample_dataset(src_file_name, dst_file_name, dst_spacing_x,
                     dst_spacing_y):
    print("{}|{}|{}|{}".format(src_file_name, dst_file_name, dst_spacing_x,
                               dst_spacing_y))
    dataset = gdal.Open(src_file_name, gdal.gdalconst.GA_ReadOnly)

    src_x_size = dataset.RasterXSize
    src_y_size = dataset.RasterYSize

    print("Source dataset {} of size {}x{}".format(src_file_name, src_x_size,
                                                   src_y_size))

    src_geo_transform = dataset.GetGeoTransform()
    (ulx, uly) = (src_geo_transform[0], src_geo_transform[3])
    (lrx, lry) = (
        src_geo_transform[0] + src_geo_transform[1] * src_x_size,
        src_geo_transform[3] + src_geo_transform[5] * src_y_size,
    )

    print("Source coordinates ({}, {})-({},{})".format(ulx, uly, lrx, lry))

    dst_x_size = int(round((lrx - ulx) / dst_spacing_x))
    dst_y_size = int(round((lry - uly) / dst_spacing_y))

    print("Destination dataset {} of size {}x{}".format(
        dst_file_name, dst_x_size, dst_y_size))

    dst_geo_transform = (
        ulx,
        dst_spacing_x,
        src_geo_transform[2],
        uly,
        src_geo_transform[4],
        dst_spacing_y,
    )

    (ulx, uly) = (dst_geo_transform[0], dst_geo_transform[3])
    (lrx, lry) = (
        dst_geo_transform[0] + dst_geo_transform[1] * dst_x_size,
        dst_geo_transform[3] + dst_geo_transform[5] * dst_y_size,
    )
    print("Destination coordinates ({}, {})-({},{})".format(
        ulx, uly, lrx, lry))

    drv = gdal.GetDriverByName("GTiff")
    dest = drv.Create(dst_file_name, dst_x_size, dst_y_size, 1,
                      gdal.GDT_Float32)
    dest.SetGeoTransform(dst_geo_transform)
    dest.SetProjection(dataset.GetProjection())
    gdal.ReprojectImage(dataset, dest, dataset.GetProjection(),
                        dest.GetProjection(), gdal.GRA_Bilinear)
Exemplo n.º 30
0
def match_rasters(match_to, match_from, destination,
                  resampling_method='GRA_Bilinear', ndv=0):
    """
    Match a source raster to a match raster, including resolution and extent.

    Parameters
    ==========
    match_to : object
               A GeoDataSet object to be matched to

    match_from : object
                 A GeoDataSet object to be clipped

    destination : str
                  PATH where the output will be written

    resampling_method : str
                        Resampling method to use.  Options include:
                        {GRA_NearestNeighbor, GRA_Bilinear (Default),
                        GRA_Cubic, GRA_CubicSpline, GRA_Lanczos, GRA_Average,
                        GRA_Mode}

    Examples
    ========
    Open an example Apollo 15 Geotiff

    >>> from plio import get_path
    >>> from plio.io.io_gdal import GeoDataSet
    >>> ds = GeoDataSet(get_path('AS15-M-0296_SML_geo.tif'))
    """

    import gdalconst  # import here so Sphinx can build the docos, mocking is not working
    # TODO: If a destination is not provided create an in-memory GeoDataSet object
    match_to_srs = match_to.dataset.GetProjection()
    match_to_gt = match_to.geotransform
    width, height = match_to.raster_size

    match_from__srs = match_from.dataset.GetProjection()
    match_from__gt = match_from.geotransform

    if not has_gdal:
        raise ImportError('No module named gdal.')

    dst = gdal.GetDriverByName('GTiff').Create(destination, width, height, 1,
                                               gdalconst.GDT_Float64)

    dst.SetGeoTransform(match_to_gt)
    dst.SetProjection(match_to_srs)
    dst.GetRasterBand(1).SetNoDataValue(ndv)

    gdal.ReprojectImage(match_from.dataset, dst, None, None, getattr(gdalconst, resampling_method))