5

How can i transform all white background and white elements of a png or jpg image in a transparent backgroun using PIL?

Theraot
  • 31,890
  • 5
  • 57
  • 86
tostes
  • 51
  • 1
  • 2

1 Answers1

9

Using numpy, the following makes white-ish areas transparent. You can change threshold and dist to control the definition of "white-ish".

import Image
import numpy as np

threshold=100
dist=5
img=Image.open(FNAME).convert('RGBA')
# np.asarray(img) is read only. Wrap it in np.array to make it modifiable.
arr=np.array(np.asarray(img))
r,g,b,a=np.rollaxis(arr,axis=-1)    
mask=((r>threshold)
      & (g>threshold)
      & (b>threshold)
      & (np.abs(r-g)<dist)
      & (np.abs(r-b)<dist)
      & (np.abs(g-b)<dist)
      )
arr[mask,3]=0
img=Image.fromarray(arr,mode='RGBA')
img.save('/tmp/out.png')

The code is easy to modify so that only RGB value (255,255,255) is turned transparent -- if that is what you truly want. Simply change the mask to:

mask=((r==255)&(g==255)&(b==255)).T
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • I understand threshold, but can you explain the purpose of distance here? – kangax Oct 09 '11 at 16:47
  • @kangax: By lowering the `dist` you can ensure that you eliminate only grayish colors. – unutbu Oct 10 '11 at 10:01
  • Ahh... makes sense! #000, #555, #aaa, ccc, #eee, #fff are all shades of grey (distance = 0) so the less distance the grey-er colors are. Thanks. – kangax Oct 10 '11 at 21:18