def cog(input_tif, output_tif,no_data=None):
    
    translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \
                                                                    '-co COPY_SRC_OVERVIEWS=YES ' \
                                                                    '-co COMPRESS=LZW '))
    
    if no_data != None:
        translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \
                                                                        '-co COPY_SRC_OVERVIEWS=YES ' \
                                                                        '-co COMPRESS=LZW '\
                                                                        '-a_nodata {}'.format(no_data)))
    ds = gdal.Open(input_tif, gdal.OF_READONLY)

    gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
    ds.BuildOverviews('NEAREST', [2,4,8,16,32])
    
    ds = None

    ds = gdal.Open(input_tif)
    gdal.Translate(output_tif,
                   ds, 
                   options=translate_options)
    ds = None

    os.remove('{}.ovr'.format(input_tif))
    os.remove(input_tif)
Esempio n. 2
0
def cog(input_tif):
    
    temp_tif = 'temp.tif'
    
    shutil.move(input_tif, temp_tif)
    
    translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \
                                                                    '-co COPY_SRC_OVERVIEWS=YES ' \
                                                                    ' -co COMPRESS=DEFLATE'))

    ds = gdal.Open(temp_tif, gdal.OF_READONLY)

    gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
    ds.BuildOverviews('NEAREST', [2,4,8,16,32])
    
    ds = None

    ds = gdal.Open(temp_tif)
    gdal.Translate(input_tif,
                   ds, 
                   options=translate_options)
    ds = None

    os.remove('{}.ovr'.format(temp_tif))
    os.remove(temp_tif)
Esempio n. 3
0
    def convertImage(self, pathname, out_path, options=None):
        """
        convert image with gdal translate functionality
        """

        # create output pathname
        out_pathname = os.path.join(out_path, os.path.basename(pathname))
        if not os.path.exists(out_pathname):

            # open existing image
            src_ds = gdal.Open(pathname, gdal.GA_ReadOnly)
            if src_ds is not None:

                # create out path if required
                if not os.path.exists(out_path):
                    os.makedirs(out_path)

                # execute translation - report error to log
                ds = gdal.Translate(
                    out_pathname,
                    src_ds,
                    options=gdal.TranslateOptions(creationOptions=options))
                if ds is None and self._log_file is not None:
                    self._log_file.write('Error converting {} -> {} {}'.format(
                        pathname, out_pathname, ','.join(options)))

                # copy geom file
                if os.path.exists(pathname.replace('.TIF', '.geom')):
                    shutil.copy(pathname.replace('.TIF', '.geom'), out_path)

            # free src_ds
            src_ds = None

        return out_pathname
Esempio n. 4
0
def get_surflith(dem, dema, interp_data, output_filename='DEMxyz.csv'):
    '''Reshape DEM and use it to compute the lithology values of the GemPy model at the land surface.
    Returns an array of lith values at the surface z elevation for each xy point.
    
    dem:                dem object returned by importDEM() or dem = gdal.Open(filename)
    dema:               dem array returned by importDEM() or dema = dem.ReadAsArray()
    interp_data:        interpolated data returned by gempy.InterpolatorData()
    output_filename:    string to name gdal's output csv file (can be a throw-away - not used again)
    
    returns:
    surflith:           an array of lith values at the surface z elevation for each xy point, dim (yres,xres)'''

    #Get an array with xyz values from the DEM:
    #can this be streamlined to avoid having to export and re-import?
    translate_options = gdal.TranslateOptions(
        options=['format'], format="XYZ")  #set options for gdal.Translate()
    gdal.Translate(
        output_filename, dem, options=translate_options
    )  #convert dem to a csv with one column of points, each with an xyz value
    xyz = pn.read_csv(output_filename, header=None,
                      sep=' ')  #read xyz csv with pandas
    demlist = xyz.as_matrix(
    )  #convert to np array of (x,y,z) values with dim (ncol*nrow, 3)

    #Format the geologic data:
    surflith, fault2 = gp.compute_model_at(
        demlist, interp_data
    )  #compute the model values at the locations specified (aka the land surface) (why is fault a required output?)
    surflith = surflith[0].reshape(
        dema.shape
    )  #reshape lith block (a list) to an array with same dimensions as dem (yres,xres,zres) (note: xres*yres must equal length of lith)
    #now we have a discretized array with the same resolution as the dem, with a value for the lithology at the surface elevation for each xy point
    return surflith
Esempio n. 5
0
def cog(input_tif):

    temp_tif = "temp.tif"

    shutil.move(input_tif, temp_tif)

    translate_options = gdal.TranslateOptions(
        gdal.ParseCommandLine(
            "-co TILED=YES " "-co COPY_SRC_OVERVIEWS=YES " " -co COMPRESS=DEFLATE"
        )
    )

    ds = gdal.Open(temp_tif, gdal.OF_READONLY)

    gdal.SetConfigOption("COMPRESS_OVERVIEW", "DEFLATE")
    ds.BuildOverviews("NEAREST", [2, 4, 8, 16, 32])

    ds = None

    ds = gdal.Open(temp_tif)
    gdal.Translate(input_tif, ds, options=translate_options)
    ds = None

    os.remove("{}.ovr".format(temp_tif))
    os.remove(temp_tif)
Esempio n. 6
0
def save_array_as_image(image_path, image_array):

    image_array = image_array.astype(np.uint8)
    if not image_path.lower().endswith(".png") and not image_path.lower(
    ).endswith(".jpg") and not image_path.lower().endswith(".tif"):
        print(image_path)
        print("Error! image_path has to end with .png, .jpg or .tif")
    height = image_array.shape[0]
    width = image_array.shape[1]
    if height * width < Image.MAX_IMAGE_PIXELS:
        newIm = Image.fromarray(image_array, "RGB")
        newIm.save(image_path)

    else:
        gdal.AllRegister()
        driver = gdal.GetDriverByName('MEM')
        ds1 = driver.Create('', width, height, 3, gdal.GDT_Byte)
        ds = driver.CreateCopy(image_path, ds1, 0)

        image_array = np.swapaxes(image_array, 2, 1)
        image_array = np.swapaxes(image_array, 1, 0)
        ds.GetRasterBand(1).WriteArray(image_array[0], 0, 0)
        ds.GetRasterBand(2).WriteArray(image_array[1], 0, 0)
        ds.GetRasterBand(3).WriteArray(image_array[2], 0, 0)
        gdal.Translate(image_path,
                       ds,
                       options=gdal.TranslateOptions(bandList=[1, 2, 3],
                                                     format="png"))
Esempio n. 7
0
    def close(self):
        #gdalTranslateOpts = gdal.TranslateOptions(format='VRT',
        #                                      width=outXSize, height=outYSize,
        #                                      srcWin=[0,0,outXSize*xlooks, outYSize*ylooks],
        #                                      noData=noData, resampleAlg=method)
        gdalTranslateOpts = gdal.TranslateOptions(format='VRT', unscale=True)

        gdal.Translate(self.stackName, self.vrt, options=gdalTranslateOpts)
Esempio n. 8
0
def cog(ds, output_name):

    translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \
                                                                    '-co COPY_SRC_OVERVIEWS=YES ' \
                                                                    '-co COMPRESS=LZW '))

    gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
    ds.BuildOverviews('NEAREST', [2, 4, 8, 16, 32])
    gdal.Translate(output_name, ds, options=translate_options)
    ds = None
Esempio n. 9
0
def gdal_translate(dest, src, *args, **kwargs):
    try:
        # If outputType is specified, convert it to gdal datatype
        kwargs['outputType'] = gdal.GetDataTypeByName(kwargs['outputType'])
    except KeyError:
        # If outputType not specified, no conversion is necessary and GDAL will
        #  use default arguments.
        pass
    opts = gdal.TranslateOptions(*args, **kwargs)
    return gdal.Translate(dest, src, options=opts)
def save_array_as_image(image_path, image_array, tile_size=None):

    image_array = image_array.astype(np.uint8)
    if not image_path.endswith(".png") and not image_path.endswith(
            ".jpg") and not image_path.endswith(".tif"):
        print("Error! image_path has to end with .png, .jpg or .tif")
    height = image_array.shape[0]
    width = image_array.shape[1]
    if height * width < Image.MAX_IMAGE_PIXELS:
        newIm = Image.fromarray(image_array, "RGB")
        newIm.save(image_path)

    else:
        gdal.AllRegister()
        driver = gdal.GetDriverByName('MEM')
        ds1 = driver.Create('', width, height, 3, gdal.GDT_Byte)
        ds = driver.CreateCopy(image_path, ds1, 0)

        image_array = np.swapaxes(image_array, 2, 1)
        image_array = np.swapaxes(image_array, 1, 0)
        ds.GetRasterBand(1).WriteArray(image_array[0], 0, 0)
        ds.GetRasterBand(2).WriteArray(image_array[1], 0, 0)
        ds.GetRasterBand(3).WriteArray(image_array[2], 0, 0)

        if not tile_size:
            gdal.Translate(image_path,
                           ds,
                           options=gdal.TranslateOptions(bandList=[1, 2, 3],
                                                         format="png"))

        else:
            for i in range(0, width, tile_size):
                for j in range(0, height, tile_size):
                    #define paths of image tile and the corresponding json file containing the geo information
                    out_path_image = image_path[:-4] + "row" + str(
                        int(j / tile_size)) + "_col" + str(int(
                            i / tile_size)) + ".png"
                    #tile image with gdal (copy bands 1, 2 and 3)
                    gdal.Translate(out_path_image,
                                   ds,
                                   options=gdal.TranslateOptions(
                                       srcWin=[i, j, tile_size, tile_size],
                                       bandList=[1, 2, 3]))
Esempio n. 11
0
 def set_data_type(tiff_path, tiff_out, out_type, res_format= 'GTiff'):
     """
     改变数据类型
     :param tiff_path:
     :param tiff_out:
     :param out_type:  输出数据类型,如 gdal.GDT_Float64
     :param res_format:   返回类型, GTiff 输出为文件, MEM 输出为临时文件
     :return:
     """
     translate_options = gdal.TranslateOptions(outputType=out_type, format=res_format)
     return gdal.Translate(tiff_out, tiff_path, options=translate_options)
Esempio n. 12
0
    def _extract_band(self, rasterFileName, band):
        sourceDir = os.path.join(os.path.dirname(self.stackName),
                                 "source_bands")
        if not os.path.exists(sourceDir):
            os.makedirs(sourceDir)

        bndVRT = os.path.join(sourceDir, os.path.basename(rasterFileName))
        gdalTranslateOpts = gdal.TranslateOptions(format='VRT',
                                                  bandList=[band])
        gdal.Translate(bndVRT, rasterFileName, options=gdalTranslateOpts)
        return os.path.abspath(bndVRT)
Esempio n. 13
0
def cog(input_tif, output_tif, band=None):
    
    if band is not None:
        
        translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \
                                                                        '-co COPY_SRC_OVERVIEWS=YES ' \
                                                                        '-co BIGTIFF=YES ' \
                                                                        '-co COMPRESS=LZW ' \
                                                                        '-ot Float32 ' \
                                                                        '-b {}'.format(band)))
    else:
        translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co TILED=YES ' \
                                                                        '-co COPY_SRC_OVERVIEWS=YES ' \
                                                                        '-co BIGTIFF=YES ' \
                                                                        '-co COMPRESS=LZW ' \
                                                                        '-ot Float32 ' \
                                                                        '-b 1 -b 2 -b 3'))

    ds = gdal.Open(input_tif, gdal.OF_READONLY)
    
    gdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')
    ds.BuildOverviews('NEAREST', [2,4,8,16,32])
    
    ds = None

    ds = gdal.Open(input_tif)

    gdal.Translate(output_tif,
                   ds, 
                   options=translate_options)

    ds = None
    if (os.path.exists(output_tif)):
        ciop.log('INFO','COG {} created'.format(output_tif))
    else:
        ciop.log('ERROR','COG {} NOT created'.format(output_tif))
       
    try:
        os.remove('{}.ovr'.format(input_tif))
    except:
        pass
Esempio n. 14
0
def create_rgb(in_mineral, out_rgb):
    
    translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co COMPRESS=LZW '\
                                                                    '-ot UInt16 ' \
                                                                    '-a_nodata 256 ' \
                                                                    '-b 1 -b 2 -b 3 -b 4'))
                                                                    
    ds = gdal.Open(in_mineral, gdal.OF_READONLY)

    gdal.Translate(out_rgb, 
                   ds, 
                   options=translate_options)
Esempio n. 15
0
def create_rbb(in_rgb, out_rbb):

    #gdal_translate -ot UInt16 -a_nodata 256 ${1::-14}RED-BLUE.rgb.tif ${1::-8}.acd.tif -co COMPRESS=LZW -b 1 -b 3 -b 3

    translate_options = gdal.TranslateOptions(gdal.ParseCommandLine('-co COMPRESS=LZW '\
                                                                    '-ot UInt16 ' \
                                                                    '-a_nodata 256 ' \
                                                                    '-b 1 -b 3 -b 3 '))

    ds = gdal.Open(in_rgb, gdal.OF_READONLY)

    gdal.Translate(out_rbb, ds, options=translate_options)
Esempio n. 16
0
    def __init__(self, **kwargs):
        kwargs['defaults'] = {
         'store_msg'  : [],\
         'database'   : None,\
         'product'    : 'MCD15A3H',\
         'tile'       : 'h08v06',\
         'log'        : None,\
         'day'        : '01',\
         'doy'        : None,
         'month'      : '*',\
         'sds'        : None,
         'year'       : "2019",\
         'site'       : 'https://e4ftl01.cr.usgs.gov',\
         'size_check' : False,\
         'noclobber'  : True,\
         'local_dir'  : 'work',\
         'local_file' : None,\
         'db_file'    : None,\
         'db_dir'     : 'work',\
         'verbose'    : False,\
         'stderr'     : sys.stderr
        }
        self.__dict__.update(ginit(self, **kwargs))
        if 'database' in self.__dict__ and type(self.database) == Database:
            # already have databse stored
            pass
        else:
            self.database = Database(self.db_file,\
                              **(fdict(self.__dict__.copy(),ignore=['db_dir','db_file'])))

        self.translateoptions = gdal.TranslateOptions(
            gdal.ParseCommandLine("-of Gtiff -co COMPRESS=LZW"))
        # list of tiles
        if type(self.tile) is str:
            self.tile = [self.tile]

        if type(self.sds) is str:
            self.sds = [self.sds]
        if self.sds is not None:
            self.msg(f'initial SDS {self.sds}')
            self.required_sds = self.sds

        # for most transactions, we want all SDS
        # so self.sds should reflect that
        self.sds = None
        response = self.database.get_from_db('SDS', self.product)
        if response:
            self.msg("found SDS names in database")
            self.sds = response
            self.msg(self.sds)
            # require them all
            if 'required_sds' not in self.__dict__:
                self.required_sds = self.sds
Esempio n. 17
0
def tif2xyz(path_dest, dtm):
    '''returns array with the x,y,z coordinates of the topography.'''
    shape = dtm.ReadAsArray().shape
    #print(shape)
    gdal.Translate(path_dest,
                   dtm,
                   options=gdal.TranslateOptions(options=['format'],
                                                 format="XYZ"))
    xyz = pn.read_csv(path_dest, header=None, sep=' ').as_matrix()
    return np.dstack([
        xyz[:, 0].reshape(shape), xyz[:, 1].reshape(shape),
        xyz[:, 2].reshape(shape)
    ])
Esempio n. 18
0
    def _compress_output_file(self, out, band):
        src_ds = gdal.Open(out)
        output = os.path.join(self.path_root,
                              'GFstack_SI_' + band + '_crop.tif')
        # Compress the image
        topts = gdal.TranslateOptions(
            format='GTiff',
            outputType=gdal.GDT_UInt16,
            creationOptions=['COMPRESS=LZW', 'GDAL_PAM_ENABLED=NO'],
            bandList=list(range(1, src_ds.RasterCount + 1)))  # gdal.GDT_Byte

        gdal.Translate(output, src_ds, options=topts)

        os.remove(out)
Esempio n. 19
0
    def convert2xyz(self):
        '''
        Returns: array with the x,y,z coordinates of the topography  [0]: shape(a,b,3), [1]: shape(a*b,3)
        '''
        path_dest = 'topo.xyz'
        print('storing converted file...')
        shape = self.dem_zval.shape
        gdal.Translate(path_dest, self.dem, options=gdal.TranslateOptions(options=['format'], format="XYZ"))

        xyz = pn.read_csv(path_dest, header=None, sep=' ').values
        x = np.flipud(xyz[:, 0].reshape(shape))
        y = np.flipud(xyz[:, 1].reshape(shape))
        z = np.flipud(xyz[:, 2].reshape(shape))

        self.values_3D = np.dstack([x, y, z])
def remove_feature_rasters_alpha_band() -> None:
    filenames_raw = [
        fn for fn in os.listdir(paths.DIR_DATA_TRAIN_FEATURES_RAW)
        if fn.endswith('features.tif')
    ]
    for filename_raw in tqdm(filenames_raw,
                             desc='Remove feature rasters alpha band'):
        filepath_lock = os.path.join(paths.DIR_DATA_TRAIN_FEATURES_RAW,
                                     filename_raw + '.lock')
        filepath_raw = os.path.join(paths.DIR_DATA_TRAIN_FEATURES_RAW,
                                    filename_raw)
        filename_tmp = re.sub('features.tif', 'features_tmp.tif', filename_raw)
        filepath_tmp = os.path.join(paths.DIR_DATA_TRAIN_FEATURES_RAW,
                                    filename_tmp)
        filepath_clean = os.path.join(paths.DIR_DATA_TRAIN_FEATURES_CLEAN,
                                      filename_raw)
        # Skip if output file already exists or if lock file exists
        if os.path.exists(filepath_clean) or os.path.exists(filepath_lock):
            continue
        try:
            file_lock = open(filepath_lock, 'x')
        except OSError:
            continue

        try:
            # Write in nodata values
            command = 'gdal_calc.py -A {filepath_raw} --allBands=A -B {filepath_raw} --B_band=4 ' + \
                      '--outfile={filepath_tmp} --NoDataValue=-9999 --type=Int16 --co=COMPRESS=DEFLATE ' + \
                      '--co=TILED=YES --overwrite --calc="A * (B == 255) + -9999 * (B == 0)"'
            command = command.format(filepath_raw=filepath_raw,
                                     filepath_tmp=filepath_tmp)
            gdal_command_line.run_gdal_command(command, _logger)
            # Remove alpha band
            options_removed = gdal.TranslateOptions(
                bandList=[1, 2, 3],
                outputType=gdal.GDT_Int16,
                creationOptions=['COMPRESS=DEFLATE', 'TILED=YES'])
            gdal.Translate(filepath_clean,
                           filepath_tmp,
                           options=options_removed)
        except Exception as error_:
            raise error_
        finally:
            if os.path.exists(filepath_tmp):
                os.remove(filepath_tmp)
            file_lock.close()
            os.remove(filepath_lock)
Esempio n. 21
0
    def convert2xyz(self):
        '''
        Translates the gdal raster object to a numpy array of xyz coordinates.
        '''
        path_dest = 'topo.xyz'
        print('storing converted file...')
        shape = self.dem_zval.shape
        if len(shape) == 3:
            shape = shape[1:]
        gdal.Translate(path_dest, self.dem, options=gdal.TranslateOptions(options=['format'], format="XYZ"))

        xyz = pn.read_csv(path_dest, header=None, sep=' ').values
        x = np.flipud(xyz[:, 0].reshape(shape))
        y = np.flipud(xyz[:, 1].reshape(shape))
        z = np.flipud(xyz[:, 2].reshape(shape))

        self.values_3D = np.dstack([x, y, z])
def compress_feature_response_rasters() -> None:
    raise AssertionError(
        'This script has not been tested since being updated, be careful')
    _logger.info('Compress rasters')
    filepaths_rasters = [
        os.path.join(paths.DIR_DATA_TRAIN_CLEAN, fn)
        for fn in os.listdir(paths.DIR_DATA_TRAIN_CLEAN) if fn.endswith('.tif')
    ]
    filepath_tmp = os.path.join(paths.DIR_DATA_TRAIN_RAW, 'tmp_compress.tif')
    for idx_filepath, filepath_clean in enumerate(filepaths_rasters):
        _logger.debug('Compressing raster {} of {}:  {}'.format(
            1 + idx_filepath, len(filepaths_rasters), filepath_clean))
        options_translate = gdal.TranslateOptions(
            creationOptions=['COMPRESS=DEFLATE', 'TILED=YES'])
        gdal.Translate(filepath_tmp, filepath_clean, options=options_translate)
        shutil.copy(filepath_tmp, filepath_clean)
        os.remove(filepath_tmp)
Esempio n. 23
0
    def processAlgorithm(self, parameters, context, feedback):

        RasterIN = self.parameterAsRasterLayer(parameters, self.RasterIN,
                                               context)
        if RasterIN is None:
            raise QgsProcessingException(
                self.invalidSourceError(parameters, self.RasterIN))
        RasterIN = RasterIN.dataProvider().dataSourceUri()

        RGB_Output = self.parameterAsFileOutput(parameters, self.RasterOUT,
                                                context)

        Carregar = self.parameterAsBool(parameters, self.OPEN, context)

        tipo = self.parameterAsEnum(parameters, self.TYPE, context)

        qualidade = self.parameterAsEnum(parameters, self.QUALITY, context)

        tiled = self.parameterAsBool(parameters, self.TILED, context)

        degree = ['65%', '75%', '85%']
        qualidade = 'JPEG_QUALITY=' + degree[qualidade]

        if tipo == 0:
            options = ['PHOTOMETRIC=YCBCR', 'COMPRESS=JPEG', qualidade]
        elif tipo == 1:
            options = ['COMPRESS=JPEG', qualidade]
        elif tipo == 2:
            options = ['PHOTOMETRIC=YCBCR', 'COMPRESS=JPEG']

        if tiled:
            options += ['TILED=YES']

        topts = gdal.TranslateOptions(creationOptions=options)

        feedback.pushInfo(self.tr('Compressing...', 'Comprimindo...'))
        outds = gdal.Translate(RGB_Output, RasterIN, options=topts)

        feedback.pushInfo(
            self.tr('Operation completed successfully!',
                    'Operação finalizada com sucesso!'))
        feedback.pushInfo('Leandro França - Eng Cart')
        self.CAMINHO = RGB_Output
        self.CARREGAR = Carregar
        return {self.RasterOUT: RGB_Output}
Esempio n. 24
0
    def batch_create_cog(self, list_of_files, out_dir):
        """
        Create cloud optimized geotiffs.

        :param list_of_files:   A list of input files.
        :param out_dir:         Output location.
        """

        # create gdal_translate command string
        trans_str = (f'-co TILED=YES '
                     f'-co COPY_SRC_OVERVIEWS=YES '
                     f'-co COMPRESS={self.compress_method} '
                     f'-co NUM_THREADS=ALL_CPUS '
                     f'-co BLOCKXSIZE={str(self.blockxsize)} '
                     f'-co BLOCKYSIZE={str(self.blockysize)}')

        # parse command line syntax to be passed to translate options
        tp = gdal.ParseCommandLine(trans_str)

        # pass parsed string to TranslateOptions object
        trans_opt = gdal.TranslateOptions(tp)

        # define output path for cloud optimized geotiffs
        out = os.path.join(out_dir, 'COG')
        os.mkdir(out)  # make the dir
        os.chdir(out)  # navigate to dir

        # loop the files and convert
        for file in tqdm(list_of_files):
            out_name = f'{os.path.splitext(os.path.basename(file))[0]}.tif'
            # if file already exists, pass
            if os.path.exists(out_name):
                continue

            # make COGS
            try:
                gdal.Translate(out_name, file, options=trans_opt
                               )  # pass translate options to gdal.Translate()

            # log any errors encountered
            except Exception as e:
                with open(os.path.join(out, 'COG_creation_errors.txt'),
                          'a+') as err_file:
                    err_file.write(f'{file}\t{e}\n')
Esempio n. 25
0
    def create_translate_options(self):
        """
        Create translate options object.

        :return: gdal_translate options.
        """

        # amend gdal command string for jpeg
        if self.compress_method == 'JPEG':
            self.set_jpeg_quality()

        # Create gdal_translate command options
        trans_str = (f'-of GTiff -a_srs EPSG:{str(self.epsg)} '
                     f'-co PREDICTOR={str(self.predictor)} -q '
                     f'-co TILED=YES -co NUM_THREADS=ALL_CPUS '
                     f'-co COMPRESS={self.compress_method} '
                     f'-co ZLEVEL={str(self.compress_level)}')
        # pass parsed string to TranslateOptions object
        return gdal.TranslateOptions(gdal.ParseCommandLine(trans_str))
Esempio n. 26
0
    def convert2xyz(self, del_temp=True):
        """
        Translates the gdal raster object to a numpy array of xyz coordinates.
        """
        path_dest = 'topo.xyz'
        print('storing converted file...')
        shape = self.dem_zval.shape
        if len(shape) == 3:
            shape = shape[1:]
        gdal.Translate(path_dest, self.dem, options=gdal.TranslateOptions(options=['format'], format="XYZ"))

        xyz = pn.read_csv(path_dest, header=None, sep=' ').values
        self.values_3D = xyz.reshape((*shape, 3), order='C')

        # This is for 3D going from xyz to ijk
        self.values_3D = self.values_3D.swapaxes(0, 1)
        self.values_3D = np.flip(self.values_3D, 1)

        return self.values_3D
Esempio n. 27
0
    def _setReference(self, rasterFile, originalRasterFile, reference):

        if reference is not None:
            ref_x = reference[0]
            ref_y = reference[1]
            ref_phase = self._get_ref_phase(rasterFile, ref_x, ref_y)
        else:
            ref_phase = 0.0

        ds = gdal.Open(rasterFile, gdal.GA_Update)
        ds.GetRasterBand(1).SetOffset(ref_phase)
        ds = None

        ##Translate to complex source

        tempVRT2 = rasterFile + ".temp"
        opts = gdal.TranslateOptions(format='VRT', bandList=[1], unscale=True)
        gdal.Translate(tempVRT2, rasterFile, options=opts)
        updateComplexSource(tempVRT2, originalRasterFile, self.xSize)
        return tempVRT2
Esempio n. 28
0
    def resample_tiff(tiff_path, out_tiff_path, cell_size, resample_algo= 'near',
                      res_format = 'GTiff'):
        """
        重采样
        :param tiff_path: 输入 tiff
        :param out_tiff_path: 输出 tiff
        :param cell_size: 像元大小
        :param resample_algo: 重采样方法 near, cubic, bilinear 等
        :param res_format: 返回类型, GTiff 输出为文件, MEM 输出为临时文件
        :return:
        """

        if isinstance(cell_size, int) or isinstance(cell_size, float):
            xy_res = (cell_size, cell_size)
        else:
            xy_res = cell_size

        translate_option = gdal.TranslateOptions(xRes=xy_res[0], yRes=xy_res[1], resampleAlg=resample_algo,
                                                 format=res_format)
        return gdal.Translate(out_tiff_path, tiff_path, options=translate_option)
Esempio n. 29
0
def take_looks_gdal2(
    infile,
    outfile,
    fmt="GTiff",
    xlooks=None,
    ylooks=None,
    noData=None,
    method="average",
):
    """
    infile - Input file to multilook
    outfile - Output file to multilook
    fmt - Output format
    xlooks - Number of looks in x/range direction
    ylooks - Number of looks in y/azimuth direction
    """
    import gdal

    ds = gdal.Open(infile, gdal.GA_ReadOnly)

    # Input file dimensions
    xSize = ds.RasterXSize
    ySize = ds.RasterYSize

    # Output file dimensions
    outXSize = xSize // xlooks
    outYSize = ySize // ylooks

    # Set up options for translation
    gdalTranslateOpts = gdal.TranslateOptions(
        format=fmt,
        width=outXSize,
        height=outYSize,
        srcWin=[0, 0, outXSize * xlooks, outYSize * ylooks],
        noData=noData,
        resampleAlg=method,
    )

    # Call gdal_translate
    gdal.Translate(outfile, ds, options=gdalTranslateOpts)
    ds = None
    def _write_tiff(self, array, variable_name, dimT, meta):

        path_tempo_file = os.path.join(
            self.saving_path,
            'TempoGFstack_' + variable_name + '_crop_2019.tif')
        with rasterio.open(path_tempo_file, 'w', **meta) as dst:
            for id in range(dimT):
                dst.write_band(id + 1, array[id, :, :].astype(np.float32))
        del array
        src_ds = gdal.Open(path_tempo_file)
        topts = gdal.TranslateOptions(
            format='GTiff',
            outputType=gdal.GDT_Float32,
            creationOptions=['COMPRESS=LZW', 'GDAL_PAM_ENABLED=NO'],
            bandList=list(range(1, src_ds.RasterCount)))  # gdal.GDT_Byte

        gdal.Translate(os.path.join(
            self.saving_path, 'GFstack_' + variable_name + '_crop_2019.tif'),
                       src_ds,
                       options=topts)
        os.remove(path_tempo_file)