Thank you both for this, very helpful.

-Matt

From: Idan Miara <i...@miara.com>
Sent: April 21, 2022 11:18 PM
To: Mike Taves <mwto...@gmail.com>
Cc: Matt.Wilkie <matt.wil...@yukon.ca>; gdal dev <gdal-dev@lists.osgeo.org>
Subject: Re: [gdal-dev] Convert to min containing bit depth?

Computing the min value is also requited if you have negative values and could 
also be useful If you wanted to optimize that method further by utilising the 
offset parameter (and or the scale, but computing the right combination for an 
optimize lossless compression could be more expensive).

On Fri, 22 Apr 2022, 06:05 Mike Taves, 
<mwto...@gmail.com<mailto:mwto...@gmail.com>> wrote:
On Fri, 22 Apr 2022 at 07:05, 
<matt.wil...@yukon.ca<mailto:matt.wil...@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.
_______________________________________________
gdal-dev mailing list
gdal-dev@lists.osgeo.org<mailto:gdal-dev@lists.osgeo.org>
https://lists.osgeo.org/mailman/listinfo/gdal-d<https://can01.safelinks.protection.outlook.com/?url=https%3A%2F%2Flists.osgeo.org%2Fmailman%2Flistinfo%2Fgdal-dev&data=05%7C01%7CMatt.Wilkie%40yukon.ca%7C530d4395252944fbff3a08da2427e83d%7C98f515313973490abb70195aa264a2bc%7C0%7C0%7C637862051196803406%7CUnknown%7CTWFpbGZsb3d8eyJWIjoiMC4wLjAwMDAiLCJQIjoiV2luMzIiLCJBTiI6Ik1haWwiLCJXVCI6Mn0%3D%7C3000%7C%7C%7C&sdata=Wxzbgz3TEIvRtrCiUvFSGc5CUoGIbeeCC8VXt1wtfuA%3D&reserved=0>e
 vroom
_______________________________________________
gdal-dev mailing list
gdal-dev@lists.osgeo.org
https://lists.osgeo.org/mailman/listinfo/gdal-dev

Reply via email to