Image Guru: Optimize PNG Transparency Function Python

I need to replace all white (ish) pixels in an PNG image with alpha transparency.

I use Python in AppEngine and therefore do not have access to libraries like PIL, imagemagick, etc. AppEngine has an image library, but it breaks down mainly into image resizing.

I found a great little pyPNG module and managed to bring down a little function that does what I need:

make_transparent.py

The pseudocode for the main loop will look something like this:

for each pixel:
    if pixel looks "quite white":
        set pixel values to transparent
    otherwise:
        keep existing pixel values

and (considering 8-bit values) "pretty white" will be:

where each r,g,b value is greater than "240" 
AND each r,g,b value is within "20" of each other

, , , . , ? (?)

, - / .

!

+5
4

- , :

new_pixels = []
for row in pixels:
    new_row = array('B', row)
    i = 0
    while i < len(new_row):
        r = new_row[i]
        g = new_row[i + 1]
        b = new_row[i + 2]
        if r>threshold and g>threshold and b>threshold:
            m = int((r+g+b)/3)
            if nearly_eq(r,m,tolerance) and nearly_eq(g,m,tolerance) and nearly_eq(b,m,tolerance):
                new_row[i + 3] = 0
        i += 4
    new_pixels.append(new_row)

slicen, ( ).

, , - , .

( , - ).

+1

, , , - .

, ( - , - , ).

( : =/)

+1

, . .

0

, , Python, .

Python , .

, , :

def make_transparent(pixel):
  if pixel looks "quite white": return transparent
  else: return pixel

newImage = [make_transparent(p) for p in oldImage]
0

All Articles