[gdal-dev] Convert to min containing bit depth?

Mike Taves mwtoews at gmail.com
Thu Apr 21 20:04:31 PDT 2022


On Fri, 22 Apr 2022 at 07:05, <Matt.Wilkie at yukon.ca> wrote:
>
> Idea for a small but useful python tool: scan image for min/max values and convert to smallest possible bit depth without losing values. Surely someone has done something like this already. Any suggestions for where to look for prior art?

This is driver-specific, as certain formats expect multiples of 2
(e.g.) NBITS=1/2/4. But for GTiff, what I typically use in a script is
to find the maximum value, then use "ceil(log(maxval, 2))" to get the
number of bits, e.g.:

from math import ceil, log
from osgeo import gdal

maxval = 17  # for example
nbits = ceil(log(maxval, 2))  # 5

drv = gdal.GetDriverByName("GTiff")
opts = [f"NBITS={maxval}"]
ds = drv.Create(fname, nx, ny, 1, gdal.GDT_Byte, opts)
...

similar can be done with rasterio, passing the keyword
"rasterio.open(fname, 'w', ..., nbits=nbits)"

For the drivers that expect NBITS as a multiple of 2:

nbits = 2**ceil(log(nbits, 2))

If nbits is greater than 8, then UInt16 or UInt32 may be required, as
supported by the driver.


More information about the gdal-dev mailing list