tools.py 1.35 KiB
# -*- coding: utf-8 -*-
"""
Created on 14 september 2019

@author: Marc Lang
"""


import pprint
import os

def mask_and_crop(in_img_file, mask_file, nodata, out_masked_file, crop=True):
    """
    Set a nodata value where pixels of image to mask are not included in the
    vector mask file entities. Based on gdalwarp.

    Parameters
    ----------
    in_img_file : str
        Path of input image file raster.
    mask_file : str
        Path of input vector mask file.
    nodata : float
        Nodata value to set.
    out_masked_file : str
        Path of output masked image file
    crop : bool,
        If True, bbox of masked file will be fit to the mask one. If False,
        bbox of output file will not change. Default's to True.

    Limitations
    -----------
    Can be issues when trying to set a nodata value whose type differs from
    the input image file.
    """


    crop = ' -crop_to_cutline' if crop else ''

    command_pattern = ('gdalwarp -dstnodata {nodata} -cutline {mask_file}' +
                       '{crop} {in_img_file} {out_masked_file}')

    command = command_pattern.format(in_img_file=in_img_file,
                                     mask_file=mask_file, nodata=nodata,
                                     out_masked_file=out_masked_file,
                                     crop=crop)
    pprint.pprint(command)
    os.system(command)