Skip to content

Instantly share code, notes, and snippets.

@perrygeo
Last active August 8, 2018 03:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perrygeo/3dde6210473275fccf7a6d90843b0d4c to your computer and use it in GitHub Desktop.
Save perrygeo/3dde6210473275fccf7a6d90843b0d4c to your computer and use it in GitHub Desktop.
Convert RGBA to RGB with GeoTIFF mask
import rasterio
import click
@click.command()
@click.argument("rgba_path")
@click.argument("out_path")
@click.option("--internal-mask/--external-mask", default=True)
@click.option("--ycbcr", default=False, is_flag=True)
@click.option("--use-blocks/--no-use-blocks", default=True)
def rgba_to_masked(rgba_path, out_path, internal_mask, ycbcr, use_blocks):
"""Converts an RGBA tif to RGB with mask"""
with rasterio.open(rgba_path) as src:
profile = src.profile
assert profile['count'] == 4
profile['count'] = 3
if ycbcr:
profile['compress'] = 'JPEG'
profile['photometric'] = 'ycbcr'
with rasterio.Env(GDAL_TIFF_INTERNAL_MASK=internal_mask):
with rasterio.open(out_path, 'w', **profile) as dst:
if use_blocks:
for _, win in src.block_windows():
dst.write(
src.read((1, 2, 3), window=win),
window=win)
else:
dst.write(src.read((1, 2, 3)))
# Mask can't be written partially, ie no block windows
# See https://github.com/mapbox/rasterio/issues/895
dst.write_mask(src.read(4))
if __name__ == "__main__":
rgba_to_masked()
@TsybusovDmitriy
Copy link

Hi! Could you please tell the equivalent with rasterio.Env (GDAL_TIFF_INTERNAL_MASK = internal_mask): in with C#?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment