Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set alpha value of a pixel in Python

I'm trying to edit an image in a way such that all white pixels are converted to transparent pixels (with 0 alpha value). Basically I want to get rid of the background.

I know of the image file's im.putpixel method, but from my experimentation this does not allow me to set alpha values. I tried the following:

for x in range(90):
    for y in range(80, 90):
        im.putpixel((x, y), (0, 0, 0, 0))

and just got blackness in the specified area, not transparency. Is there a way to alter the alpha value of a pixel? If so, how?

like image 770
mishaturnbull Avatar asked Feb 26 '15 23:02

mishaturnbull


People also ask

How is alpha value set?

To get α subtract your confidence level from 1. For example, if you want to be 95 percent confident that your analysis is correct, the alpha level would be 1 – . 95 = 5 percent, assuming you had a one tailed test. For two-tailed tests, divide the alpha level by 2.


1 Answers

It sounds like you are using python image library (PIL).

If so, you can just do something like this:

from PIL import Image
image = Image.open("<path to image file>").convert('RGBA')
pixeldata = list(image.getdata())

for i,pixel in enumerate(pixeldata):
    if pixel[:3] == (255,255,255):
        pixeldata[i] = (255,255,255,0)

image.putdata(pixeldata)
image.save("output.png")

That should generate something like this:

enter image description hereenter image description here

Of course, that's probably not exactly what you wanted. One thing you can do is set pixels to transparent when the color is close to white instead of exactly white. You can define a function like

def almostEquals(a,b,thres=5):
    return all(abs(a[i]-b[i])<thres for i in range(len(a)))

And replace the color checking line with:

if almostEquals(pixel[:3], (255,255,255):

To get something like this

enter image description hereenter image description here

Still some haloing/border artifacts but better.

In your case, with a simple black and white image, you may just want to set the alpha based on how white your pixels are (I often do this in photoshop). You can use one of the 3 color channels or even the average. Something like:

for i,pixel in enumerate(pixeldata):
    avg = int(sum(pixel[:3])/3.0)
    pixeldata[i] = (pixel[0],pixel[1],pixel[2],255-avg)

Would give you a result like this:

enter image description hereenter image description here

Still a minor halo, since we are still only changing alpha values, but much better. To fix even that, you could do something like set all pixels to black as well instead of just modifying the alpha.

Anyways, a long answer for a simple question, but hopefully that helps.

like image 75
lemonhead Avatar answered Oct 15 '22 12:10

lemonhead