Since this is currently Google’s first result when searching for "Pillow from white to transparent", I would like to add that the same can be achieved with numpy, and in my test (one 8MP image with a lot of white background) about 10 times faster (about 300 ms versus 3.28 s for the proposed solution). The code is also a bit shorter:
import numpy as np def white_to_transparency(img): x = np.asarray(img.convert('RGBA')).copy() x[:, :, 3] = (255 * (x[:, :, :3] != 255).any(axis=2)).astype(np.uint8) return Image.fromarray(x)
It is also easy to replace it with a version in which “almost white” (for example, one channel 254 instead of 255) is “almost transparent”. Of course, this will make the whole picture partially transparent, except for pure black:
def white_to_transparency_gradient(img): x = np.asarray(img.convert('RGBA')).copy() x[:, :, 3] = (255 - x[:, :, :3].mean(axis=2)).astype(np.uint8) return Image.fromarray(x)
Note: .copy() necessary because, by default, pillow images are converted to read-only arrays.
Marco Spinaci Jan 11 '19 at 14:24 2019-01-11 14:24
source share