系列文章目录
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、remove.bg API申请
1、登录网址:https://www.remove.bg/zh,注册;
2、登录账号,点击我的仪表盘,获取API Key;
二、效果展示(需要借一张小姐姐照片)
三、使用步骤
1.去除背景
代码如下(示例):
from removebg import RemoveBg
rmbg=RemoveBg("jxLrSswU5NVKf9xxxxxxx","error.log") #AI密钥
rmbg.remove_background_from_img_file(r"E:\py\python3.7\test\test45\ceshi2\2.jpg")
2.填充背景
代码如下(示例):
# 给去除了背景的图像添加背景颜色
from PIL import Image
# 输入已经去除背景的图像
im = Image.open(r'E:\py\python3.7\test\test45\ceshi2\2.jpg_no_bg.png')
x, y = im.size
try:
# 填充红色背景255,0,0 白色是255,255,255
p = Image.new('RGBA', im.size, (255, 0, 0))
p.paste(im, (0, 0, x, y), im)
# 保存填充后的图片
p.save(r'E:\py\python3.7\test\test45\ceshi2\2.png')
except:
with open('./error.log', 'a') as f:
f.write('background change fail .')
3.去除背景+填充背景
代码如下(示例):
from removebg import RemoveBg
from PIL import Image
def Change_picture_background(old_file,new_file,color):
rmbg = RemoveBg("jxLrSswU5NVKxxxxxx", "error.log") # 引号内是你获取的API
rmbg.remove_background_from_img_file(r"E:\py\python3.7\test\test45/"+old_file) #图片地址
path = r"E:\py\python3.7\test\test45/"+ old_file + '_no_bg.png'
im = Image.open(path)
x, y = im.size
# 填充背景
p = Image.new('RGBA', im.size, color)
p.paste(im, (0, 0, x, y), im)
# 保存填充后的图片
p.save(r"E:\py\python3.7\test\test45/"+new_file)
Change_picture_background('2.jpg','2.png','#66CC99')
四、颜色参考
1.颜色代码对应表
其它颜色可自主选择更改!
总结
青春须早为,岂能长少年!!