Python osgeo.gdal.ReprojectImage() Examples
The following are 19
code examples of osgeo.gdal.ReprojectImage().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
osgeo.gdal
, or try the search function
.
Example #1
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 6 votes |
def test_reproject_with_no_data_5(self): data = np.array([[2, 7, 7, 7, 2], [2, 7, 7, 7, 2], [2, 7, 7, 7, 2], [2, 7, 7, 2, 2], [2, 7, 7, 2, 2], [2, 7, 7, 2, 2]]) src_ds = gdal.GetDriverByName('MEM').Create('', 5, 6) src_ds.GetRasterBand(1).WriteArray(data) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) dst_ds = gdal.GetDriverByName('MEM').Create('', 2, 3) 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_NearestNeighbour) got_data = dst_ds.GetRasterBand(1).ReadAsArray() expected_data = np.array([[7, 7], [7, 3], [7, 3]]) np.testing.assert_array_equal(got_data, expected_data)
Example #2
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 6 votes |
def test_reproject_with_no_data_4(self): data = np.array([[2, 7, 7, 7, 2], [2, 7, 7, 7, 2], [2, 7, 7, 7, 2], [2, 7, 7, 2, 2], [2, 7, 7, 2, 2]]) src_ds = gdal.GetDriverByName('MEM').Create('', 5, 5) src_ds.GetRasterBand(1).WriteArray(data) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) dst_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) 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_NearestNeighbour) got_data = dst_ds.GetRasterBand(1).ReadAsArray() expected_data = np.array([[7, 7], [7, 3]]) np.testing.assert_array_equal(got_data, expected_data)
Example #3
Source File: gdal2cesium.py From gdal2cesium with GNU General Public License v2.0 | 6 votes |
def scale_query_to_tile(self, dsquery, dstile): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if self.options.resampling == 'average': for i in range(1,tilebands+1): res = gdal.RegenerateOverview( dsquery.GetRasterBand(i), dstile.GetRasterBand(i), 'average' ) if res != 0: self.error("RegenerateOverview() failed") else: # Other algorithms are implemented by gdal.ReprojectImage(). dsquery.SetGeoTransform( (0.0, tilesize / float(querysize), 0.0, 0.0, 0.0, tilesize / float(querysize)) ) dstile.SetGeoTransform( (0.0, 1.0, 0.0, 0.0, 0.0, 1.0) ) res = gdal.ReprojectImage(dsquery, dstile, None, None, self.resampling) if res != 0: self.error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
Example #4
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 6 votes |
def test_reproject_with_no_data_2(self): data = np.array([[2, 7, 7, 7], [2, 7, 7, 2]]) height, width = data.shape src_ds = gdal.GetDriverByName('MEM').Create('', width, height) src_ds.GetRasterBand(1).WriteArray(data) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) dst_ds = gdal.GetDriverByName('MEM').Create('', 2, 1) 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_NearestNeighbour) got_data = dst_ds.GetRasterBand(1).ReadAsArray() expected_data = np.array([[7, 3]]) np.testing.assert_array_equal(got_data, expected_data)
Example #5
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 6 votes |
def test_reproject_with_no_data(self): data = np.array([[2, 7], [2, 7]]) src_ds = gdal.GetDriverByName('MEM').Create('', 2, 2) src_ds.GetRasterBand(1).WriteArray(data) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) dst_ds = gdal.GetDriverByName('MEM').Create('', 1, 1) 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_NearestNeighbour) got_data = dst_ds.GetRasterBand(1).ReadAsArray() expected_data = np.array([[7]]) np.testing.assert_array_equal(got_data, expected_data)
Example #6
Source File: gdal_python.py From PyRate with Apache License 2.0 | 6 votes |
def resample_nearest_neighbour(input_tif, extents, new_res, output_file): """ Nearest neighbor resampling and cropping of an image. :param str input_tif: input geotiff file path :param list extents: new extents for cropping :param list[float] new_res: new resolution for resampling :param str output_file: output geotiff file path :return: dst: resampled image :rtype: ndarray """ dst, resampled_proj, src, _ = _crop_resample_setup(extents, input_tif, new_res, output_file) # Do the work gdal.ReprojectImage(src, dst, '', resampled_proj, gdalconst.GRA_NearestNeighbour) return dst.ReadAsArray()
Example #7
Source File: gdal_python.py From PyRate with Apache License 2.0 | 6 votes |
def _alignment(input_tif, new_res, resampled_average, src_ds_mem, src_gt, tmp_ds): """ Correction step to match python multi-look/crop output to match that of Legacy data. Modifies the resampled_average array in place. """ src_ds = gdal.Open(input_tif) data = src_ds.GetRasterBand(1).ReadAsArray() xlooks = ylooks = int(new_res[0] / src_gt[1]) xres, yres = _get_resampled_data_size(xlooks, ylooks, data) nrows, ncols = resampled_average.shape # Legacy nearest neighbor resampling for the last # [yres:nrows, xres:ncols] cells without nan_conversion # turn off nan-conversion src_ds_mem.GetRasterBand(1).SetNoDataValue(LOW_FLOAT32) # nearest neighbor resapling gdal.ReprojectImage(src_ds_mem, tmp_ds, '', '', gdal.GRA_NearestNeighbour) # only take the [yres:nrows, xres:ncols] slice if nrows > yres or ncols > xres: resampled_nearest_neighbor = tmp_ds.GetRasterBand(1).ReadAsArray() resampled_average[yres - nrows:, xres - ncols:] = \ resampled_nearest_neighbor[yres - nrows:, xres - ncols:]
Example #8
Source File: base.py From geoio with MIT License | 5 votes |
def upsample_like_that(self, ext_img, method='bilinear', no_data_value=None): """Use gdal.ReprojectImage to upsample the object so that it looks like the geoio image object passed in as the ext_img argument. Method can be those listed in GeoImage.upsample. """ if ext_img.meta.resolution[0]>self.meta.resolution[0]: raise ValueError('The requested resolution is not at or higher ' 'than the base object. Use downsample or ' 'resample methods.') # Set up destination image in memory drv = gdal.GetDriverByName('MEM') dst = drv.Create('', ext_img.shape[2], ext_img.shape[1], ext_img.shape[0], ext_img.meta.gdal_dtype) dst.SetGeoTransform(ext_img.meta.geo_transform) dst.SetProjection(ext_img.meta.projection_string) if no_data_value is not None: blist = [x + 1 for x in range(ext_img.shape[0])] [dst.GetRasterBand(x).SetNoDataValue(no_data_value) for x in blist] # Run resample, pull data, and del the temp gdal object. data = self._upsample_from_gdalobj(self.get_gdal_obj(),dst,method) del dst return data
Example #9
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 5 votes |
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.]]))
Example #10
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 5 votes |
def test_reproject_average_resampling(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.]], dtype=np.float32) src_ds = gdal.GetDriverByName('MEM').Create('', 6, 6, 1, gdalconst.GDT_Float32) src_ds.GetRasterBand(1).WriteArray(data) src_ds.GetRasterBand(1).SetNoDataValue(2) src_ds.SetGeoTransform([10, 1, 0, 10, 0, -1]) dst_ds = gdal.GetDriverByName('MEM').Create('', 3, 3, 1, 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)
Example #11
Source File: gdal_python.py From PyRate with Apache License 2.0 | 5 votes |
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
Example #12
Source File: base.py From geoio with MIT License | 5 votes |
def _upsample_from_gdalobj(self,src,dst,method='bilinear'): """Hidden to run the actual reprojection gdal code that is called from two higher level methods.""" # Set reprojection method if isinstance(method,int): pass elif method == "nearest": method = gdal.GRA_NearestNeighbour elif method == "bilinear": method = gdal.GRA_Bilinear elif method == "cubic": method = gdal.GRA_Cubic elif method == "average": method = gdal.GRA_Average else: raise ValueError("requested method is not understood.") # Do the reprojection gdal.ReprojectImage(src, dst, self.meta.projection_string, dst.GetProjection(), method) # Return data and free the temp image. return dst.ReadAsArray()
Example #13
Source File: gdal2tiles_parallel.py From geopackage-python with GNU General Public License v3.0 | 4 votes |
def scale_query_to_tile(self, dsquery, dstile, tilefilename=''): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if self.options.resampling == 'average': # Function: gdal.RegenerateOverview() for i in range(1, tilebands + 1): # Black border around NODATA #if i != 4: # dsquery.GetRasterBand(i).SetNoDataValue(0) res = gdal.RegenerateOverview( dsquery.GetRasterBand(i), dstile.GetRasterBand(i), 'average') if res != 0: self.error("RegenerateOverview() failed on %s, error %d" % (tilefilename, res)) elif self.options.resampling == 'antialias': # Scaling by PIL (Python Imaging Library) - improved Lanczos array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8) for i in range(tilebands): array[:, :, i] = gdalarray.BandReadAsArray( dsquery.GetRasterBand(i + 1), 0, 0, querysize, querysize) im = Image.fromarray(array, 'RGBA') # Always four bands im1 = im.resize((tilesize, tilesize), Image.ANTIALIAS) if path.exists(tilefilename): im0 = Image.open(tilefilename) im1 = Image.composite(im1, im0, im1) im1.save(tilefilename, self.tiledriver) else: # Other algorithms are implemented by gdal.ReprojectImage(). dsquery.SetGeoTransform((0.0, tilesize / float(querysize), 0.0, 0.0, 0.0, tilesize / float(querysize))) dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0)) res = gdal.ReprojectImage(dsquery, dstile, None, None, self.resampling) if res != 0: self.error("ReprojectImage() failed on %s, error %d" % (tilefilename, res)) # -------------------------------------------------------------------------
Example #14
Source File: tilelayer.py From quickmapservices with GNU General Public License v2.0 | 4 votes |
def drawTilesOnTheFly(self, renderContext, tiles, sdx=1.0, sdy=1.0): if not hasGdal: msg = self.tr("Reprojection requires python-gdal") self.emitShowBarMessage(msg, QGisMessageBarLevel.Info, 2) return transform = renderContext.coordinateTransform() if not transform: return # create an image that has the same resolution as the tiles image = tiles.image() if self.grayscaleRender: QgsImageOperation.convertToGrayscale(image) if self.brigthness != LayerDefaultSettings.BRIGTNESS or self.contrast != LayerDefaultSettings.CONTRAST: QgsImageOperation.adjustBrightnessContrast(image, self.brigthness, self.contrast) # tile extent extent = tiles.extent() geotransform = [extent.xMinimum(), extent.width() / image.width(), 0, extent.yMaximum(), 0, -extent.height() / image.height()] driver = gdal.GetDriverByName("MEM") tile_ds = driver.Create("", image.width(), image.height(), 1, gdal.GDT_UInt32) tile_ds.SetProjection(str(transform.sourceCrs().toWkt())) tile_ds.SetGeoTransform(geotransform) # QImage to raster ba = image.bits().asstring(image.numBytes()) tile_ds.GetRasterBand(1).WriteRaster(0, 0, image.width(), image.height(), ba) # canvas extent m2p = renderContext.mapToPixel() viewport = renderContext.painter().viewport() width = viewport.width() height = viewport.height() extent = QgsRectangle(m2p.toMapCoordinatesF(0, 0), m2p.toMapCoordinatesF(width, height)) geotransform = [extent.xMinimum(), extent.width() / width, 0, extent.yMaximum(), 0, -extent.height() / height] canvas_ds = driver.Create("", width, height, 1, gdal.GDT_UInt32) canvas_ds.SetProjection(str(transform.destCRS().toWkt())) canvas_ds.SetGeoTransform(geotransform) # reproject image gdal.ReprojectImage(tile_ds, canvas_ds) # raster to QImage ba = canvas_ds.GetRasterBand(1).ReadRaster(0, 0, width, height) reprojected_image = QImage(ba, width, height, QImage.Format_ARGB32_Premultiplied) # draw the image on the map canvas rect = QRectF(QPointF(0, 0), QPointF(viewport.width() * sdx, viewport.height() * sdy)) renderContext.painter().drawImage(rect, reprojected_image)
Example #15
Source File: gdal2tiles.py From gdal2tiles with MIT License | 4 votes |
def scale_query_to_tile(dsquery, dstile, tiledriver, options, tilefilename=''): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if options.resampling == 'average': # Function: gdal.RegenerateOverview() for i in range(1, tilebands + 1): # Black border around NODATA res = gdal.RegenerateOverview(dsquery.GetRasterBand(i), dstile.GetRasterBand(i), 'average') if res != 0: exit_with_error("RegenerateOverview() failed on %s, error %d" % ( tilefilename, res)) elif options.resampling == 'antialias': # Scaling by PIL (Python Imaging Library) - improved Lanczos array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8) for i in range(tilebands): array[:, :, i] = gdalarray.BandReadAsArray(dsquery.GetRasterBand(i + 1), 0, 0, querysize, querysize) im = Image.fromarray(array, 'RGBA') # Always four bands im1 = im.resize((tilesize, tilesize), Image.ANTIALIAS) if os.path.exists(tilefilename): im0 = Image.open(tilefilename) im1 = Image.composite(im1, im0, im1) im1.save(tilefilename, tiledriver) else: if options.resampling == 'near': gdal_resampling = gdal.GRA_NearestNeighbour elif options.resampling == 'bilinear': gdal_resampling = gdal.GRA_Bilinear elif options.resampling == 'cubic': gdal_resampling = gdal.GRA_Cubic elif options.resampling == 'cubicspline': gdal_resampling = gdal.GRA_CubicSpline elif options.resampling == 'lanczos': gdal_resampling = gdal.GRA_Lanczos # Other algorithms are implemented by gdal.ReprojectImage(). dsquery.SetGeoTransform((0.0, tilesize / float(querysize), 0.0, 0.0, 0.0, tilesize / float(querysize))) dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0)) res = gdal.ReprojectImage(dsquery, dstile, None, None, gdal_resampling) if res != 0: exit_with_error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
Example #16
Source File: raster.py From wradlib with MIT License | 4 votes |
def get_raster_elevation(dataset, resample=None, **kwargs): """Return surface elevation corresponding to raster dataset The resampling algorithm is chosen based on scale ratio Parameters ---------- dataset : gdal.Dataset raster image with georeferencing (GeoTransform at least) resample : GDALResampleAlg If None the best algorithm is chosen based on scales. GRA_NearestNeighbour = 0, GRA_Bilinear = 1, GRA_Cubic = 2, GRA_CubicSpline = 3, GRA_Lanczos = 4, GRA_Average = 5, GRA_Mode = 6, GRA_Max = 8, GRA_Min = 9, GRA_Med = 10, GRA_Q1 = 11, GRA_Q3 = 12 kwargs : keyword arguments passed to wradlib.io.dem.get_strm() Returns ------- elevation : :class:`numpy:numpy.ndarray` Array of shape (rows, cols, 2) containing elevation """ extent = get_raster_extent(dataset) src_ds = wradlib.io.dem.get_srtm(extent, **kwargs) driver = gdal.GetDriverByName("MEM") dst_ds = driver.CreateCopy("ds", dataset) if resample is None: src_gt = src_ds.GetGeoTransform() dst_gt = dst_ds.GetGeoTransform() src_scale = min(abs(src_gt[1]), abs(src_gt[5])) dst_scale = min(abs(dst_gt[1]), abs(dst_gt[5])) ratio = dst_scale / src_scale resample = gdal.GRA_Bilinear if ratio > 2: resample = gdal.GRA_Average if ratio < 0.5: resample = gdal.GRA_NearestNeighbour gdal.ReprojectImage( src_ds, dst_ds, src_ds.GetProjection(), dst_ds.GetProjection(), resample ) elevation = read_gdal_values(dst_ds) return elevation
Example #17
Source File: gdal2tiles.py From gdal2tiles with MIT License | 4 votes |
def scale_query_to_tile(dsquery, dstile, tiledriver, options, tilefilename=''): """Scales down query dataset to the tile dataset""" querysize = dsquery.RasterXSize tilesize = dstile.RasterXSize tilebands = dstile.RasterCount if options.resampling == 'average': # Function: gdal.RegenerateOverview() for i in range(1, tilebands+1): # Black border around NODATA res = gdal.RegenerateOverview(dsquery.GetRasterBand(i), dstile.GetRasterBand(i), 'average') if res != 0: exit_with_error("RegenerateOverview() failed on %s, error %d" % ( tilefilename, res)) elif options.resampling == 'antialias': # Scaling by PIL (Python Imaging Library) - improved Lanczos array = numpy.zeros((querysize, querysize, tilebands), numpy.uint8) for i in range(tilebands): array[:, :, i] = gdalarray.BandReadAsArray(dsquery.GetRasterBand(i+1), 0, 0, querysize, querysize) im = Image.fromarray(array, 'RGBA') # Always four bands im1 = im.resize((tilesize, tilesize), Image.ANTIALIAS) if os.path.exists(tilefilename): im0 = Image.open(tilefilename) im1 = Image.composite(im1, im0, im1) im1.save(tilefilename, tiledriver) else: if options.resampling == 'near': gdal_resampling = gdal.GRA_NearestNeighbour elif options.resampling == 'bilinear': gdal_resampling = gdal.GRA_Bilinear elif options.resampling == 'cubic': gdal_resampling = gdal.GRA_Cubic elif options.resampling == 'cubicspline': gdal_resampling = gdal.GRA_CubicSpline elif options.resampling == 'lanczos': gdal_resampling = gdal.GRA_Lanczos # Other algorithms are implemented by gdal.ReprojectImage(). dsquery.SetGeoTransform((0.0, tilesize / float(querysize), 0.0, 0.0, 0.0, tilesize / float(querysize))) dstile.SetGeoTransform((0.0, 1.0, 0.0, 0.0, 0.0, 1.0)) res = gdal.ReprojectImage(dsquery, dstile, None, None, gdal_resampling) if res != 0: exit_with_error("ReprojectImage() failed on %s, error %d" % (tilefilename, res))
Example #18
Source File: utils.py From unmixing with MIT License | 4 votes |
def intersect_rasters( ref_rast_defn, src_rast_defn, nodata=-9999, gdt=gdalconst.GDT_Int32): ''' Projects the source raster so that its top-left corner is aligned with the reference raster. Then, clips or pads the source raster so that it has the same number of rows and columns (covers the same extent at the same grid resolution) as the reference raster. Arguments: ref_rast_defn A (raster, gt, wkt) tuple for the reference raster src_rast_defn A (raster, gt, wkt) tuple for the source raster; the raster to be changed nodata The NoData value to fill in where the reference raster is larger gdt The GDAL data type to use for the output raster NOTE: If the reference raster's top-left corner is far left and/or above that of the source raster, the interesect raster may contain no data from the original raster, i.e., an empty raster will result. ''' rast_ref, gt, wkt = ref_rast_defn rast_src, gt0, wkt0 = src_rast_defn # Create a new raster with the desired attributes width, height = (rast_ref.RasterXSize, rast_ref.RasterYSize) width0, height0 = (rast_src.RasterXSize, rast_src.RasterYSize) rast_out = gdal.GetDriverByName('MEM').Create('temp.file', width, height, rast_src.RasterCount, gdt) # Initialize and set the NoData value for i in range(1, rast_src.RasterCount + 1): b = rast_out.GetRasterBand(i) b.Fill(nodata) b.SetNoDataValue(nodata) # Set the desired geotransform, and projection rast_out.SetGeoTransform(gt) rast_out.SetProjection(wkt) # Re-project the source image; now the top-left corners are aligned gdal.ReprojectImage(rast_src, rast_out, wkt0, wkt, gdalconst.GRA_Bilinear) arr = rast_out.ReadAsArray() del rast_src # Delete original raster references del rast_ref del rast_out # Clip the extent of the src image if ref is smaller if arr.ndim > 2: ch, cw = arr.shape[1:] else: ch, cw = arr.shape if (width <= width0): cw = width # Clip src to ref extents if (height <= height0): ch = height if arr.ndim > 2: arr_out = arr[:,0:ch,0:cw] else: arr_out = arr[0:ch,0:cw] return array_to_raster(arr_out, gt, wkt)
Example #19
Source File: test_gdal_python.py From PyRate with Apache License 2.0 | 4 votes |
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): try: os.remove(temp_tif) except PermissionError: print("File opened by another process.")