1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > python怎么弄成白色背景_使用PIL python将白色背景转换为透明背景

python怎么弄成白色背景_使用PIL python将白色背景转换为透明背景

时间:2022-04-11 07:49:18

相关推荐

python怎么弄成白色背景_使用PIL python将白色背景转换为透明背景

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

解决方案

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)

& (np.abs(r-b)

& (np.abs(g-b)

)

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。