pyrsgis.raster.trim_array

pyrsgis.raster.trim_array(data_arr, remove='negative', return_clip_index=False)[source]

Trim raster array to remove NoData value at the edge

This function trims an array by removing the given unwanted value. Note that the function will trim array for the smallest possible bounding box outside which all the cells in the input array have the value equal to the value passed using remove parameter.

Parameters
data_arrarray

A 2D or 3D array to clip. Ideally this should be a raster array that has unimportant value at the edges (NoData cells in most cases).

removeinteger or float or string

The value to be considered as irrelevant at the edges. It can be a integer or a float number. An additional option ‘negative’ is also available that will treat negative values of the array as unnecessary.

return_clip_index: boolean

Whether to return the index used for clipping. If True, the function will return both, the clipped array and a list cointaining [x_min, y_min] and [x_max, y_max] representing column and row indexes.

Returns
trimmed_arrarray

A trimmed array.

Examples

>>> from pyrsgis import raster
>>> infile = r'E:/path_to_your_file/your_file.tif'
>>> ds, data_arr = raster.read(infile)
>>> new_arr = raster.trim_array(data_arr, remove=-9999)
>>> print('Shape of the input array:', data_arr.shape)
>>> print('Shape of the trimmed array:', new_arr.shape)
Shape of the input array: (15000, 15900)
Shape of the trimmed array: (7059, 7685)

In the above example a raster file which was masked using a polygon but the option ‘match extent of the raster with extent of the input polygon’ was disabled has been used for demonstration. Although this is a classic example of observing unnecessary padding at the edges of a raster file, there can be many more reason for the same. In this particular case, useful values were only towards a corner of the raster surround by NoData cells. Hence, the actual extent of the file was much larger (and unnecessary).

In a similar fashion, any other value can be used to trim the raster array. Using the ‘negative’ option for the remove parameter will treat negative values as unnecessary. It should be noted that cells within the ‘meaningful’ region of the raster that have value same as the remove value will remain unaffected by the trimming process.