Search code examples
pythonpython-3.xopencvopencv3.0

Save float array to image (with EXR format)


The following code does not work, it converts values to np.uint8 before writing image to disk.

import cv2
import numpy as np
# Generate dummy gradient with float values
arr = np.arange(0,10,0.02)
arr = np.repeat(arr, arr.shape[0])
arr.reshape((500,500))
cv2.imwrite('output.exr',arr)
# At this point, returns True. Opening the image with OpenEXR 1.4 shows values have become UINT8 instead of Float
arr = cv2.imread('output.exr')
# Shape is (1000, 1000, 3)
print(arr[10,10])
array([0, 0, 0], dtype=uint8) # All float data is lost

As a little bonus, the documentation is very not helpful

$ pydoc cv2.imwrite
Help on built-in function imwrite in cv2:

cv2.imwrite = imwrite(...)
    imwrite(filename, img[, params]) -> retval

Doesn't say what the params should be...

How can I save an array with floating point values to EXR format ? (using OpenCV)


Solution

  • imageio can save EXR files in any data format, (and it also supports a large amount of other image formats).

    Pretty much a life saver for reading and writing most images:

    import numpy as np
    import imageio
    
    # Generate dummy random image with float values
    arr = np.random.uniform(0.0, 1.0, size=(500,500))
    
    # freeimage lib only supports float32 not float64 arrays
    arr = arr.astype("float32")
    
    # Write to disk
    imageio.imwrite('float_img.exr', arr)
    
    # Read created exr from disk
    img = imageio.imread('float_img.exr')
    
    assert img.dtype == np.float32