去除背景是一个比较复杂的工作,从简单到复杂依次为:
- 去除白色背景
- 去除单一背景(电视中常用的抠图)
- 去除复杂背景
Python中去除背景可以使用的程序包是PIL和CV2。本文只实现了使用PIL去除白色背景。另外的情况后面研究透彻后再发文章。
核心的方法是增加了Alpha通道,将此通道设置为0。
- PIL去除白色背景
from PIL import Image
import numpy as np
threshold=100
dist=5
img=Image.open("d:\\green.jpg").convert('RGBA') #增加Alpha通道
img.show()
arr=np.array(np.asarray(img)) #获取图像数据,使用了numpy
r,g,b,a=np.rollaxis(arr,axis=-1)img.show()
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.show()
版权声明:本文为weixin_42272768原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。