Advertisement
Guest User

Untitled

a guest
Feb 21st, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. import cairo
  2. CAIRO_OPERATOR_HSL_LUMINOSITY = 28 # my py2cairo seems outdated
  3.  
  4. def convert_to_grayscale(img_in):
  5. img_out = img_in.create_similar(
  6. cairo.CONTENT_COLOR_ALPHA, img_in.get_width(), img_in.get_height())
  7. cr = cairo.Context(img_out)
  8. cr.set_source_rgba(1, 1, 1, 1)
  9. cr.paint()
  10. cr.set_source_surface(img_in)
  11. cr.set_operator(CAIRO_OPERATOR_HSL_LUMINOSITY)
  12. cr.paint()
  13.  
  14. return img_out
  15.  
  16. import cairo
  17. import numpy
  18. import sys
  19.  
  20.  
  21. def convert_to_grayscale(img_in):
  22. """Convert an image to grayscale.
  23.  
  24. Arguments:
  25. img_in: (cairo.ImageSurface) input image.
  26.  
  27. Return:
  28. (cairo.ImageSurface) image in grayscale, in ARGB32 mode.
  29.  
  30. Timing:
  31. ~100ms to convert an image of 800x800
  32.  
  33. Examples:
  34. # returns a B&W image
  35. >>> convert_to_grayscale(cairo.ImageSurface.create_from_png('test.png'))
  36. """
  37. a = numpy.frombuffer(img_in.get_data(), numpy.uint8)
  38. w, h = img_in.get_width(), img_in.get_height()
  39. a.shape = (h, h, 4)
  40.  
  41. assert sys.byteorder == 'little', (
  42. 'The luminosity vector needs to be switched if we're in a big endian architecture. '
  43. 'The alpha channel will be at position 0 instead of 3.')
  44. alpha = a[:, :, 3]
  45. alpha.shape = (w, h, 1)
  46.  
  47. luminosity_float = numpy.sum(a * numpy.array([.114, .587, .299, 0]), axis=2)
  48. luminosity_int = numpy.array(luminosity_float, dtype=numpy.uint8)
  49. luminosity_int.shape = (w, h, 1)
  50. grayscale_gbra = numpy.concatenate((luminosity_int, luminosity_int, luminosity_int, alpha),
  51. axis=2)
  52. stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_ARGB32, w)
  53. assert stride == 4 * w, 'We need to modify the numpy code if the stride is different'
  54. img_out = cairo.ImageSurface.create_for_data(grayscale_gbra, cairo.FORMAT_ARGB32, w, h, stride)
  55.  
  56. return img_out
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement