def open_gdal_masks(self, shape_file, temp_dir): gdal_masks = {} for mask_key, mask_name in self.TheiaMaskDict.items(): mask_file = [file for file in self.masks_folder.glob(mask_name)][0] gdal_masks.update({mask_key: gdal.Open(mask_file.as_posix())}) if shape_file: opt = gdal.WarpOptions(cutlineDSName=shape_file, cropToCutline=True, srcNodata=-9999, dstNodata=-9999, outputType=gdal.GDT_Int16) for mask_key, mask_ds in gdal_masks.items(): dest_name = (temp_dir / mask_key).as_posix() clipped_mask_ds = gdal.Warp(destNameOrDestDS=dest_name, srcDSOrSrcDSTab=mask_ds, options=opt) clipped_mask_ds.FlushCache() gdal_masks.update({mask_key: clipped_mask_ds}) return gdal_masks
def clip_bands(self, bands_to_clip, ref_band, temp_dir): opt = gdal.WarpOptions(cutlineDSName=self.shape_file, cropToCutline=True, srcNodata=-9999, dstNodata=-9999, outputType=gdal.GDT_Float32) for band in bands_to_clip: if band not in self._clipped_gdal_bands and band in self.gdal_bands: dest_name = (temp_dir / (band + '.tif')).as_posix() self._clipped_gdal_bands.update({ band: gdal.Warp(destNameOrDestDS=dest_name, srcDSOrSrcDSTab=self.gdal_bands[band], options=opt) }) self.gdal_bands[band] = self._clipped_gdal_bands[band] self.gdal_bands[band].FlushCache() self._ref_band_name = ref_band self._ref_band = self.gdal_bands[ref_band] self.temp_dir = temp_dir return
def open_gdal_masks(self, shape_file, temp_dir): mask_file = [file for file in self.masks_folder.glob('*pixel_qa.tif')][0] gdal_mask = gdal.Open(mask_file.as_posix()) if shape_file: opt = gdal.WarpOptions(cutlineDSName=shape_file, cropToCutline=True, srcNodata=-9999, dstNodata=-9999, outputType=gdal.GDT_Int16) dest_name = (temp_dir / 'qa_cliped').as_posix() clipped_mask_ds = gdal.Warp(destNameOrDestDS=dest_name, srcDSOrSrcDSTab=gdal_mask, options=opt) clipped_mask_ds.FlushCache() gdal_mask = clipped_mask_ds return gdal_mask
def read_gdal_ds(file, shape_file, temp_dir): """ Read a GDAL dataset clipping it with a given shapefile, if necessary :param file: Filepath of the GDAL file (.tif, etc.) as Pathlib :param shape_file: file path of the shapefile :param temp_dir: file path of the temporary directory :return: GDAL dataset """ gdal_mask = gdal.Open(file.as_posix()) if gdal_mask and shape_file: opt = gdal.WarpOptions(cutlineDSName=shape_file, cropToCutline=True, srcNodata=-9999, dstNodata=-9999, outputType=gdal.GDT_Int16) dest_name = (temp_dir / (file.stem + '_clipped')).as_posix() clipped_mask_ds = gdal.Warp(destNameOrDestDS=dest_name, srcDSOrSrcDSTab=gdal_mask, options=opt) clipped_mask_ds.FlushCache() gdal_mask = clipped_mask_ds return gdal_mask