def _recompress_image( input_image: rasterio.DatasetReader, output_fp: rasterio.MemoryFile, zlevel=9, block_size=(512, 512), ): """ Read an image from given file pointer, and write as a compressed GeoTIFF. """ # noinspection PyUnusedLocal block_size_y, block_size_x = block_size if len(input_image.indexes) != 1: raise ValueError( f"Expecting one-band-per-tif input (USGS packages). " f"Input has multiple layers {repr(input_image.indexes)}") array: numpy.ndarray = input_image.read(1) profile = input_image.profile profile.update( driver="GTiff", predictor=_PREDICTOR_TABLE[array.dtype.name], compress="deflate", zlevel=zlevel, blockxsize=block_size_x, blockysize=block_size_y, tiled=True, ) with output_fp.open(**profile) as output_dataset: output_dataset.write(array, 1) # Copy gdal metadata output_dataset.update_tags(**input_image.tags()) output_dataset.update_tags(1, **input_image.tags(1))
def npArrayToRasterioDataset(npArray, crs, affineTransform): height, width = npArray.shape npArray = npArray.reshape((1, height, width)) profile = { 'driver': 'GTiff', 'dtype': npArray.dtype, 'width': width, 'height': height, 'count': 1, 'crs': rioc.CRS.from_epsg(crs), 'transform': affineTransform, 'tiled': False, 'nodata': 0 } memfile = MemoryFile() dataset = memfile.open(**profile) dataset.write(npArray) dataset.close() return memfile.open()
def __init__( self, info: GeoRasterInfo, dst: Union[str, MemoryFile], blocksize: Optional[int] = None, bigtiff: Union[str, bool] = "auto", lock: bool = True, **extra_rio_opts, ): if blocksize is None: blocksize = 512 if bigtiff == "auto": # do bigtiff if raw raster is larger than 4GB bigtiff = info.raster_size() > (1 << 32) opts = dict( driver="GTiff", bigtiff=bigtiff, tiled=True, blockxsize=_adjust_blocksize(blocksize, info.width), blockysize=_adjust_blocksize(blocksize, info.height), compress="DEFLATE", zlevel=6, predictor=2, num_threads="ALL_CPUS", ) opts.update(info.gdal_opts()) opts.update(extra_rio_opts) mem: Optional[MemoryFile] = None self._mem_mine: Optional[MemoryFile] = None if isinstance(dst, str): if dst == ":mem:": mem = MemoryFile() out = mem.open(**opts) self._mem_mine = mem else: out = rasterio.open(dst, mode="w", **opts) else: mem = dst out = dst.open(**opts) self._mem = mem self._info = info self._out = out self._lock = threading.Lock() if lock else None