Last active
March 5, 2020 19:48
-
-
Save vincentsarago/f1adeae24cf38c8862cc7d8ab8db9cc4 to your computer and use it in GitHub Desktop.
convert multiple nodata values to 0
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""cli""" | |
import click | |
import numpy | |
import rasterio | |
from rasterio.rio import options | |
class NodataParamType(click.ParamType): | |
"""Nodata type.""" | |
name = "nodata" | |
def convert(self, value, param, ctx): | |
"""Validate and parse band index.""" | |
try: | |
if value.lower() == "nan": | |
return numpy.nan | |
elif value.lower() in ["nil", "none", "nada"]: | |
return None | |
else: | |
return float(value) | |
except (TypeError, ValueError): | |
raise click.ClickException("{} is not a valid nodata value.".format(value)) | |
@click.command() | |
@options.file_in_arg | |
@options.file_out_arg | |
@click.option( | |
"--nodata", | |
type=NodataParamType(), | |
metavar="NUMBER|nan", | |
help="Set nodata masking values for input dataset.", | |
multiple=True, | |
) | |
def main(input, output, nodata): | |
"""Read tile.""" | |
with rasterio.open(input) as src_dst: | |
profile = src_dst.profile.copy() | |
profile["nodata"] = 0 | |
arr = src_dst.read() | |
for n in nodata: | |
arr[arr == n] = 0 | |
with rasterio.open(output, "w", **profile) as out_dst: | |
out_dst.write(arr) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment