Topics

Throwing an error when result from mask operation is all nodata

me@...
 
Edited

So I've just been clipping some rasters to a shapefile and one thing I noticed was that if I manage to pull in a few edges of my raster that contain nodata then those get written to file. When there is no overlap at all on a mask operation  a Value Error will be thrown.

At the moment I'm doing something like this to ensure I don't write blank rasters to disk.

out_image, out_transform = rasterio.mask.mask(src, projected_aoi, crop=True)
unique_vals_in_out_raster = np.unique(out_image)
if len(unique_vals_in_out_raster) > 1 or unique_vals_in_out_raster[0] != src.nodata:
    // write the output to disk...


So I was wondering if there was value in adding another parameter to the mask operation that throw_err_on_empty.

Cheers
Rowan

Jonas
 
Edited

Hi Rowan,

I am not a maintainer, but I would definitely keep this kind of check outside of the function, since it is so easy for you as a user to perform and it would just be a line at the end of the function anyways (+ 5 or so for documentation).

You can simplify your solution and save some resources, though, by calling `rasterio.mask.mask(..., filled=False)`, which will return a masked array, and then use `if not np.all(out_image.mask)` as a check.

Best,
Jonas

me@...
 

You can simplify your solution and save some resources, though, by calling `rasterio.mask.mask(..., filled=False)`, which will return a masked array, and then use `if not np.all(out_image.mask)` as a check.
Thanks for the tip @Jonas , that does seem like a slightly neater way to do the check, I'm slowly having to remember my way back around numpy now that I'm entering raster world again :)

Sean Gillies
 

On Fri, Jan 4, 2019 at 2:13 AM <me@...> wrote:
You can simplify your solution and save some resources, though, by calling `rasterio.mask.mask(..., filled=False)`, which will return a masked array, and then use `if not np.all(out_image.mask)` as a check.
Thanks for the tip @Jonas , that does seem like a slightly neater way to do the check, I'm slowly having to remember my way back around numpy now that I'm entering raster world again :)

I, too, think that a new option for the function is not warranted here and endorse Jonas's solution.

--
Sean Gillies