一、功能
(1)实现图片底色替换为红色(白色或蓝色)
二、实现
(1)登录remove.bg,获取API KEY。
(2)使用pip安装 requests和pillow
pip install pillow
pip install requests
(3)remove.bg简单使用
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)
(4)改造上述方法,将得到的图片重新进行处理
import requests
from PIL import Image
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('path/to/saved/no-bg.png', 'wb') as out:
out.write(response.content)
else:
print("Error:", response.status_code, response.text)
bg_color = (255, 0, 0) # 红色,(255, 255, 255)白色 ,(0, 0, 255) 蓝色
img = Image.open(f'path/to/saved/no-bg.png')
x, y = img.size
new_img = Image.new('RGBA', img.size, color=color)
new_img.paste(img, (0, 0, x, y), img)
new_img.save(f'path/to/gen.png')
使用remove.bg Python库创建证件照背景替换工具
本文介绍了如何利用remove.bg的API和Python的requests与Pillow库,实现证件照片的背景颜色替换,支持红、白、蓝三种颜色。
2595

被折叠的 条评论
为什么被折叠?



