[cairo] Convert image to grayscale

Joaquin Cuenca Abela joaquin at cuencaabela.com
Tue Sep 11 15:39:10 PDT 2012


On Tue, Sep 11, 2012 at 10:49 PM, Søren Sandmann <sandmann at cs.au.dk> wrote:
> 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.

not quite, the original pixels will be watered down by the alpha
twice, once when I compose the image with the black background, and
once again when I mask the result with the original image. Pure white
half transparent will end up being gray half transparent.

Is there any way to compose an image ignoring its alpha channel?

> 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



-- 
Joaquin Cuenca Abela -- presspeople.com: Fuentes de prensa y comunicados


More information about the cairo mailing list