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,allaxis(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
本文发布于:2024-02-04 23:16:29,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170718638560667.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |