3行代码,搞定AI自动抠图

picture.image

文/GitPython

抠图是用PS?

用魔棒和快速选择工具?

遇到复杂背景怎么办?

最近发现一个神奇的工具-- Remove Image Background

https://www.remove.bg/zh

它基于 Python、Ruby 和深度学习技术开发,通过强大的 AI 人工智能算法实现自动识别出前景主体与背景图,秒秒钟完成抠图。

这款抠图工具有两种简单方式:

1 在线抠图

2 API代码抠图

在线抠图

1)打开remove.bg 网站首页,可以上传本地图片,也可以选择网络图片的URL链接(见文章首图)

2)上传几秒后,就可以看到无背景透明图了。

picture.image

3)可以对图像进行编辑,添加各种场景的背景,或者替换为纯色背景,然后下载即可。

picture.image

它还支持客户端 Windows、Mac、Linux和PS插件,同时还可以引入API到自己的程序中,进行批处理。

picture.image

代码抠图

1)查看API密钥

需要注册账号方可获取密钥。

注册成功后即可登录,查看自己的API密钥。

picture.image

默认生成的图片格式尺寸是标准的,每月最多免费处理 50 张照片,且每张尺寸大小不超过25MB。

如果想生成高清或者处理更多图片需要付费

(在线抠图方式没有次数限制)。

2)安装扩展库

pip install removebg

3)代码使用指南

https://github.com/brilam/remove-bg

picture.image

from removebg import RemoveBg

rmbg = RemoveBg("YOUR-API-KEY", "error.log") # 第一个引号内是你获取的API

rmbg.remove_background_from_img_file("D:/gitpython.jpg") #图片地址

picture.image

运行结果

让我们打开pycharm,看看源码:

import requests
import logging

API_ENDPOINT = "https://api.remove.bg/v1.0/removebg"

class RemoveBg:

def \_\_init\_\_(self, api\_key, error\_log\_file):  
    self.\_\_api\_key = api\_key  
    logging.basicConfig(filename=error\_log\_file)  

def remove\_background\_from\_img\_file(self, img\_file\_path, size="regular"):  
    """  
    Removes the background given an image file and outputs the file as the original file name with "no\_bg.png"  
    appended to it.  
    :param img\_file\_path: the path to the image file  
    :param size: the size of the output image (regular = 0.25 MP, hd = 4 MP, 4k = up to 10 MP)  
    """  
    # Open image file to send information post request and send the post request  
    img\_file = open(img\_file\_path, 'rb')  
    response = requests.post(  
        API\_ENDPOINT,  
        files={'image\_file': img\_file},  
        data={'size': size},  
        headers={'X-Api-Key': self.\_\_api\_key})  

    self.\_\_output\_file\_\_(response, img\_file.name + "\_no\_bg.png")  

    # Close original file  
    img\_file.close()  

我是总结

本文介绍了两种方式:

1 在线抠图

2 API代码抠图

可根据需求,选择不同的方式。

自己用的话在线抠图就可以了; 如果想要批量处理,可以试试代码搞定一下。

-END-

picture.image

▼ 点击成为社区注册会员** 喜欢文章,点个** 在看 picture.image

0
0
0
0
评论
未登录
暂无评论