def as_mask(path, nodata=-9999):
'''
Converts all non-zero values in all bands to ones.
'''
rast, gt, wkt = as_array(path)
# Create a baseline raster
base = np.empty((1, rast.shape[-2], rast.shape[-1]))
base.fill(False)
# Case of multiband raster
if rast.ndim == 3:
# Update the mask for nonzero values in any band
for i in range(rast.shape[0]):
np.logical_or(base, (rast[i,...].ravel() > 0).reshape(rast[i,...].shape), out=base)
# Repeat the value of one (1) across the bands
np.place(rast, base.repeat(rast.shape[0], axis=0), (1,))
elif rast.ndim == 2:
# Create a single band (dim-3 array)
rast = rast.reshape((1, rast.shape[-2], rast.shape[-1]))
# Update the mask for nonzero values in any band
np.logical_or(base, (rast.ravel() > 0).reshape(rast.shape), out=base)
# Repeat the value of one (1) across the bands
np.place(rast, base, (1,))
else:
raise ValueError('Number of array dimensions must be 2 or 3')
# Replace the NoData values
rast[rast == nodata] = 0
return (rast, gt, wkt)
评论列表
文章目录