1

I have a geotiff image that I am clipping to a geojson polygon using rasterio. When I load input the image in QGIS, it has an alpha band (4 bands total). rasterio says it only has 3 bands, which leads me to believe that the rasterio sees the alpha band as a dataset mask. I am using rasterio.mask.mask to clip the image to the polygon. The output of rasterio.mask.mask when written to a geotiff is a 3 band image without the alpha band. Is there a way to include the alpha band/dataset mask in the clipped image?

Here is my code:

src = rasterio.open('<input image path>')
output_meta = deepcopy(src.meta)
output_meta["driver"] = "GTiff"

masked_image, masked_image_transform = rasterio.mask.mask(src, [shape(<geojson geometry>)], all_touched=True, crop=True)

output_meta.update({
    "height": masked_image.shape[1],
    "width": masked_image.shape[2],
    "transform": masked_image_transform
})

with rasterio.open('<clipped image path>', 'w', **output_meta) as dest:
    dest.write(masked_image)
  • Do you have any other use for the alpha band than to act as a nodata mask? Do you also control partial opacity with alpha? – user30184 May 26 at 17:02
  • @user30184 I am just using it for the NoData mask/transparency in QGIS. However, my goal is for the clipped image to be as identical as possible to the original image, just limited to the extent of the input geometry. – Brian May 26 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.