[英]Convert sRGB image to grayscale using OpenImageIO and Python
I can't find anywhere online or in documentation that explains clearly how to make this conversion using Python.我在网上或文档中找不到任何地方清楚地解释了如何使用 Python 进行这种转换。 In my situation I need to do it with OpenImageIO- I just need to feed it a path and save out the converted image, and ideally it would be great to output a single channel grayscale image.
在我的情况下,我需要用 OpenImageIO 来做——我只需要给它一个路径并保存转换后的图像,理想情况下它会很棒 output 单通道灰度图像。 Anyone know how?
有谁知道怎么做? Thanks in advance!
提前致谢!
The "averaging" approach is wrong, because your eyes are not uniformly sensitive to all wavelengths, so R, G, and B do not contribute equally to your perception of brightness. “平均”方法是错误的,因为您的眼睛对所有波长的敏感度不一致,因此 R、G 和 B 对您对亮度的感知的贡献不同。 That means that the grayscale image you get by averaging won't seem to have the same relative brightnesses as the original color image.
这意味着您通过平均获得的灰度图像似乎与原始彩色图像具有相同的相对亮度。 Also, sRGB is not a linear encoding, so "average" (or any weighted sum) of the encoded value is not what you imagine it should be.
此外,sRGB 不是线性编码,因此编码值的“平均值”(或任何加权和)并不是您想象的那样。
The fully correct way to do this with OpenImageIO from Python is:使用 Python 中的 OpenImageIO 执行此操作的完全正确方法是:
import OpenImageIO as oiio
# Read the image, force it to be float for full precision
img = oiio.ImageBuf("input.jpg")
img.read(convert='float')
# linearize it -- this assumes sRGB, which jpeg always is
lin = oiio.ImageBufAlgo.colorconvert(img, "sRGB", "linear")
# generate a luminance image with proper channel weights
luma = oiio.ImageBufAlgo.channel_sum (img, (.2126, .7152, .0722))
# convert back to sRGB for proper jpeg output
luma = oiio.ImageBufAlgo.colorconvert(luma, "linear", "sRGB")
luma.write("luma.jpg")
If you're just interested in doing this from the command line (not Python), it's extra easy:如果您只是对从命令行(而不是 Python)执行此操作感兴趣,那么它会更加简单:
oiiotool --autocc rgb.jpg --chsum:weight=.2126,.7152,.0722 -o luma.jpg
(the autocc does the automatic linearizing upon input and back to sRGB upon output to jpeg) (autocc 在输入时自动线性化并在 output 到 jpeg 时返回 sRGB)
Note that in both cases, you're outputting a single channel image with the luminance.请注意,在这两种情况下,您都会输出具有亮度的单通道图像。 It's only a couple extra lines if you really need to convert it to an RGB image where R, G, and B are all equal.
如果您确实需要将其转换为 R、G 和 B 都相等的 RGB 图像,则只需多行几行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.