[cairo] Convert image to grayscale

Søren Sandmann sandmann at cs.au.dk
Tue Sep 11 13:49:21 PDT 2012


Joaquin Cuenca Abela <joaquin at cuencaabela.com> writes:

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

You may be able to get what you want by using HSL_LUMINOSITY against a
solid black background, which will produce a gray scale image without
alpha, and then use that image as the source in a mask() operation with
the original image as the mask to put the alpha channel back.

I guess what you really want is 'white' ATOP 'image' with a blend mode
of HSL_COLOR. Unfortunately, cairo only offers blend modes with the OVER
operator.


Søren


More information about the cairo mailing list