Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I finally managed to convert the image respecting the original alpha using NumPy. I asked in the cairo mailing lists, but the only alternative that I got had the same problem that my version had (ie, it didn't respect the original alpha channel).</p> <p>Here is my solution:</p> <pre><code>import cairo import numpy import sys def convert_to_grayscale(img_in): """Convert an image to grayscale. Arguments: img_in: (cairo.ImageSurface) input image. Return: (cairo.ImageSurface) image in grayscale, in ARGB32 mode. Timing: ~100ms to convert an image of 800x800 Examples: # returns a B&amp;W image &gt;&gt;&gt; convert_to_grayscale(cairo.ImageSurface.create_from_png('test.png')) """ a = numpy.frombuffer(img_in.get_data(), numpy.uint8) w, h = img_in.get_width(), img_in.get_height() a.shape = (w, h, 4) assert sys.byteorder == 'little', ( 'The luminosity vector needs to be switched if we\'re in a big endian architecture. ' 'The alpha channel will be at position 0 instead of 3.') alpha = a[:, :, 3] alpha.shape = (w, h, 1) luminosity_float = numpy.sum(a * numpy.array([.114, .587, .299, 0]), axis=2) luminosity_int = numpy.array(luminosity_float, dtype=numpy.uint8) luminosity_int.shape = (w, h, 1) grayscale_gbra = numpy.concatenate((luminosity_int, luminosity_int, luminosity_int, alpha), axis=2) stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, w) assert stride == 4 * w, 'We need to modify the numpy code if the stride is different' img_out = cairo.ImageSurface.create_for_data(grayscale_gbra, cairo.FORMAT_ARGB32, w, h, stride) return img_out </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload