[cairo] Convert image to grayscale
Joaquin Cuenca Abela
joaquin at cuencaabela.com
Tue Sep 11 05:15:58 PDT 2012
Hi,
I'm trying to convert an image to grayscale in Python, and I got it
almost working drawing the luminance of the image over a white
background. It fails when the original image contains an alpha
channel.
The code that I'm using is:
def convert_to_grayscale(img_in):
img_out = img_in.create_similar(
cairo.CONTENT_COLOR_ALPHA, img_in.get_width(), img_in.get_height())
cr = cairo.Context(img_out)
cr.set_source_rgba(1, 1, 1, 1)
cr.paint()
cr.set_source_surface(img_in)
cr.set_operator(CAIRO_OPERATOR_HSL_LUMINOSITY)
cr.paint()
return img_out
# convert_to_grayscale(Image with rgba [20, 30, 40, 255]) -> [28, 28,
28, 255] as expected
# convert_to_grayscale(Image with rgba [10, 15, 20, 128]) -> [141,
141, 141, 25], but I want [14, 14, 14, 128]
I understand why I'm not getting what I want, but I can't figure out a
way to get what I want. I think I can get the results that I want if I
convert_to_grayscale my original image without its alpha channel, and
then I just put back the original alpha mask. But I can't figure out a
way to remove the alpha channel from my original image. This is what I
tried:
def remove_alpha(img_in):
img_out = cairo.ImageSurface(
cairo.FORMAT_RGB24, img_in.get_width(), img_in.get_height())
cr = cairo.Context(img_out)
cr.set_source_surface(img_in)
cr.paint()
return img_out
but I'm getting back exactly the same image that I put in. I
understand that the alpha values are not specified, and thus the
output image is free to have the same alpha values than the original
image had, but the premultiplied values for r, g and b should at least
change, and they are not change.
Can anybody suggest a way to convert to grayscale that will deal
correctly with semitransparent images, or a way to remove the alpha
information from a surface?
Thanks!
--
Joaquin Cuenca Abela -- presspeople.com: Fuentes de prensa y comunicados
More information about the cairo
mailing list