def matchData(data_src, data_match, type, nRow, nCol): # funcion que retorna la informacion presente en el raster data_scr # modificada con los datos de proyeccion y transformacion del raster data_match # se crea un raster en memoria que va a ser el resultado #data_result = gdal.GetDriverByName('MEM').Create('', data_match.RasterXSize, data_match.RasterYSize, 1, gdalconst.GDT_Float64) data_result = gdal.GetDriverByName('MEM').Create('', nCol, nRow, 1, gdalconst.GDT_Float64) # Se establece el tipo de proyección y transfomcion en resultado qye va ser coincidente con data_match data_result.SetGeoTransform(data_match.GetGeoTransform()) data_result.SetProjection(data_match.GetProjection()) # se cambia la proyeccion de data_src, con los datos de data_match y se guarda en data_result if (type == "Nearest"): gdal.ReprojectImage(data_src, data_result, data_src.GetProjection(), data_match.GetProjection(), gdalconst.GRA_NearestNeighbour) if (type == "Bilinear"): gdal.ReprojectImage(data_src, data_result, data_src.GetProjection(), data_match.GetProjection(), gdalconst.GRA_Bilinear) if (type == "Cubic"): gdal.ReprojectImage(data_src, data_result, data_src.GetProjection(), data_match.GetProjection(), gdalconst.GRA_Cubic) return data_result
def reproject_dataset_example(dataset, dataset_example, method=1): try: if (os.path.splitext(dataset)[-1] == '.tif' or os.path.splitext(dataset)[-1] == '.TIF'): g_in = gdal.Open(dataset) else: g_in = dataset except: g_in = dataset epsg_from = get_projection(g_in) # open dataset that is used for transforming the dataset try: if (os.path.splitext(dataset_example)[-1] == '.tif' or os.path.splitext(dataset_example)[-1] == '.TIF'): g_ex = gdal.Open(dataset_example) else: g_ex = dataset_example except: g_ex = dataset_example epsg_to = get_projection(g_ex) Y_raster_size = g_ex.RasterYSize X_raster_size = g_ex.RasterXSize Geo = g_ex.GetGeoTransform() ulx = Geo[0] uly = Geo[3] lrx = ulx + X_raster_size * Geo[1] lry = uly + Y_raster_size * Geo[5] # Set the EPSG codes osng = osr.SpatialReference() osng.ImportFromProj4(epsg_to) wgs84 = osr.SpatialReference() wgs84.ImportFromProj4(epsg_from) # Create new raster mem_drv = gdal.GetDriverByName('MEM') dest1 = mem_drv.Create('', X_raster_size, Y_raster_size, 1, gdal.GDT_Float32) dest1.SetGeoTransform(Geo) dest1.SetProjection(osng.ExportToWkt()) # Perform the projection/resampling if method == 1: gdal.ReprojectImage(g_in, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(), gdal.GRA_NearestNeighbour) if method == 2: gdal.ReprojectImage(g_in, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(), gdal.GRA_Average) if method == 3: gdal.ReprojectImage(g_in, dest1, wgs84.ExportToWkt(), osng.ExportToWkt(), gdal.GRA_Cubic) return (dest1, ulx, lry, lrx, uly, epsg_to)
def reproject(driver, out_file, in_image, in_proj, ref_image, ref_trans, ref_trans_new, ref_proj): """Reproject and resample a band intended resolution. :param driver: Driver determining the format of the written file :param out_file: Path to the temporary file where the resampled band will be created :param in_image: Path to the original, not-resampled band :param in_proj: Projection of in_image :param ref_image: A GDAL object representing the reference image :param ref_trans: Geo transform (transformation coefficients) of the reference image :param ref_trans_new: Geo transform of the reference image, where the resolution is changed to the intended one :param ref_proj: Projection of ref_image """ from osgeo import gdal, gdalconst x = ref_image.RasterXSize y = ref_image.RasterYSize data_type = ref_image.GetRasterBand(1).DataType rand_file = tempfile.mkstemp(prefix='resampled_5m_', suffix='.tif')[1] ref_trans_list = list(ref_trans_new) ref_trans_list[1] = 5 ref_trans_list[5] = -5 ref_trans_5m = tuple(ref_trans_list) x_5m = int(x * ref_trans[1] / 5) y_5m = int(y * ref_trans[5] / -5) output_5m = driver.Create(rand_file, x_5m, y_5m, 1, data_type) output_5m.SetGeoTransform(ref_trans_5m) output_5m.SetProjection(ref_proj) gdal.ReprojectImage(in_image, output_5m, in_proj, ref_proj, gdalconst.GRA_NearestNeighbour) # resample from 5 m to the intended resolution x_target = int(x * ref_trans[1] / ref_trans_new[1]) y_target = int(y * ref_trans[5] / ref_trans_new[5]) output = driver.Create(out_file, x_target, y_target, 1, data_type) output.SetGeoTransform(ref_trans_new) output.SetProjection(ref_proj) gdal.ReprojectImage(output_5m, output, in_proj, ref_proj, gdalconst.GRA_NearestNeighbour) output_5m = None output = None # delete temporary files with single resampled bands into a 5 m res os.remove(rand_file)
def resample_and_reproject(image_in, dim, out_geo_transform, out_proj=None, mode='lanczos'): """ Resample and reproject a raster :param image_in: input raster :param dim: output dimensions (width, height) :param out_geo_transform: GeoTransform of the output raster :param out_proj: output projection (default to input projection) :param mode: interpolation mode ['bicubic', 'average', 'bilinear', 'lanczos' (default) or 'nearest'] :type image_in: ``ogr.DataSet`` :type dim: tuple of int :type out_geo_transform: tuple of floats :type out_proj: string (ex : 'EPSG:4326') :type mode: string :return: the reprojected and resampled raster, None otherwise :rtype: ` `gdal.DataSet`` """ if isinstance(image_in, str): image_in = gdal.Open(image_in) in_proj = image_in.GetProjection() out_raster = gdal.GetDriverByName('MEM').Create( "", dim[0], dim[1], image_in.RasterCount, image_in.GetRasterBand(1).DataType) out_raster.SetGeoTransform(out_geo_transform) mode_gdal = gdal.GRA_Lanczos if mode.lower() == 'average': mode_gdal = gdal.GRA_Average elif mode.lower() == 'bilinear': mode_gdal = gdal.GRA_Bilinear elif mode.lower() == 'bicubic': mode_gdal = gdal.GRA_Cubic elif mode.lower() == 'nearest': mode_gdal = gdal.GRA_NearestNeighbour reproj_res = None if out_proj is None: out_raster.SetProjection(in_proj) reproj_res = gdal.ReprojectImage(image_in, out_raster, None, None, mode_gdal) else: out_raster.SetProjection(out_proj) reproj_res = gdal.ReprojectImage(image_in, out_raster, in_proj, out_proj, mode_gdal) if reproj_res != 0: logging.error(" Error of reprojection/resampled") return None return out_raster
def reproject_dataset_res(dataset, res, method=1): try: if isinstance(dataset, str): g_in = gdal.Open(dataset) else: g_in = dataset except: g_in = dataset epsg_from = get_projection(g_in) Geo = g_in.GetGeoTransform() X_raster_size = g_in.RasterXSize Y_raster_size = g_in.RasterYSize ulx = Geo[0] uly = Geo[3] lrx = ulx + X_raster_size * Geo[1] lry = uly + Y_raster_size * Geo[5] X_raster_size = int(np.round((lrx - ulx) / res)) Y_raster_size = int(np.round((uly - lry) / res)) Geo = list(Geo) Geo[1] = res Geo[5] = -res Geo = tuple(Geo) # Set the EPSG codes wgs84 = osr.SpatialReference() wgs84.ImportFromProj4(epsg_from) # Create new raster mem_drv = gdal.GetDriverByName("MEM") dest1 = mem_drv.Create('', X_raster_size, Y_raster_size, 1, gdal.GDT_Float32) dest1.SetGeoTransform(Geo) dest1.SetProjection(wgs84.ExportToWkt()) # Perform the projection/resampling if method == 1: gdal.ReprojectImage(g_in, dest1, wgs84.ExportToWkt(), wgs84.ExportToWkt(), gdal.GRA_NearestNeighbour) elif method == 2: gdal.ReprojectImage(g_in, dest1, wgs84.ExportToWkt(), wgs84.ExportToWkt(), gdal.GRA_Average) elif method == 3: gdal.ReprojectImage(g_in, dest1, wgs84.ExportToWkt(), wgs84.ExportToWkt(), gdal.GRA_Cubic) else: print('method is None') return dest1, Geo, wgs84.ExportToWkt()
def project_and_resample_Array(input_array, srs_geotrs, srs_proj, Nxin, Nyin, reference_netcdf): #, output_array): #srs_data = gdal.Open(input_raster, GA_ReadOnly) #srs_proj = srs_data.GetProjection() #osr.SpatialReference(wkt srs_data = gdal.GetDriverByName('MEM').Create('', Nxin, Nyin, 1, gdal.GDT_Float32) srs_data.SetGeoTransform(srs_geotrs) srs_data.SetProjection(srs_proj) srsband = srs_data.GetRasterBand(1) srsband.WriteArray(input_array) srsband.FlushCache() ref_data = gdal.Open(reference_netcdf, GA_ReadOnly) ref_proj = ref_data.GetProjection() ref_geotrs = ref_data.GetGeoTransform() Ncols = ref_data.RasterXSize Nrows = ref_data.RasterYSize ref_data = None out_data = gdal.GetDriverByName('MEM').Create('', Ncols, Nrows, 1, gdal.GDT_Float32) out_data.SetGeoTransform(ref_geotrs) out_data.SetProjection(ref_proj) gdal.ReprojectImage(srs_data, out_data, srs_proj, ref_proj, gdal.GRA_Bilinear) output_array = out_data.ReadAsArray() srs_data = None out_data = None return output_array
def gridmatch(lmod, ctxt, rtxt): """ Matches the rows and columns of the second grid to the first grid """ rgrv = lmod.griddata[rtxt] cgrv = lmod.griddata[ctxt] data = rgrv data2 = cgrv orig_wkt = data.wkt orig_wkt2 = data2.wkt doffset = 0.0 if data.data.min() <= 0: doffset = data.data.min()-1. data.data = data.data - doffset gtr0 = (data.tlx, data.xdim, 0.0, data.tly, 0.0, -data.ydim) gtr = (data2.tlx, data2.xdim, 0.0, data2.tly, 0.0, -data2.ydim) src = data_to_gdal_mem(data, gtr0, orig_wkt, data.cols, data.rows) dest = data_to_gdal_mem(data, gtr, orig_wkt2, data2.cols, data2.rows, True) gdal.ReprojectImage(src, dest, orig_wkt, orig_wkt2, gdal.GRA_Bilinear) dat = gdal_to_dat(dest, data.dataid) if doffset != 0.0: dat.data = dat.data + doffset data.data = data.data + doffset return dat.data
def reproject(driver, out_file, in_image, in_proj, ref_image, ref_trans, ref_trans_new, ref_proj): """Reproject and resample a band intended resolution. :param driver: Driver determining the format of the written file :param out_file: Path to the temporary file where the resampled band will be created :param in_image: Path to the original, not-resampled band :param in_proj: Projection of in_image :param ref_image: A GDAL object representing the reference image :param ref_trans: Geo transform (transformation coefficients) of the reference image :param ref_trans_new: Geo transform of the reference image, where the resolution is changed to the intended one :param ref_proj: Projection of ref_image """ from osgeo import gdal, gdalconst x = ref_image.RasterXSize y = ref_image.RasterYSize data_type = ref_image.GetRasterBand(1).DataType x_target = int(x * ref_trans[1] / ref_trans_new[1]) y_target = int(y * ref_trans[5] / ref_trans_new[5]) output = driver.Create(out_file, x_target, y_target, 1, data_type) output.SetGeoTransform(ref_trans_new) output.SetProjection(ref_proj) gdal.ReprojectImage(in_image, output, in_proj, ref_proj, gdalconst.GRA_NearestNeighbour) output = None
def subset_and_resample_Raster(input_raster, reference_raster, output_raster, driverName='GTiff'): #, output_array): srs_data = gdal.Open(input_raster, GA_ReadOnly) srs_proj = srs_data.GetProjection() #osr.SpatialReference(wkt srs_geotrs = srs_data.GetGeoTransform() ref_data = gdal.Open(reference_raster, GA_ReadOnly) ref_proj = ref_data.GetProjection() ref_geotrs = ref_data.GetGeoTransform() Ncols = ref_data.RasterXSize Nrows = ref_data.RasterYSize ref_data = None out_data = gdal.GetDriverByName(driverName).Create(output_raster, Ncols, Nrows, 1, gdal.GDT_Float32) out_data.SetGeoTransform(ref_geotrs) out_data.SetProjection(ref_proj) gdal.ReprojectImage(srs_data, out_data, ref_proj, ref_proj, gdal.GRA_Bilinear) srs_data = None out_data = None
def resample_raster_to_reference_raster(src_filename, match_filename, dst_filename, resampling_method, driver='GTiff'): from osgeo import gdal from osgeo import gdalconst src = gdal.Open(src_filename, gdalconst.GA_ReadOnly) src_proj = src.GetProjection() src_bands = src.RasterCount # 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() wide = match_ds.RasterXSize high = match_ds.RasterYSize # Output / destination dst = gdal.GetDriverByName(driver).Create(dst_filename, wide, high, src_bands, gdalconst.GDT_Float32) dst.SetGeoTransform(match_geotrans) dst.SetProjection(match_proj) # Do the work gdal.ReprojectImage(src, dst, src_proj, match_proj, resampling_method) del (dst)
def reprojectXarray(self, array: xr.DataArray, resolution: float): xcoord = array.coords[array.dims[-1]] ycoord = array.coords[array.dims[-2]] longitude_location: float = (xcoord.values[0] + xcoord.values[-1]) / 2.0 dest_crs = CRS.get_utm_crs(longitude_location) xbounds = [xcoord.values[0], xcoord.values[-1]] ybounds = [ycoord.values[0], ycoord.values[-1]] srcSRS = self.getSpatialReference(array.crs) dstSRS = self.getSpatialReference(dest_crs) transformation = osr.CoordinateTransformation(srcSRS, dstSRS) (ulx, uly, ulz) = transformation.TransformPoint(xbounds[0], ybounds[0]) (lrx, lry, lrz) = transformation.TransformPoint(xbounds[1], ybounds[1]) out_dir, out_file = CRS.to_geotiff(array) g: gdal.Dataset = gdal.Open(os.path.join(out_dir, out_file)) mem_drv = gdal.GetDriverByName('MEM') nx = int((lrx - ulx) / resolution) ny = int((uly - lry) / resolution) dest: gdal.Dataset = mem_drv.Create('', nx, ny, 1, gdal.GDT_Float32) new_geo = (ulx, resolution, 0.0, uly, 0.0, -resolution) dest.SetGeoTransform(new_geo) dest.SetProjection(dstSRS.ExportToWkt()) res = gdal.ReprojectImage(g, dest, srcSRS.ExportToWkt(), dstSRS.ExportToWkt(), gdal.GRA_Bilinear) gArray = dest.ReadAsArray() return gArray
def reproject(source_path, match_path, out_path ): # Source src_filename = real_path + source_path 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 = real_path + match_path 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 = real_path + out_path dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, 1, gdalconst.GDT_Float32) dst.SetGeoTransform(match_geotrans) dst.SetProjection( match_proj) # Do the work gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_Bilinear) del dst # Flush
def gdal_reprojectimage(source_dataset, target_dataset, source_projection, target_projection, resampling): """ Reproject an image onto the model grid. Todo: * Add a timeout here that if the gdal command takes too long to run (ie. it freezes) that our whole server does not get unresponsive. Under some weird circumstances gdal.ReprojectImage or rasterize can do this. For timeout see http://stackoverflow.com/questions/2281850/timeout-function-if-it-takes-too-long-to-finish """ logger.debug( "Reprojecting dataset using gdal.ReprojectImage(). Timeout is set to 10 seconds." ) logger.debug("Input dataset is %d by %d pixels" % (source_dataset.RasterXSize, source_dataset.RasterYSize)) logger.debug("Input projection: %s" % (source_dataset.GetProjection())) logger.debug("Output dataset is %d by %d pixels" % (target_dataset.RasterXSize, target_dataset.RasterYSize)) logger.debug("Output projection: %s" % (target_dataset.GetProjection())) gdal.ReprojectImage(source_dataset, target_dataset, source_dataset.GetProjection(), target_dataset.GetProjection(), resampling) band = target_dataset.GetRasterBand(1) dt = np.dtype(np.float32) if gdal.GetDataTypeName(band.DataType) in ('Int32', 'Int16', 'Byte'): dt = np.dtype(np.int32) data = np.array(band.ReadAsArray(), dtype=dt) source_dataset = None target_dataset = None return data
def gdal_average(dst_ds, src_ds, src_ds_mem, thresh): """ Perform subsampling of an image by averaging values :param gdal.Dataset dst_ds: Destination gdal dataset object :param str input_tif: Input geotif :param float thresh: NaN fraction threshold :return resampled_average: resampled image data :rtype: ndarray :return src_ds_mem: Modified in memory src_ds with nan_fraction in Band2. The nan_fraction is computed efficiently here in gdal in the same step as the that of the resampled average (band 1). This results is huge memory and computational efficiency :rtype: gdal.Dataset """ src_gt = src_ds.GetGeoTransform() src_ds_mem.SetGeoTransform(src_gt) data = src_ds_mem.GetRasterBand(1).ReadAsArray() # update nan_matrix # if data==nan, then 1, else 0 nan_matrix = np.isnan( data) # all nans due to phase data + coh masking if used src_ds_mem.GetRasterBand(2).WriteArray(nan_matrix) gdal.ReprojectImage(src_ds_mem, dst_ds, '', '', gdal.GRA_Average) # dst_ds band2 average is our nan_fraction matrix nan_frac = dst_ds.GetRasterBand(2).ReadAsArray() resampled_average = dst_ds.GetRasterBand(1).ReadAsArray() resampled_average[nan_frac >= thresh] = np.nan return resampled_average, src_ds_mem
def resample(filename,source_to_match): from osgeo import gdal, gdalconst # Source src_filename = filename 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 = source_to_match 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 = filename[:-4] + '-resampled.tif' dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, 1, gdalconst.GDT_Float32) dst.SetGeoTransform( match_geotrans ) dst.SetProjection( match_proj) # Do the work gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_NearestNeighbour) del dst # Flush
def resample_img(self, in_file, out_file, resolution=100): """Resample image file to given resolution. :param str in_file: input raster name :param str out_file: output raster name :param int resolution : target resolution for resampling """ input = gdal.Open(in_file, gdalconst.GA_ReadOnly) inputProj = input.GetProjection() inputTrans = input.GetGeoTransform() nbands = input.RasterCount bandreference = input.GetRasterBand(1) # adjust raster metadata x = int(np.round(input.RasterXSize / (resolution / inputTrans[1]), 0)) y = int(np.round(input.RasterYSize / (resolution / inputTrans[1]), 0)) targetTrans = (inputTrans[0], float(resolution), inputTrans[2], inputTrans[3], inputTrans[4], float(-resolution)) driver = gdal.GetDriverByName('GTiff') output = driver.Create(out_file, x, y, nbands, bandreference.DataType) output.SetGeoTransform(targetTrans) output.SetProjection(inputProj) gdal.ReprojectImage(input, output, inputProj, inputProj, gdalconst.GRA_Bilinear) del output del input
def reproject_tiff_from_model(old_name, new_name, model, unit): """ Reprojects an tiff on a tiff model. Can be used to warp tiff. Keyword arguments: old_name -- the name of the old tiff file new_name -- the name of the output tiff file model -- the gdal dataset which will be used to warp the tiff unit -- the gdal unit in which the operation will be performed """ mem_drv = gdal.GetDriverByName("MEM") old = gdal.Open(old_name) new = mem_drv.Create(new_name, model.RasterXSize, model.RasterYSize, 1, unit) new.SetGeoTransform(model.GetGeoTransform()) new.SetProjection(model.GetProjection()) res = gdal.ReprojectImage(old, new, old.GetProjection(), model.GetProjection(), gdal.GRA_NearestNeighbour) assert res == 0, 'Error in ReprojectImage' arr = new.ReadAsArray() new = None return arr
def resample_swir_gdal(vnir_fn: str, swir_fn: str, order: int): if order == 0: # order 0 = nearest neighbour upsample = gdalconst.GRA_NearestNeighbour elif order == 1: # order 1 = bilinear upsample = gdalconst.GRA_Bilinear swirfile = gdal.Open(swir_fn) vnirfile = gdal.Open(vnir_fn) swir_proj = swirfile.GetProjection() vnir_proj = vnirfile.GetProjection() swir_trans = swirfile.GetGeoTransform() vnir_trans = vnirfile.GetGeoTransform() vnir_band = vnirfile.GetRasterBand(1) x_vnir = vnirfile.RasterXSize y_vnir = vnirfile.RasterYSize tile_id = re.search(r"SWIR_(.*)\.tif", swir_fn).group(1) outfile = f'temp/SWIR_{tile_id}' driver = gdal.GetDriverByName('GTiff') output = driver.Create(outfile, x_vnir, y_vnir, 288, vnir_band.DataType) output.SetGeoTransform(vnir_trans) output.SetProjection(vnir_proj) gdal.ReprojectImage(swirfile, output, swir_proj, vnir_proj, upsample) # close and remove unneeded files del outfile del swirfile del vnirfile os.remove(swir_fn) return
def test_reproject_average_resampling_with_2bands(self): data = np.array( [[[4, 7, 7, 7, 2, 7.], [4, 7, 7, 7, 2, 7.], [4, 7, 7, 7, 2, 7.], [4, 7, 7, 2, 2, 7.], [4, 7, 7, 2, 2, 7.], [4, 7, 7, 10, 2, 7.]], [[2, 0, 0, 0, 0, 0.], [2, 0, 0, 0, 0, 2.], [0, 1., 0, 0, 0, 1.], [0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0.], [0, 0, 0, 0, 0, 0.]]], dtype=np.float32) src_ds = gdal.GetDriverByName('MEM').Create('', 6, 6, 2, gdalconst.GDT_Float32) src_ds.GetRasterBand(1).WriteArray(data[0, :, :]) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.GetRasterBand(2).WriteArray(data[1, :, :]) # src_ds.GetRasterBand(1).SetNoDataValue() src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) dst_ds = gdal.GetDriverByName('MEM').Create('', 3, 3, 2, gdalconst.GDT_Float32) dst_ds.GetRasterBand(1).SetNoDataValue(3) dst_ds.GetRasterBand(1).Fill(3) dst_ds.SetGeoTransform([10, 2, 0, 10, 0, -2]) gdal.ReprojectImage(src_ds, dst_ds, '', '', gdal.GRA_Average) got_data = dst_ds.GetRasterBand(1).ReadAsArray() expected_data = np.array([[5.5, 7, 7], [5.5, 7, 7], [5.5, 8, 7]]) np.testing.assert_array_equal(got_data, expected_data) band2 = dst_ds.GetRasterBand(2).ReadAsArray() np.testing.assert_array_equal( band2, np.array([[1., 0., 0.5], [0.25, 0., 0.75], [0., 0., 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 check(driver_type): temp_tif = tempfile.mktemp(suffix='.tif') data = np.array( [[[4, 7, 7, 7, 2, 7.], [4, 7, 7, 7, 2, 7.], [4, 7, 7, 7, 2, 7.], [4, 7, 7, 2, 2, 7.], [4, 7, 7, 2, 2, 7.], [4, 7, 7, 10, 2, 7.]], [[2, 0, 0, 0, 0, 0.], [2, 0, 0, 0, 0, 2.], [0, 1., 0, 0, 0, 1.], [0, 0, 0, 0, 0, 2], [0, 0, 0, 0, 0, 0.], [0, 0, 0, 0, 0, 0.]]], dtype=np.float32) src_ds = gdal.GetDriverByName(driver_type).Create( temp_tif, 6, 6, 2, gdalconst.GDT_Float32) src_ds.GetRasterBand(1).WriteArray(data[0, :, :]) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.GetRasterBand(2).WriteArray(data[1, :, :]) src_ds.GetRasterBand(2).SetNoDataValue(3) src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) src_ds.FlushCache() dst_ds = gdal.GetDriverByName('MEM').Create('', 3, 3, 2, gdalconst.GDT_Float32) dst_ds.GetRasterBand(1).SetNoDataValue(3) dst_ds.GetRasterBand(1).Fill(3) dst_ds.SetGeoTransform([10, 2, 0, 10, 0, -2]) gdal.ReprojectImage(src_ds, dst_ds, '', '', gdal.GRA_Average) band1 = dst_ds.GetRasterBand(1).ReadAsArray() np.testing.assert_array_equal( band1, np.array([[5.5, 7, 7], [5.5, 7, 7], [5.5, 8, 7]])) band2 = dst_ds.GetRasterBand(2).ReadAsArray() np.testing.assert_array_equal( band2, np.array([[1., 0., 0.5], [0.25, 0., 0.75], [0., 0., 0.]])) if os.path.exists(temp_tif): os.remove(temp_tif)
def main(pan, mss, out): pan_ds = gdal.Open(pan) pan_xsize = pan_ds.RasterXSize pan_ysize = pan_ds.RasterYSize mss_ds = gdal.Open(mss) mss_prj = mss_ds.GetProjection() mss_geo = mss_ds.GetGeoTransform() mss_xsize = mss_ds.RasterXSize mss_ysize = mss_ds.RasterYSize bandCount = mss_ds.RasterCount # Band Count dataType = mss_ds.GetRasterBand(1).DataType # Data Type # 计算输出后影像的分辨率 # 计算缩放系数 fact = np.array([pan_xsize / mss_xsize, pan_ysize / mss_ysize]) xs = mss_geo[1] / fact[0] ys = mss_geo[5] / fact[1] # 创建输出影像 out_driver = gdal.GetDriverByName("GTiff") out_ds = out_driver.Create(out, pan_xsize, pan_ysize, bandCount, dataType) out_ds.SetProjection(mss_prj) out_geo = list(mss_geo) out_geo[1] = xs out_geo[5] = ys out_ds.SetGeoTransform(out_geo) # 执行重投影和重采样 print('Begin to reprojection and resample!') res = gdal.ReprojectImage(mss_ds, out_ds, \ mss_prj, mss_prj, \ gdal.GRA_Bilinear, callback=progress) out_ds.FlushCache() pan_ds = None mss_ds = None out_ds = None return 1
def main(indir, example_file, outdir): files = searchfile(indir, '.tif') if files == []: files = searchfile(indir, '.dat') if files == []: sys.exit('there is no data ') dataset1 = gdal.Open(example_file) im_width1 = dataset1.RasterXSize im_height1 = dataset1.RasterYSize im_proj1 = dataset1.GetProjection() im_Geotransform1 = dataset1.GetGeoTransform() for file in files: dataset = gdal.Open(file) im_width = dataset.RasterXSize im_height = dataset.RasterYSize im_proj = dataset.GetProjection() im_Geotransform = dataset.GetGeoTransform() dtype = dataset.GetRasterBand(1).DataType im_data = dataset.ReadAsArray(0, 0, im_width, im_height) outname = os.path.split(file)[1] outfile = os.path.join(outdir, outname) # output envi file dst = gdal.GetDriverByName('GTiff').Create(outfile, im_width1, im_height1, 1, dtype) dst.SetGeoTransform(im_Geotransform1) dst.SetProjection(im_proj1) gdal.ReprojectImage(dataset, dst, im_proj, im_proj, gdalconst.GRA_Bilinear) dst = None
def test_reproject_2(): sr = osr.SpatialReference() sr.ImportFromEPSG(32611) sr2 = osr.SpatialReference() sr2.ImportFromEPSG(4326) drv = gdal.GetDriverByName('GTiff') src_ds = gdal.Open('../gcore/data/byte.tif') dst_ds = drv.Create('tmp/byte_4326.tif', 22, 18, gdal.GDT_Byte) dst_ds.SetGeoTransform([ -117.641169915168746, 0.000598105625684, 0, 33.900668703925191, 0, -0.000598105625684 ]) gdal.ReprojectImage(src_ds, dst_ds, sr.ExportToWkt(), sr2.ExportToWkt()) cs_expected = 4727 cs = dst_ds.GetRasterBand(1).Checksum() dst_ds = None drv.Delete('tmp/byte_4326.tif') if cs != cs_expected: print('Got: ', cs) pytest.fail('got wrong checksum')
def main(): # Open raster. class_ids = [1, 2, 4, 5, 6, 7] multispectralToBits(data_path + in_raster, class_ids) src_ds = gdal.Open('bit_raster.tif') # Open a template or copy array, for dimensions and NODATA mask. cpy_ds = gdal.Open(data_path + '1.2_avg_tree_height.tif') band = cpy_ds.GetRasterBand(1) cpy_mask = (band.ReadAsArray() == band.GetNoDataValue()) # Result raster, with same resolution and position as the copy raster. drv = gdal.GetDriverByName('GTiff') dst_ds = drv.Create(data_path + out_raster, cpy_ds.RasterXSize, cpy_ds.RasterYSize, len(class_ids), gdal.GDT_Float32, ['INTERLEAVE=BAND']) dst_ds.SetGeoTransform(cpy_ds.GetGeoTransform()) dst_ds.SetProjection(cpy_ds.GetProjection()) # Do the same as gdalwarp -r average; this might take a while to finish. gdal.ReprojectImage(src_ds, dst_ds, None, None, gdal.GRA_Average) # Convert all fractions to percent, and apply the same NODATA mask from the copy raster. NODATA = 0 for bidx in range(dst_ds.RasterCount): band = dst_ds.GetRasterBand(bidx + 1) ar = band.ReadAsArray() * 100.0 ar[cpy_mask] = NODATA band.WriteArray(ar) band.SetNoDataValue(NODATA) # Save and close all rasters src_ds = cpy_ds = dst_ds = band = None
def resize_tif(pan_ds, mss_ds, GS_mss_resize_path): # 打开高分辨率影像 pan_geo = pan_ds.GetGeoTransform() # 打开低分辨率影像 mss_prj = mss_ds.GetProjection() mss_geo = mss_ds.GetGeoTransform() mss_xsize = mss_ds.RasterXSize mss_ysize = mss_ds.RasterYSize bandCount = mss_ds.RasterCount # Band Count dataType = mss_ds.GetRasterBand(1).DataType # Data Type # 判断输入影像是否正确 if pan_geo[1] > mss_geo[1]: sys.exit("The order of input files is wrongT!") # 计算输出后影像的分辨率 fact = np.array([pan_geo[1] / mss_geo[1], pan_geo[5] / mss_geo[5]]) new_xsize = math.ceil(mss_xsize / fact[0]) new_ysize = math.ceil(mss_ysize / fact[1]) # 创建输出影像 out_driver = gdal.GetDriverByName("GTiff") out_ds = out_driver.Create(GS_mss_resize_path, new_xsize, new_ysize, bandCount, dataType) out_ds.SetProjection(mss_prj) out_geo = list(mss_geo) out_geo[1] = pan_geo[1] out_geo[5] = pan_geo[5] out_ds.SetGeoTransform(out_geo) # 执行重投影和重采样 print('Begin to reprojection and resample!', flush=True) res = gdal.ReprojectImage(mss_ds, out_ds, \ mss_prj, mss_prj, \ gdal.GRA_NearestNeighbour, callback=progress) out_ds = None return None
def intermediaryReprojection(sourceRaster, templateRaster, outRasterFName, resamplingType, matchTemplateCellSize=False): '''Reprojects the sourceRaster into the templateRaster projection, datum and extent. The output cell size is determined to be the closest dimension to the sourceRaster cell size that will evenly go into the template raster cell size ''' outputFile = SAHMRaster(outRasterFName) outputFile.getParams(templateRaster.ds) outputFile.gt = templateRaster.gt outputFile.width = templateRaster.width outputFile.height = templateRaster.height outputFile.west = templateRaster.west outputFile.north = templateRaster.north outputFile.east = templateRaster.east outputFile.south = templateRaster.south outputFile.NoData = sourceRaster.NoData outputFile.pixelType = sourceRaster.pixelType outputFile.signedByte = sourceRaster.signedByte if matchTemplateCellSize: targetCellSize, numSourcePerTarget = (templateRaster.xScale, 1) else: targetCellSize, numSourcePerTarget = getAggregateTargetCellSize(sourceRaster, templateRaster) outputFile.xScale = targetCellSize outputFile.yScale = -1 * targetCellSize outputFile.height = templateRaster.height * int(templateRaster.xScale / targetCellSize) outputFile.width = templateRaster.width * int(templateRaster.xScale / targetCellSize) outputFile.createNewRaster() err = gdal.ReprojectImage(sourceRaster.ds, outputFile.ds, sourceRaster.srs.ExportToWkt(), templateRaster.srs.ExportToWkt(), resamplingType)
def _resampleSM(sm_interp, tile, geo_t, interpolation='avearge'): ''' ''' # Create output file matching ALOS tile gdal_driver = gdal.GetDriverByName('MEM') ds_source = gdal_driver.Create('', sm_interp.shape[0], sm_interp.shape[1], 1, gdal.GDT_Float32) ds_source.SetGeoTransform(geo_t) ds_source.SetProjection(tile.proj) ds_source.GetRasterBand(1).SetNoDataValue(-9999) ds_source.GetRasterBand(1).WriteArray(sm_interp) ds_dest = gdal_driver.Create('', tile.ySize, tile.xSize, 1, gdal.GDT_Float32) ds_dest.SetGeoTransform(tile.geo_t) ds_dest.SetProjection(tile.proj) # Select interpolation type if interpolation == 'average' or interpolation == 'nearest': interp_type = gdal.GRA_NearestNeighbour elif interpolation == 'cubic': interp_type = gdal.GRA_CubicSpline # Reproject input GeoTiff to match the ALOS tile gdal.ReprojectImage(ds_source, ds_dest, tile.proj, tile.proj, interp_type) # Load resampled image into memory sm_resampled = ds_dest.GetRasterBand(1).ReadAsArray() return np.ma.array(sm_resampled, mask=sm_resampled == -9999.)
def createPyramidTile(levelMosaicInfo, offsetX, offsetY, width, height, tileName, OGRDS): sx = levelMosaicInfo.scaleX * 2 sy = levelMosaicInfo.scaleY * 2 dec = AffineTransformDecorator([ levelMosaicInfo.ulx + offsetX * sx, sx, 0, levelMosaicInfo.uly + offsetY * sy, 0, sy ]) s_fh = levelMosaicInfo.getDataSet(dec.ulx, dec.uly + height * dec.scaleY, dec.ulx + width * dec.scaleX, dec.uly) if s_fh is None: return if OGRDS is not None: points = dec.pointsFor(width, height) addFeature(OGRDS, tileName, points[0], points[1]) if BandType is None: bt = levelMosaicInfo.band_type else: bt = BandType geotransform = [dec.ulx, dec.scaleX, 0, dec.uly, 0, dec.scaleY] bands = levelMosaicInfo.bands if MemDriver is None: t_fh = Driver.Create(tileName, width, height, bands, bt, CreateOptions) else: t_fh = MemDriver.Create(tileName, width, height, bands, bt) if t_fh is None: print('Creation failed, terminating gdal_tile.') sys.exit(1) t_fh.SetGeoTransform(geotransform) t_fh.SetProjection(levelMosaicInfo.projection) for band in range(1, bands + 1): t_band = t_fh.GetRasterBand(band) if levelMosaicInfo.ct is not None: t_band.SetRasterColorTable(levelMosaicInfo.ct) t_band.SetRasterColorInterpretation(levelMosaicInfo.ci[band - 1]) res = gdal.ReprojectImage(s_fh, t_fh, None, None, ResamplingMethod) if res != 0: print("Reprojection failed for %s, error %d" % (tileName, res)) sys.exit(1) levelMosaicInfo.closeDataSet(s_fh) if MemDriver is not None: tt_fh = Driver.CreateCopy(tileName, t_fh, 0, CreateOptions) tt_fh.FlushCache() if Verbose: print(tileName + " : " + str(offsetX) + "|" + str(offsetY) + "-->" + str(width) + "-" + str(height))
def reproject_1(): try: x = gdal.ReprojectImage except: return 'skip' drv = gdal.GetDriverByName('GTiff') src_ds = gdal.Open('../gcore/data/byte.tif') dst_ds = drv.Create('tmp/byte.tif', src_ds.RasterXSize, src_ds.RasterYSize, gdal.GDT_Byte) dst_ds.SetProjection(src_ds.GetProjectionRef()) dst_ds.SetGeoTransform(src_ds.GetGeoTransform()) gdal.ReprojectImage(src_ds, dst_ds) cs_expected = src_ds.GetRasterBand(1).Checksum() cs = dst_ds.GetRasterBand(1).Checksum() dst_ds = None drv.Delete('tmp/byte.tif') if cs != cs_expected: print('Got: ', cs) gdaltest.post_reason('got wrong checksum') return 'fail' else: return 'success'