How can I make a halftone copy of a surface in pygame?

In pygame, I have a surface:

im = pygame.image.load('foo.png').convert_alpha()
im = pygame.transform.scale(im, (64, 64))

How do I get a halftone copy of an image or convert image data to grayscale? I have numpy.

+3
source share
2 answers

Use Surfarray and filter it with numpy or Numeric:

def grayscale(self, img):
    arr = pygame.surfarray.array3d(img)
    #luminosity filter
    avgs = [[(r*0.298 + g*0.587 + b*0.114) for (r,g,b) in col] for col in arr]
    arr = numpy.array([[[avg,avg,avg] for avg in col] for col in avgs])
    return pygame.surfarray.make_surface(arr)
+4
source

The easiest way is to iterate over all the pixels in your image and call .get_at (...) and .set_at (...).

This will be pretty slow, so in response to your implicit suggestion about using NumPy, check out http://www.pygame.org/docs/tut/surfarray/SurfarrayIntro.html . The concepts and most of the code are identical.

+2
source

All Articles