Crop image DN range, gdal_clip2range.py

I just wanted to push this out there in case it might be useful to others. There are so many times when I run into an image with extraneous pixel values outside the normal range of data. This could be from an image with more than one special pixel value (like ISIS) or simply from noise. This issue arose when I recently tried to help a colleague set the values outside 0 to 1 to NoDATA. This was for an I/F (reflectance) 32bit lunar image.

Seems like there should be a simple method to do this without writing code, but I have never been able to find a method. Maybe someone has a better method (and yes ISIS does also have this capability). Anyway, the routine below can clip pixel values to a defined data range. It can also help if the input data does not have a NoData value defined in the header. So, you can run this to set a NoData value while clipping out those extraneous DN values.

Requires a gdal Python environment to run. I recommend Anaconda or Miniconda and the commands below.

conda create -n gdal3
conda activate gdal3
conda install -c conda-forge gdal

Into this environment, you can also conda install tuiview for a simple image viewer or qgis for a robust GIS application. for example:
conda install -c conda-forge gdal tuiview

Python code to clip pixel value range: https://github.com/thareUSGS/GDAL_scripts/tree/main/gdal_clip2range

gdal_clip2range.py

description: This routine was written to clip pixel values to a defined range. All values outside that range will be set to a single NoData value. If there exists a NoDATA value in the input file, it is best to not set the optional “output_noData” parameter. If there is not a NoData value set in the input file, then you should define the “output_noData” parameter for the output file.

Usage:

python gdal_clip2range.py in.file output.tif min_valid max_valid [output_noData]

python gdal_clip2range.py input.tif output.tif -100.5 500.2

This example will set pixel values less than -100.5 and greater than 500.2 to NoDATA. It will maintain the original NoDATA value to the output file.

or

reminder: only set the optional “output_noData” parameter on the command-line, if the original file has none set. For example:

python gdal_clip2range.py input.tif output.tif 0 1 0

This example will clip any pixels outside the range of 0 to 1 to NoDATA. It will also define the NoDATA in the output file to 0. This example might be used to set a valid range for I/F 32bit floating point image.