简体   繁体   English

在 Python 中使用 OpenEXR 将 PIL 图像写入 EXR

[英]Write PIL image to EXR using OpenEXR in Python

I'm attempting to write a floating point PIL image object out to a channel in an EXR file using OpenEXR.我正在尝试使用 OpenEXR 将浮点 PIL 图像 object 写入 EXR 文件中的通道。

I can read EXR data into a PIL image fine:我可以很好地将 EXR 数据读入 PIL 图像:

import OpenEXR
import Imath
from PIL import Image
import numpy as np

exrPath = "path/to/image.exr"
exrFile = OpenEXR.InputFile(exrPath)

pt = Imath.PixelType(Imath.PixelType.FLOAT)
dw = curFile.header()['dataWindow']
size = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)

rgbf = [Image.frombytes("F", size, exrFile.channel(c, pt)) for c in ("R", "G", "B")]

I then run some operations over the PIL image data and want to save a single channel out as a new EXR.然后我对 PIL 图像数据运行一些操作,并希望将单个通道保存为新的 EXR。 This is what I have so far:这是我到目前为止所拥有的:

exrHeader = OpenEXR.Header(pilImage.size[0],pilImage.size[1])
exrHeader["channels"] = {"GRAY":Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT), 1, 1)}

exrOut = OpenEXR.OutputFile("path/to/new.exr", exrHeader)
exrOut.writePixels({"GRAY": np.array(pilImage).astype(np.float32).tostring()})

But I get this error:但我得到这个错误:

TypeError: Data for channel 'GRAY' should have size 67108864 but got 16777216

How do I convert a floating point PIL image to the correct format to write to a float EXR channel?如何将浮点 PIL 图像转换为正确的格式以写入浮点 EXR 通道?

I got it working but don't understand it completely yet.我得到了它的工作,但还不完全理解它。

npImage = np.squeeze(pilImage)
size = img.shape
exrHeader = OpenEXR.Header(size[1], size[0])

exrHeader['channels'] = {"GRAY":Imath.Channel(Imath.PixelType(Imath.PixelType.FLOAT), 1, 1)}

exrOut = OpenEXR.OutputFile("path/to/new.exr", exrHeader)
GRAY = (npImage[:,:]).astype(np.float32).tobytes()
exrOut.writePixels({'GRAY' : R})
exrOut.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM