1.安装POLLOW库

在cmd中输入pip install?pillow?,然后回车
?
?我已经安装过了,要是没安装,会在线下载,所以需要联网哦
2.安装removebg库
过程同上。
?
?pillow和removebg,分别用于修改照片尺寸和抠图
3.申请removebg库的API(很简单)
如何获取RemoveBg的API(点击查看)
安装完removebg库之后,需要申请API,打开网站:https://www.remove.bg/zh/api
PS:每一个API每月只可以免费使用50次,超出需要付费,请知悉...

?点击之后,需要登录,注册下就行,用QQ邮箱即可。


?
?
?4.代码
from PIL import Image
from removebg import RemoveBg
# removebg涉及到api_key,需要到其官网申请
api_key = '00000000000000000' #自己去申请,这里我就不提供了。申请完替换一下即可
def change_bgcolor(file_in, file_out, api_key, color):
'''
#必须为png格式
'''
p, s = file_in.split(".")
rmbg = RemoveBg(api_key, 'error.log')
rmbg.remove_background_from_img_file(file_in)
file_no_bg = "{}.{}_no_bg.{}".format(p, s, s)
no_bg_image = Image.open(file_no_bg)
x, y = no_bg_image.size
new_image = Image.new('RGBA', no_bg_image.size, color=color)
new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
new_image.save(file_out)
# 修改照片尺寸
def change_size(file_in, file_out, width, height):
image = Image.open(file_in)
resized_image = image.resize((width, height), Image.ANTIALIAS)
resized_image.save(file_out)
if __name__ == "__main__":
file_in = 'C:\XiongBig.png'
file_out = 'C:\XiongBig_cutout.png'
# 尺寸可按需求自修改
# change_size(file_in, file_out, width, height)
# 换背景色
color = (0, 125, 255)
change_bgcolor(file_in, file_out, api_key, color)
?5.效果展示
原图:

?修改后的图:

蓝底的图:
?
|