pyrsgis.raster.trim

pyrsgis.raster.trim(ds, data_arr, remove)[source]

Trim raster array and modify ds

This function trims the raster array by removing the given unwanted value and update datasource object accordingly. 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
dsdatasource object

A datasource object of the raster. Ideally, the datasource should be the same as one generated by the pyrsgis.raster.read function.

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.

Returns
new_dsdatasource object

The modified ds object that can be used to export the trimmed raster.

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_ds, new_arr = raster.trim(ds, 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.

The trimmed raster can be exported with the following line:

>>> raster.export(new_arr, new_ds, r'E:/path_to_your_file/trimmed_file.tif')