将浮点数数组保存为图像(使用EXR格式)

6
以下代码无法正常工作,它在将图像写入磁盘之前会将值转换为 np.uint8。
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

作为额外的奖励,这份文档非常不友好。
$ pydoc cv2.imwrite
Help on built-in function imwrite in cv2:

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

没有说明参数应该是什么...

我该如何将包含浮点值的数组保存为EXR格式?(使用OpenCV)

2个回答

6

imageio可以保存任何数据格式的EXR文件(同时还支持大量其他图像格式)。它是读写大多数图像的救星。

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

1
非常有帮助(+1)。根据此页面上的说明https://imageio.readthedocs.io/en/latest/format_exr-fi.html#exr-fi,我不得不下载“freeimage二进制文件”,以使`imwrite`命令正常工作。尽管我仍在努力弄清楚为什么加载保存的文件后值会略微改变(例如,在相同的数组位置中,1.0653863变为1.0654297)。 - AlexK
如果您看到了轻微的值变化,我不确定这一点,但很可能EXR不是无损格式(尽管在视觉上您永远不应该观察到任何差异)。 - Overdrivr
这可能只是一个非常重要的侧记: 上面的代码不再直接工作,因为np.random.uniform()创建了一个float64数组。这种格式不受freeimage库支持。因此,我建议进行编辑: arr = arr.astype("float32") 解决问题。 - benschbob91
1
以上代码给我一个错误:ValueError:在单图像模式下找不到写入指定文件的格式。 - Jäger

0
你可以尝试以下代码:
``` arr = cv2.imread("output.exr", cv2.IMREAD_UNCHANGED).astype(np.float32) ```

这不起作用是因为问题出现在导出时,而不是在加载过程中。我已经找到了一个解决方法,请参见我的其他问题。 - Overdrivr
2
也许你应该在这里添加一个链接到你的其他问题。 - Nagabhushan S N

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接