这两件事都用到了一个功能强大的api,网址为 https://www.remove.bg/welcome
这个api功能为去除图片的背景色,每个邮箱可以注册一个账户,每个账户可免费使用50张/月
https://www.remove.bg/r/ybjFyg6rouZDrJVs7LcBUTRH
(哈哈这是我的邀请链接,觉得文章不错,可以从这边点进去) 点我申请
- 制作证件照思路: 普通图片---->> 去除背景图片----->>填充背景色
- 证件照换底色思路:证件照图片---->> 去除背景证件照----->>填充新的背景色证件照
第一阶段是利用上述api实现,第二阶段可以利用PIL库功能实现
Tips:安装PIL库时,在命令行使用pip install Pillow安装,不能pip install PIL,引入时写from PIL import Image
废话不说了,上demo:(使用时需要把demo里的api的key换成自己申请的)
import requests
from PIL import Image
#第一阶段,利用api去除背景色
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
files={'image_file': open('test.jpg', 'rb')},
data={'size': 'auto'},
headers={'X-Api-Key': 'your key'},
)
if response.status_code == requests.codes.ok:
with open('no-bg.png', 'wb') as out:
out.write(response.content)
else:
print("Error:", response.status_code, response.text)
print("想换成的颜色: blue for 蓝色,red for 红色 white for 白色 ,回车 for no_change\n:")
#第二阶段,利用PIL库填充背景色
color=input()
im = Image.open('no-bg.png')
x,y = im.size
try:
# (alpha band as paste mask).
if color=='':
print('no change')
pass
elif color=='blue':
p = Image.new('RGBA', im.size, (0, 0, 255))
p.paste(im, (0, 0, x, y), im)
p.save('bg_blue.png')
elif color=='red':
p = Image.new('RGBA', im.size, (255, 0, 0))
p.paste(im, (0, 0, x, y), im)
p.save('bg_red.png')
elif color=='white':
p = Image.new('RGBA', im.size, (255, 255, 255))
p.paste(im, (0, 0, x, y), im)
p.save('bg_white.png')
else:
print('no match!')
except:
pass
效果展示:
分别换成了红底,白底,蓝底证件照