myimagelib.myImageLib.to8bit

myimagelib.myImageLib.to8bit(img)

Auto adjust the contrast of an image and convert it to 8-bit. The input image dtype can be float or int of any bit-depth. The function handles spuriously bright pixels by clipping the image with the 5-sigma rule (inspired by processing active nematics data). The function also works with images containing NaN values.

Parameters:

img (2D numpy.array) – mono image of any dtype

Returns:

8-bit image with contrast enhanced.

Return type:

2D numpy.array (uint8)

>>> from myimagelib import to8bit
>>> img8 = to8bit(img)

Edit

  • Feb 27, 2023 – change img.max() to np.nanmax(img) to handle NaN values.

  • Mar 16, 2023 – use mean and std to infer upper bound. This makes the function more stable to images with spurious pixels with extremely large intensity.

  • Mar 17, 2023 – using upper bound that is smaller than the maximal pixel intensity causes dark “patches” in the rescaled images due to the data type change to “uint8”. The solution is to clip the images with the determined bounds first, then apply the data type conversion. In this way, the over exposed pixels will just reach the saturation value 255.

  • Feb 27, 2025 – convert the image to float32 before processing, to avoid overflow when the image is of int8 type when performing clipping.