Python一键抠背景功能
分享一个有趣的小项目,可以一键抠背景,需要用到removebg模块及其API,API可从其官网免费获取,网址如下
ps:加上/zh后,网页内容会显示中文
首先是安装removebg模块
然后就敲代码了,官方使用文档是个好东西,应该好好利用
有趣的是,意外发现了两种使用API的方法
1.用到爬虫的知识,利用requests模块,从网页上调用,直接实现抠背景
# Requires "requests" to be installed (see python-requests.org)
import requests
response = requests.post(
'https://api.remove.bg/v1.0/removebg',
files={'image_file': open('/path/to/file.jpg', 'rb')},
data={'size': 'auto'},
headers={'X-Api-Key': 'INSERT_YOUR_API_KEY_HERE'},
)
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)
效果如下:


2.参照removebg库中的使用说明调用API,用相关代码实现抠背景

上代码,这里就只展示处理单张图片的代码,批量处理图片以及根据url处理图片的相关代码均在README.md中有展示
效果如下

rom removebg import RemoveBg
# 抠单张图片
rmbg = RemoveBg("P3UCVZzKiUxW7BbkmcRYhgTB", "error.log") # 引号内是你获取的API
rmbg.remove_background_from_img_file(r"C:\Users\Lenovo\PycharmProjects\爬虫\长颈鹿1.jpg",size='regular',bg_color='e.g.red') # 图片地址

但奇怪的是加上填充纯色背景的属性bg_color='e.g.red’后会有这样的报错,尚未解决
后来使用了PIL库来实现背景的填充
from PIL import Image
# 加载已去背景的图像
im = Image.open('./pic/no-bg.png')
x, y = im.size
try:
# 填充红色背景
p = Image.new('RGBA', im.size, (255, 0, 0))
p.paste(im, (0, 0, x, y), im) #paste的背景尺寸需与原图尺寸相同
# 保存填充后的图片
p.save('./pic/no-bg_red_bg.png')
p.show() #显示处理后的图片
except:
with open('./error1.log', 'a') as f:
f.write('background change fail .')
效果如下

不断的学习python核心知识,深入的研习计算机基础知识,我们的Python学习群:313074041