简体   繁体   中英

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. 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. 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. 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.

The fully correct way to do this with OpenImageIO from Python is:

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:

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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