使用PIL python将白色背景转换为透明背景 [英] White background to transparent background using PIL python

查看:1246
本文介绍了使用PIL python将白色背景转换为透明背景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用PIL在透明背景中转换png或jpg图像中的所有白色背景和白色元素?

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

推荐答案

以下使用numpy使白色区域透明.您可以更改thresholddist以控制白色"的定义.

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')

该代码易于修改,因此只有RGB值(255,255,255)变为透明-如果那是您真正想要的.只需将mask更改为:

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

这篇关于使用PIL python将白色背景转换为透明背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆