赞
踩
backgroundremover
是一款开源免费的命令行工具,专门用来消除图片和视频中的背景,使用python
语言编写,项目地址 https://github.com/nadermx/backgroundremover。
可以使用pip
安装
pip install backgroundremover
当然,下载源码进行安装也是可以的
- git clone https://github.com/nadermx/backgroundremover.git
- cd backgroundremover
- python setup.py install
目前最新版本为0.1.9,后面测试也是基于这个版本进行。
接下来还需要安装ffmpeg
,它是用来进行视频处理的。从官网下载编译好的二进制文件 http://ffmpeg.org/download.html,尽量下载较新的版本,并将其路径加入到系统环境变量中
最后安装下torch
,由于本机有gpu
,安装的是gpu
版本的,版本要求1.7以上
pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
准备一张带背景的原图
执行下面命令就可以去除背景,操作非常简单
backgroundremover -i original.jpg -o output.png
操作过程中会到google driver
去下载所需要的u2net
模型,但是由于国内的网络环境,无法访问
这时候,可以通过下面的链接去下载
另外也提供个网盘的地址
链接:https://pan.baidu.com/s/1ZYzV0SYEjlBldsGXIn2IXA
提取码:srix
下载后的模型文件,将其放到~/.u2net
文件夹下,如果文件夹不存在就自己创建
准备就绪后,重新执行上面的去背指令,就可以得到去掉背景的图片了
backgroundremover
可以使用三种模型来达到图片视频去背的目的,分别是u2netp
、u2net
和u2net_human_seg
比如说要使用u2net_human_seg
,可以使用-m
参数
backgroundremover -i original.jpg -m u2net_human_seg -o output.png
如果要处理视频的话,可以这样
backgroundremover -i test.mp4 -tv -o output.mov
视频背景去除后叠加到另一个视频上
backgroundremover -i test.mp4 -tov -tv videtobeoverlayed.mp4 -o output.mov
视频去背后生成gif
动图
backgroundremover -i test.mp4 -tg -o output.gif
更换图片底色应用
- import os
- from PIL import Image
- # 输入
- in_path = "d:\in.jpg"
- # 输出
- out_path = "d:\out.png"
- # 要替换的背景颜色
- color = "deepskyblue"
- # 红:red、蓝:blue、黑:black、白:white
-
- # 去掉背景颜色
- os.system('backgroundremover -i "'+str(in_path)+'" -o "d:\cg_output.jpg"')
- # 加上背景颜色
- no_bg_image = Image.open("d:\cg_output.jpg")
- x, y = no_bg_image.size
- new_image = Image.new('RGBA', no_bg_image.size, color=color)
- new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
- new_image.save(out_path)

更多场景使用及参数设置,请参考官方文档。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。