Skip to content Skip to sidebar Skip to footer

How To Save Floating-point Pixel Values In Image File

I want to save floating-point numbers as pixels in an image file. I am currently working in OpenCV-python, but I had also tried it with Pillow (PIL). Both packages convert float pi

Solution 1:

Raster images are normally stored as integer values only. Instead save the numpy array directly like so

x = numpy.array([1, 2, 3])
withopen('x.npy', 'wb') as f:
    numpy.save(f, x)

Then load the variable back like so

x = numpy.load('x.npy')

Other alternatives include

  • Save one or more GRAY16 png images, with your floats multiplied and truncated.
  • Use the Netpbm format supporting floats.
  • Save a pickle.

Solution 2:

The behavior you observe depends on the file format in which you save the image. Few image formats have a specification for floating-point pixel values. Though some do, first and foremost TIFF.

To demonstrate the desired behavior with a TIFF image writer, consider the following script. It uses the versatile image input/output library ImageIO, which relies on PILlow as one of its back-ends:

# Use Stack Overflow logo as sample image.import imageio
logo = 'https://cdn.sstatic.net/Sites/stackoverflow/img/logo.png'
image = imageio.imread(logo)

# Normalize to 1. Pixel values are now floating-point.
image = image / image.max()

# Save as image file and read back in.format = 'tiff'
imageio.imwrite(f'image.{format}', image)
print(f'wrote: {image.dtype}')
image = imageio.imread(f'image.{format}')
print(f'read:  {image.dtype}')

The output of that script is:

wrote: float64
read:  float64

If, on the other hand, you change the format to PNG (format = 'png' in the code), the output is:

Lossy conversion from float64 to uint8. Range [0, 1].
Convert image to uint8 prior to saving to suppress this warning.
wrote: float64
read:  uint8

Post a Comment for "How To Save Floating-point Pixel Values In Image File"