[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

Re: [pygame] using pil to covert rgb into grayscale



If you are going to roll your own, at least use the standard luminance calculation:

L = 0.3 * red + 0.59 * green + 0.11 * blue

hth,

-Casey

On Apr 29, 2010, at 9:22 AM, Jason M. Marshall wrote:

> Stas,
>  
> This is simple and it works.
>  
> Jason
>  
> def convert_to_gs(surf):
>     width, height = surf.get_size()
>     for x in range(width):
>         for y in range(height):
>             red, green, blue, alpha = surf.get_at((x, y))
>             average = (red + green + blue) // 3
>             gs_color = (average, average, average, alpha)
>             surf.set_at((x, y), gs_color)
> 
> From: stas zytkiewicz <stas.zytkiewicz@xxxxxxxxx>
> To: pygame-users@xxxxxxxx
> Sent: Thu, April 29, 2010 8:56:37 AM
> Subject: [pygame] using pil to covert rgb into grayscale
> 
> Hello, I'm trying to convert a RGB image into a grayscaled image
> using PIL but pygame keeps throwing this error:
> "ValueError: Buffer length does not equal format and resolution size"
> 
> Why this code doesn't work, I have no idea :-(
> 
> ('surf' is a pygame.Surface)
> 
> pilimg = Image.fromstring('RGBA', surf.get_size(),
> pygame.image.tostring(surf, 'RGBA'))
> pilimg = pilimg.convert('L')
> pilimg.show()# it's grayscaled
> surf_gr = pygame.image.fromstring(pilimg.tostring(), pilimg.size, 'RGBA')
> 
> OK, I know the last 'RGBA' probably isn't correct but 'P' isn't either
> nor is one of the other
> possible modes.
> 
> Can someone explain to me how to properly convert a RGB into grayscale, with
> or without PIL.
> 
> Thanks,
> Stas
> 
> -- 
> Free-source educational programs for schools
> http://www.schoolsplay.org  and http://wiki.laptop.org/go/Schoolsplay
> http://gvr.sf.net and http://wiki.laptop.org/go/Guido_van_Robot
> 
>