def test_numpy_rw_7(): ds = gdal.Open('data/byte.tif') array = numpy.zeros([1, ds.RasterYSize, ds.RasterXSize], numpy.uint8) array_res = ds.ReadAsArray(buf_obj=array) assert array is array_res ds2 = gdal_array.OpenArray(array) assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum() # Try again with a 2D array array = numpy.zeros([ds.RasterYSize, ds.RasterXSize], numpy.uint8) array_res = ds.ReadAsArray(buf_obj=array) assert array is array_res ds2 = gdal_array.OpenArray(array) assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum() # With a multi band file ds = gdal.Open('data/rgbsmall.tif') array = numpy.zeros([ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8) array_res = ds.ReadAsArray(buf_obj=array) assert array is array_res ds2 = gdal_array.OpenArray(array) assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum()
def test_numpy_rw_16(): if gdaltest.numpy_drv is None: pytest.skip() import numpy from osgeo import gdal_array # 1D array = numpy.empty([1], numpy.uint8) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) assert ds is None # 4D array = numpy.empty([1, 1, 1, 1], numpy.uint8) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) assert ds is None # Unsupported data type array = numpy.empty([1, 1], numpy.float16) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) assert ds is None
def numpy_rw_16(): if gdaltest.numpy_drv is None: return 'skip' import numpy from osgeo import gdal_array # 1D array = numpy.empty([1], numpy.uint8) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) if ds is not None: gdaltest.post_reason('failure') return 'fail' # 4D array = numpy.empty([1, 1, 1, 1], numpy.uint8) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) if ds is not None: gdaltest.post_reason('failure') return 'fail' # Unsupported data type array = numpy.empty([1, 1], numpy.float16) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) if ds is not None: gdaltest.post_reason('failure') return 'fail' return 'success'
def _CalcResiduals(self, DLST, LST): """Caclculate the residuals between the corresponding DLST and LST data. This function applies the HUTS residual correction (Dominguez et al. 2011). It starts by resampling the input DLST data array to the LST coarse resolution grid. It then subtracts the input LST and DLST arrays and calculates the corresponding LST-DLST residuals. Finally, it supersamples the derived residuals to the fine resolution grid of the predictors using using cubic spline interpolation, so as to avoid any boxing effects. To change the utilised resampling method use the 'SetSupersamplingMthd()' method before running the 'ApplyDownscaling()' method. Arguments: DLST {numpy.ndarray} -- The uncorrected DLST data array LST {numpy.ndarray} -- The corresponding LST data array Returns: numpy.ndarray -- The supersampled LST-DLST residuals array """ # Make a mask with the DLST noData pixels mask = DLST == 0 # Resample the input DLST array to the LST grid DLST = gdal_array.OpenArray(DLST) DLST.SetGeoTransform(self.predictors.GetGeoTransform()) DLST.SetProjection(self.predictors.GetProjection()) DLST.SetDescription("ResidCorr_DLSTarray") upscaled_DLST_VRT = self._WarpRaster( dst=self.LST, src=DLST, dst_ndv=self.LST_NDV, src_ndv=0, resampling="average", ) upscaled_DLST = upscaled_DLST_VRT.ReadAsArray() upscaled_DLST[upscaled_DLST == self.LST_NDV] = np.nan # Calculate the LST-DLST residuals residuals = np.subtract(LST, upscaled_DLST) residuals[np.isnan(residuals)] = 0 # Supersample the residuals to the DLST grid residuals = gdal_array.OpenArray(residuals) residuals.SetGeoTransform(upscaled_DLST_VRT.GetGeoTransform()) residuals.SetProjection(upscaled_DLST_VRT.GetProjection()) residuals.SetDescription("ResidCorr_RESIDarray") supersampled_residuals_VRT = self._WarpRaster( dst=self.predictors, src=residuals, dst_ndv=0, src_ndv=np.nan, resampling=self.supersampling_method, ) supersampled_residuals = supersampled_residuals_VRT.ReadAsArray() supersampled_residuals[mask == True] = 0 return supersampled_residuals
def OpenArray(array, prototype_ds=None, xoff=0, yoff=0): ds = gdal_array.OpenArray(gdalnumeric.GetArrayFilename(array)) if ds is not None and prototype_ds is not None: if type(prototype_ds).__name__ == 'str': prototype_ds = gdal_array.OpenArray(prototype_ds) if prototype_ds is not None: gdalnumeric.CopyDatasetInfo(prototype_ds, ds, xoff=xoff, yoff=yoff) return ds
def input_numpy_array_output_geotiff( self, attribute_values_in_2d_array, prototype_dataset=None, format="GTiff", output_directory=None, output_file_name=None, ): """ This method accepts numpy array objects, x, y and attribute_values and converts them to a GeoTiff image. twoD_attribute_values - 2d attribute values, could be return value from Dataset.get_2d_attribute(); prototype_dataset - prototype dataset that includes the same projection and goetransform info, must be in a format that can be opened by gdal.Open(); format - default "GTiff" for GeoTiff format, possible options "PNG" and any other formats GDAL support; output_directory and output_file_name indicate where to save the output, if unspecified, save to current directory and use time stamp as file name (without file extension). """ driver = gdal.GetDriverByName(format) tdata = Numeric.array(attribute_values_in_2d_array.tolist()) tdata = Numeric.transpose(tdata) min_val = min(Numeric.argmin(tdata)) if min_val >= 0: null_substitute = -1 else: null_substitute = min_val + min_val * 10 for i in range(len(tdata)): for j in range(len(tdata[i])): if tdata[i][j] == 999999: tdata[i][j] = null_substitute if prototype_dataset is not None: imgds = gdalnumeric.OpenArray(tdata, prototype_ds=prototype_dataset) else: imgds = gdalnumeric.OpenArray(tdata) if output_directory is None: output_directory = "." elif not os.path.exists(output_directory): os.mkdir(output_directory) if output_file_name is None: output_file_name = strftime("%Y_%m_%d_%H_%M.", localtime()) + format.lower() sfilename = os.path.join(output_directory, output_file_name) #try: imgds = driver.CreateCopy(sfilename, imgds)
def test_numpy_rw_gdal_array_openarray_permissions(): # Writeable array ar = numpy.zeros([1, 1], dtype=numpy.uint8) ds = gdal_array.OpenArray(ar) assert ds.GetRasterBand(1).Fill(1) == 0 assert ds.GetRasterBand(1).Checksum() != 0 # Non-writeable array ar = numpy.zeros([1, 1], dtype=numpy.uint8) ar.setflags(write=False) ds = gdal_array.OpenArray(ar) with gdaltest.error_handler(): assert ds.GetRasterBand(1).Fill(1) != 0 assert ds.GetRasterBand(1).Checksum() == 0
def test_numpy_rw_11(): if gdaltest.numpy_drv is None: pytest.skip() import numpy from osgeo import gdal_array type_tuples = [ ('uint8', gdal.GDT_Byte, numpy.uint8, 255), ('uint16', gdal.GDT_UInt16, numpy.uint16, 65535), ('int16', gdal.GDT_Int16, numpy.int16, -32767), ('uint32', gdal.GDT_UInt32, numpy.uint32, 4294967295), ('int32', gdal.GDT_Int32, numpy.int32, -2147483648), ('float32', gdal.GDT_Float32, numpy.float32, 1.23), ('float64', gdal.GDT_Float64, numpy.float64, 1.23456789), ('cint16', gdal.GDT_CInt16, numpy.complex64, -32768 + 32767j), ('cint32', gdal.GDT_CInt32, numpy.complex64, -32769 + 32768j), ('cfloat32', gdal.GDT_CFloat32, numpy.complex64, -32768.5 + 32767.5j), ('cfloat64', gdal.GDT_CFloat64, numpy.complex128, -32768.123456 + 32767.123456j) ] for type_tuple in type_tuples: ds = gdal.GetDriverByName('GTiff').Create('/vsimem/' + type_tuple[0], 1, 1, 1, type_tuple[1]) tmp = ds.ReadAsArray() assert tmp.dtype == type_tuple[2], 'did not get expected numpy type' ar = numpy.empty([1, 1], dtype=type_tuple[2]) ar_ds = gdal_array.OpenArray(ar) got_dt = ar_ds.GetRasterBand(1).DataType ar_ds = None expected_dt = type_tuple[1] if expected_dt == gdal.GDT_CInt16 or expected_dt == gdal.GDT_CInt32: expected_dt = gdal.GDT_CFloat32 if got_dt != expected_dt: print(type_tuple[1]) pytest.fail('did not get expected result (0)') ar[0][0] = type_tuple[3] ds.GetRasterBand(1).WriteArray(ar) ds = None ds = gdal.Open('/vsimem/' + type_tuple[0]) ar2 = ds.ReadAsArray() ar3 = numpy.empty_like(ar2) ds.GetRasterBand(1).ReadAsArray(buf_obj=ar3) ds = None gdal.Unlink('/vsimem/' + type_tuple[0]) assert (not (type_tuple[0] == 'float32' and abs(ar2[0][0] - type_tuple[3]) > 1e-6) or \ (type_tuple[0] != 'float32' and ar2[0][0] != type_tuple[3])), \ 'did not get expected result (1)' assert (not (type_tuple[0] == 'float32' and abs(ar3[0][0] - type_tuple[3]) > 1e-6) or \ (type_tuple[0] != 'float32' and ar3[0][0] != type_tuple[3])), \ 'did not get expected result (2)'
def numpy_rw_18(): if gdaltest.numpy_drv is None: return 'skip' import numpy import numpy.random from osgeo import gdal_array img = numpy.random.randint(0, 255, size=(256, 200, 3)).astype('uint8') ds = gdal_array.OpenArray(img, interleave='pixel') if ds is None: gdaltest.post_reason('Failed to open memory array as dataset.') return 'fail' bnd1 = ds.GetRasterBand(1).ReadAsArray() bnd2 = ds.GetRasterBand(2).ReadAsArray() bnd3 = ds.GetRasterBand(3).ReadAsArray() res = numpy.dstack((bnd1, bnd2, bnd3)) if not numpy.all(img == res): return 'fail' res = ds.ReadAsArray(interleave='pixel') if not numpy.all(img == res): return 'fail' return 'success'
def test_numpy_rw_18(): if gdaltest.numpy_drv is None: pytest.skip() import numpy import numpy.random from osgeo import gdal_array img = numpy.random.randint(0, 255, size=(256, 200, 3)).astype('uint8') ds = gdal_array.OpenArray(img, interleave='pixel') assert ds is not None, 'Failed to open memory array as dataset.' bnd1 = ds.GetRasterBand(1).ReadAsArray() bnd2 = ds.GetRasterBand(2).ReadAsArray() bnd3 = ds.GetRasterBand(3).ReadAsArray() res = numpy.dstack((bnd1, bnd2, bnd3)) assert numpy.all(img == res) res = ds.ReadAsArray(interleave='pixel') assert numpy.all(img == res) res = numpy.zeros([256, 200, 3]) ds.ReadAsArray(buf_obj=res, interleave='pixel') assert numpy.all(img == res)
def fill_gaps(elevation, max_distance=10): """Fills gaps in SRTM elevation data for which the distance from missing pixel to nearest existing one is smaller than `max_distance`. This function requires osgeo/gdal to work. :type elevation: numpy.ndarray :param elevation: SRTM elevation data (in meters) :type max_distance: int :param max_distance: maximal distance (in pixels) between a missing point and the nearest valid one. :rtype: numpy.ndarray :return: SRTM elevation data with filled gaps.. """ # Lazily import osgeo - it is only an optional dependency for cartopy. from osgeo import gdal from osgeo import gdal_array src_ds = gdal_array.OpenArray(elevation) srcband = src_ds.GetRasterBand(1) dstband = srcband maskband = srcband smoothing_iterations = 0 options = [] gdal.FillNodata(dstband, maskband, max_distance, smoothing_iterations, options, callback=None) elevation = dstband.ReadAsArray() return elevation
def convert_file(f: str, output_proj: str) -> None: nodata_val = -32768 in_ds = gdal.Open(f"/vsigs/{f}") big_vals = in_ds.ReadAsArray() * 10000 np.nan_to_num(big_vals, copy=False, nan=nodata_val) out_ds = gdal_array.OpenArray(np.int16(big_vals)) gdal_array.CopyDatasetInfo(in_ds, out_ds) gdal.Warp( # Could also copy directly to vsiaz if you want f"data/hm/{os.path.basename(f)}", out_ds, dstSRS=output_proj, srcNodata=nodata_val, dstNodata=nodata_val, xRes=30, yRes=30, creationOptions=[ "COMPRESS=LZW", "PREDICTOR=2", "BLOCKXSIZE=256", "BLOCKYSIZE=256", "INTERLEAVE=BAND", "TILED=YES", ], )
def array_to_raster_clone(a, proto, xoff=None, yoff=None): ''' Creates a raster from a given array and a prototype raster dataset, with optional x- and y-offsets if the array was clipped. Arguments: a A NumPy array proto A prototype dataset xoff The offset in the x-direction; should be provided when clipped yoff The offset in the y-direction; should be provided when clipped ''' try: rast = gdal_array.OpenNumPyArray(a) except AttributeError: # For backwards compatibility with older version of GDAL rast = gdal.Open(gdalnumeric.GetArrayFilename(a)) except: rast = gdal_array.OpenArray(a) kwargs = dict() if xoff is not None and yoff is not None: kwargs = dict(xoff=xoff, yoff=yoff) # Copy the projection info and metadata from a prototype dataset if type(proto) == str: proto = gdal.Open(proto) gdalnumeric.CopyDatasetInfo(proto, rast, **kwargs) return rast
def copy_geo(array, prototype=None, xoffset=0, yoffset=0): """Copy geotransfrom from prototype dataset to array but account for x, y offset of clipped array.""" ds = gdal_array.OpenArray(array) prototype = gdal.Open(prototype) gdal_array.CopyDatasetInfo(prototype, ds, xoff=xoffset, yoff=yoffset) return ds
def SaveArrayWithGeo(array, src_filename, dst_filename, format): """ SaveArrayWithGeo(): Saves an Array (array) with Georeferencing from another file (src_flnm), save it in file (dst_flnm) with format (format) SaveArrayWithGeo( self, array, src_filename, dst_filename, format ) """ #From warmerdam at p... Thu May 3 09:36:03 2001 #From: warmerdam at p... (Frank Warmerdam) #Date: Wed Nov 21 11:49:13 2007 #Subject: [gdal-dev] python bindings #References: <Pine.OSF.4.20.0105030806190.4482-100000@e...> #Message-ID: <3AF15EC3.FFD4AACF@p...> # Read information from source file. src_ds = gdal.Open(str(src_filename)) gt = src_ds.GetGeoTransform() pj = src_ds.GetProjection() src_ds = None # Create GDAL dataset for array, and set georeferencing. src_ds = gdal_array.OpenArray(array) src_ds.SetGeoTransform(gt) src_ds.SetProjection(pj) # Write array dataset to new file. driver = gdal.GetDriverByName(format) if driver is None: raise ValueError, "SaveArrayWithGeo: Can't find driver " + format return driver.CreateCopy(dst_filename, src_ds)
def array_to_raster(a, gt, wkt, xoff=None, yoff=None, dtype=None): ''' Creates a raster from a given array, with optional x- and y-offsets if the array was clipped. Arguments: a A NumPy array gt A GDAL GeoTransform tuple wkt Well-Known Text projection xoff The offset in the x-direction; should be provided when clipped yoff The offset in the y-direction; should be provided when clipped dtype The data type to coerce on the array ''' if dtype is not None: a = a.astype(dtype) try: rast = gdal_array.OpenNumPyArray(a) except AttributeError: # For backwards compatibility with older version of GDAL rast = gdal.Open(gdalnumeric.GetArrayFilename(a)) except: rast = gdal_array.OpenArray(a) rast.SetGeoTransform(gt) rast.SetProjection(wkt) if xoff is not None and yoff is not None: # Bit of a hack; essentially, re-create the raster but with the # correct X and Y offsets (don't know how to do this without the # use of CopyDatasetInfo()) return array_to_raster_clone(a, rast, xoff, yoff) return rast
def test_numpy_rw_8(): ds = gdal.Open('data/rgbsmall.tif') array = numpy.zeros([ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8) ds.ReadAsArray(buf_obj=array) ds2 = gdal_array.OpenArray(array) for i in range(1, ds.RasterCount): assert ds2.GetRasterBand(i).Checksum() == ds.GetRasterBand(i).Checksum()
def test_numpy_rw_15(): array = numpy.empty([1, 1, 1], numpy.uint8) ds = gdal_array.OpenArray(array) gt = ds.GetGeoTransform(can_return_null=True) assert gt is None ds.SetGeoTransform([1, 2, 3, 4, 5, -6]) gt = ds.GetGeoTransform() assert gt == (1, 2, 3, 4, 5, -6)
def generate_patch(input_dir:str,output_dir:str,patch_width:int,patch_height:int,x_off:int,y_off:int): """ input_dir: input image directory output_dir: output image directory patch_width: the width of the cliping image block (pixle) patch_height: the height of the cliping image block (pixle) x_off: the overlap on image x axis (pixle) y_off: the overlap on image y axis (pixle) """ img_list=os.listdir(input_dir) for img_name in tqdm(img_list,ascii=True): img_path=input_dir+img_name name_not_tif=img_name.split('.')[0] img_array = gdal_array.DatasetReadAsArray( gdal.Open(img_path, GA_ReadOnly)) dimension_img_array=len(img_array.shape) if dimension_img_array==3: (_,height, width) = img_array.shape elif dimension_img_array==2: (height, width) = img_array.shape else: print('The dimension of image is not right') break x_num=math.ceil((width-patch_width)/(patch_width-x_off))+1 y_num=math.ceil((height-patch_height)/(patch_height-y_off))+1 k=0 for i in range(y_num): if i==y_num-1: s_y=height-patch_height else: s_y=i*(patch_height-y_off) for j in range(x_num): if j==x_num-1: s_x=width-patch_width else: s_x=j*(patch_width-x_off) if dimension_img_array==3: img_clip=img_array[:,s_y:s_y+patch_height,s_x:s_x+patch_width] elif dimension_img_array==2: img_clip=img_array[s_y:s_y+patch_height,s_x:s_x+patch_width] filename=output_dir+name_not_tif+'_'+str(k)+'.tif' driver = gdal.GetDriverByName("GTiff") driver.CreateCopy(filename, gdal_array.OpenArray(img_clip, None))#, options=["COMPRESS=LZW", "PREDICTOR=2"]) k+=1
def open_array(array, prototype_ds=None, xoff=0, yoff=0): from osgeo import gdal_array ds = gdal_array.OpenArray(array) if ds is not None and prototype_ds is not None: if type(prototype_ds).__name__ == 'str': prototype_ds = gdalnumeric.gdal.Open(prototype_ds) if prototype_ds is not None: gdalnumeric.CopyDatasetInfo(prototype_ds, ds, xoff=xoff, yoff=yoff) return ds
def test_numpy_rw_6(): ds = gdal.Open('data/byte.tif') array = numpy.zeros([ds.RasterYSize, ds.RasterXSize], numpy.uint8) array_res = ds.GetRasterBand(1).ReadAsArray(buf_obj=array) assert array is array_res ds2 = gdal_array.OpenArray(array) assert ds2.GetRasterBand(1).Checksum() == ds.GetRasterBand(1).Checksum()
def test_numpy_rw_16(): # 1D array = numpy.empty([1], numpy.uint8) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) assert ds is None # 4D array = numpy.empty([1, 1, 1, 1], numpy.uint8) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) assert ds is None # Unsupported data type array = numpy.empty([1, 1], numpy.float16) with gdaltest.error_handler(): ds = gdal_array.OpenArray(array) assert ds is None
def test_numpy_rw_2(): array = gdal_array.LoadFile('data/utmsmall.tif') assert array is not None, 'Failed to load utmsmall.tif into array' ds = gdal_array.OpenArray(array) assert ds is not None, 'Failed to open memory array as dataset.' bnd = ds.GetRasterBand(1) assert bnd.Checksum() == 50054, 'Didnt get expected checksum on reopened file' ds = None
def test_createNumpyDataset(): ny, nx = 200, 100 data = np.random.randn(ny, nx).astype(np.float32) dset = gdal_array.OpenArray(data) raster = isce.io.Raster(np.uintp(dset.this)) assert (raster.width == nx) assert (raster.length == ny) assert (raster.datatype() == gdal.GDT_Float32) dset = None del raster
def calc_aspect(elev, proc_dims=None, w=None, **kwargs): """ Calculates aspect from elevation Args: elev (2d array): The elevation data. proc_dims (Optional[tuple]): Dimensions to resize to. w (Optional[int]): The smoothing window size when ``proc_dims`` is given. kwargs (Optional[dict]): Keyword arguments passed to ``gdal.DEMProcessingOptions``. Returns: ``numpy.ndarray`` """ if not OPENCV_INSTALLED: logger.exception('OpenCV must be installed.') if proc_dims: inrows, incols = elev.shape elev = cv2.resize(elev.astype('float32'), proc_dims, interpolation=cv2.INTER_LINEAR) ds = gdal_array.OpenArray(elev.astype('float64')) aspect_options = gdal.DEMProcessingOptions(**kwargs) out_ds = gdal.DEMProcessing('', ds, 'aspect', options=aspect_options) dst_array = out_ds.GetRasterBand(1).ReadAsArray() ds = None out_ds = None if proc_dims: dst_array = cv2.resize(dst_array.astype('float32'), (incols, inrows), interpolation=cv2.INTER_LINEAR) if not w: w = 15 return np.float64(cv2.bilateralFilter(np.float32(dst_array), w, 10, 10)) else: return np.float64(dst_array)
def cambiar_projection(in_array: np.ndarray): """Convert Grid to New Projection. Parameters ---------- in_array """ # WRF Spatial Reference System source_prj = osr.SpatialReference() source_prj.ImportFromProj4('+proj=lcc +lat_0=-32.500008 +lon_0=-62.7 ' '+lat_1=-60 +lat_2=-30 +x_0=0 +y_0=0 +R=6370000' ' +units=m +no_defs') # Lat/lon WSG84 Spatial Reference System target_prj = osr.SpatialReference() target_prj.ImportFromProj4('+proj=longlat +ellps=WGS84 ' '+datum=WGS84 +no_defs') # se configura la matriz destino sizex = int(((CBA_EXTENT[2] - CBA_EXTENT[0]) * KM_PER_DEGREE) / RESOLUTION) sizey = int(((CBA_EXTENT[3] - CBA_EXTENT[1]) * KM_PER_DEGREE) / RESOLUTION) out_array = np.ndarray(shape=(int(in_array.coords['Time'].count()), sizey, sizex)) for t in range(in_array.coords['Time'].size): # loar gdal array y se le asigna la projección y transofrmación raw = gdal_array.OpenArray(np.flipud(in_array[t].values)) raw.SetProjection(source_prj.ExportToWkt()) raw.SetGeoTransform( getGeoT(WRF_EXTENT, raw.RasterYSize, raw.RasterXSize)) grid = gdal.GetDriverByName('MEM').Create("tmp_ras", sizex, sizey, 1, gdal.GDT_Float32) # Setup projection and geo-transformation grid.SetProjection(target_prj.ExportToWkt()) grid.SetGeoTransform( getGeoT(CBA_EXTENT, grid.RasterYSize, grid.RasterXSize)) # reprojectamos gdal.ReprojectImage(raw, grid, source_prj.ExportToWkt(), target_prj.ExportToWkt(), gdal.GRA_NearestNeighbour, options=['NUM_THREADS=ALL_CPUS']) out_array[t] = grid.ReadAsArray() return out_array, grid.GetGeoTransform(), grid.GetProjection()
def test_numpy_rw_15(): if gdaltest.numpy_drv is None: pytest.skip() import numpy from osgeo import gdal_array array = numpy.empty([1, 1, 1], numpy.uint8) ds = gdal_array.OpenArray(array) gt = ds.GetGeoTransform(can_return_null=True) assert gt is None ds.SetGeoTransform([1, 2, 3, 4, 5, -6]) gt = ds.GetGeoTransform() assert gt == (1, 2, 3, 4, 5, -6)
def OpenArray_T(array, prototype_ds=None, xoff=0, yoff=0): """ EDIT: this is basically an overloaded version of the gdal_array.OpenArray passing in xoff, yoff explicitly so we can pass these params off to CopyDatasetInfo """ #ds = gdal.Open(gdalnumeric.GetArrayFilename(array)) ds = gdal_array.OpenArray(array) if ds is not None and prototype_ds is not None: if type(prototype_ds).__name__ == 'str': prototype_ds = gdal.Open(prototype_ds) if prototype_ds is not None: gdalnumeric.CopyDatasetInfo( prototype_ds, ds, xoff=xoff, yoff=yoff) return ds
def save(array, filename, dtype=None, georef=None, compress=None, pixel=True): """Export a numpy array as a band-interleaved GDAL image. georef clones transform, projection, and GCPs from source image filename. Compression with DEFLATE better than LZW, need to use predictor for ints. >>> a1 = read('test/truth_float.tif') >>> save(a1, 'copy.tif') >>> a2 = read('copy.tif') >>> compare(a1, a2) True >>> os.remove('copy.tif') >>> row = [[255, 0, 0, 128]] * 10 # 4-band, 10-cols, pixel interleaved >>> a = np.array([row, row, row], dtype=np.uint8) # 3-rows >>> save(a, 'bands.tif', dtype=np.uint8) >>> read('bands.tif')[0, 0] # Read a pixel, from pixel interleaved array([255, 0, 0, 128], dtype=uint8) >>> os.remove('bands.tif') >>> gdal.Open('test/ag.bmp').GetGeoTransform() (95.0, 10.0, 0.0, 105.0, 0.0, -10.0) >>> save(read('test/ag.bmp'), 'copy.tif', georef='test/ag.bmp') >>> gdal.Open('copy.tif').GetGeoTransform() (95.0, 10.0, 0.0, 105.0, 0.0, -10.0) >>> os.path.getsize('copy.tif') # Uncompressed by default 81114L >>> save(read('test/ag.bmp'), 'copy.tif', georef='test/ag.bmp', ... compress='DEFLATE') >>> os.path.getsize('copy.tif') 48109L >>> os.remove('copy.tif') """ if dtype: array = array.astype(dtype) if pixel and len(array.shape) > 2: array = roll(array, 'right') if compress is None: options = [] else: "Optimized for int image compression" options = ['COMPRESS=%s' % compress, 'PREDICTOR=2'] driver = gdal.GetDriverByName('GTiff') driver.CreateCopy(filename, gdal_array.OpenArray(array, georef), options=options)
def test_createNumpyDataset(): import numpy as np from isce3.extensions.isceextension import pyRaster from osgeo import gdal_array import os ny, nx = 200, 100 data = np.random.randn(ny, nx).astype(np.float32) dset = gdal_array.OpenArray(data) raster = pyRaster('', dataset=dset) assert (raster.width == nx) assert (raster.length == ny) assert (raster.getDatatype() == 6) dset = None del raster