Re: Convert image to grayscale

[email protected] (Søren Sandmann)
Newsgroups gmane.comp.lib.cairo
Message-ID <[email protected]>
Joaquin Cuenca Abela <[email protected]> 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
-- 
cairo mailing list
[email protected]
http://lists.cairographics.org/mailman/listinfo/cairo
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.