暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python自动化:一款基于AI的自动图片背景去除软件

alitrack 2022-10-12
1512

官网的介绍很谦虚,Rembg[1] 是一款图片背景去除工具. 这里我先简单介绍下它的特点。

特点

  • 开源、免费
  • 基于 Python 开发
  • 后台引擎是用于显著对象检测的深度网络架构 U²-Net(后文有简单介绍)
  • 安装简单
pip install rembg

  • 支持命令行
# 处理本地图片
rembg i path/to/input.png path/to/output.png
# 处理整个目录
rembg p path/to/input path/to/output

该程序需要预先训练好的模型支持, 程序可以自动下载模型,不过是从 Google Drive 里,建议你关注本公众号,回复关键字: 去除背景,获得全部四个模型的下载地址,将模型下载并保存在用户主文件夹的.u2net
目录中, 默认使用的模型是u2net

  • 支持 GPU
pip install rembg[gpu]

  • 作为 Web Server 运行
rembg s
# 然后浏览器访问
http://localhost:5000/docs



  • 作为包使用
# 字节组
from rembg import remove

input_path = 'input.png'
output_path = 'output.png'

with open(input_path, 'rb'as i:
    with open(output_path, 'wb'as o:
        input = i.read()
        output = remove(input)
        o.write(output)

# PIL
from rembg import remove
from PIL import Image

input_path = 'input.png'
output_path = 'output.png'

input = Image.open(input_path)
output = remove(input)
output.save(output_path)

# numpy array
from rembg import remove
import cv2

input_path = 'input.png'
output_path = 'output.png'

input = cv2.imread(input_path)
output = remove(input)
cv2.imwrite(output_path, output)

模型

所有模型都下载并保存在用户主文件夹的.u2net
目录中。

可用的型号有:

  • u2net(下载[2]-替代[3]来源[4]):用于一般用例的预训练模型。
  • u2netp(下载[5]-替代[6][7]):u2net 模型的轻量级版本。
  • u2net_human_seg(下载[8]-替代[9]来源[10]):用于人体分割的预训练模型。
  • u2net_cloth_seg(下载[11]-替代[12]来源[13]):用于从人类肖像中解析布料的预训练模型。这里的衣服被解析为 3 类:上半身、下半身和全身。

如果下载失败可以关注本公众号,回复关键字: 去除背景,获得全部四个模型的下载地址

如何训练自己的模型

如果您需要更精细的模型,试试这个:#193(评论)[14]

高级用法

有时可以通过打开 alpha matting 来获得更好的结果。例子:

rembg i -a -ae 15 path/to/input.png path/to/output.png

U²-Net 简介

自从 CVPR2020 的用于显著对象检测的深度网络架构U²-Net[15]开源以来,该项目的 GitHub 页面在三天内获得了 2,400 颗星,到目前已经 6200 颗星了。

U²-Net 给我们带来了什么?

得益于在 SOTA SOD 方法取得了不错的竞争力,U²-Net 可以应用在很多场景。首先,U²-Net 现在已经是 Python 的抠图工具 Rembg 的基础算法。抠图就是将照片的主体人或物品从图片中抠出来,以便贴到别处使用。除了被用来作为抠图外,素描肖像生成(Portrait Drawing)也是其非常有趣且流行的新应用。

如果你觉得有必要把它封装成便于使用的 app,请 👍、留言,谢谢!

参考资料

[1]

Rembg: https://github.com/danielgatis/rembg

[2]

下载: https://drive.google.com/uc?id=1tCU5MM1LhRgGou5OpmpjBQbSrYIUoYab

[3]

替代: http://depositfiles.com/files/ltxbqa06w

[4]

来源: https://github.com/xuebinqin/U-2-Net

[5]

下载: https://drive.google.com/uc?id=1tNuFmLv0TSNDjYIkjEdeH1IWKQdUA4HR

[6]

替代: http://depositfiles.com/files/0y9i0r2fy

[7]

源: https://github.com/xuebinqin/U-2-Net

[8]

下载: https://drive.google.com/uc?id=1ZfqwVxu-1XWC1xU1GHIP-FM_Knd_AX5j

[9]

替代: http://depositfiles.com/files/6spp8qpey

[10]

来源: https://github.com/xuebinqin/U-2-Net

[11]

下载: https://drive.google.com/uc?id=15rKbQSXQzrKCQurUjZFg8HqzZad8bcyz

[12]

替代: http://depositfiles.com/files/l3z3cxetq

[13]

来源: https://github.com/levindabhi/cloth-segmentation

[14]

#193(评论): https://github.com/danielgatis/rembg/issues/193#issuecomment-1055534289

[15]

U²-Net: https://github.com/xuebinqin/U-2-Net


文章转载自alitrack,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论