Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PIL to make all white pixels transparent?

I'm trying to make all white pixels transparent using the Python Image Library. (I'm a C hacker trying to learn python so be gentle) I've got the conversion working (at least the pixel values look correct) but I can't figure out how to convert the list into a buffer to re-create the image. Here's the code

img = Image.open('img.png') imga = img.convert("RGBA") datas = imga.getdata()  newData = list() for item in datas:     if item[0] == 255 and item[1] == 255 and item[2] == 255:         newData.append([255, 255, 255, 0])     else:         newData.append(item)  imgb = Image.frombuffer("RGBA", imga.size, newData, "raw", "RGBA", 0, 1) imgb.save("img2.png", "PNG") 
like image 823
haseman Avatar asked Apr 19 '09 17:04

haseman


People also ask

How do I get rid of white pixels?

Choose Layer > Matting > Defringe. For starters, try a setting of 1 pixel and click OK. At this point Photoshop goes off and replaces the white edge pixels with a mixture of the colours in the background and the colours in your object. If 1 pixel doesn't do the trick, then try Defringe again with either 2 or 3 pixels.


1 Answers

You need to make the following changes:

  • append a tuple (255, 255, 255, 0) and not a list [255, 255, 255, 0]
  • use img.putdata(newData)

This is the working code:

from PIL import Image  img = Image.open('img.png') img = img.convert("RGBA") datas = img.getdata()  newData = [] for item in datas:     if item[0] == 255 and item[1] == 255 and item[2] == 255:         newData.append((255, 255, 255, 0))     else:         newData.append(item)  img.putdata(newData) img.save("img2.png", "PNG") 
like image 140
cr333 Avatar answered Sep 28 '22 05:09

cr333