一行Python代码去除照片背景

使用Python去除照片背景,说到去除照片背景的方法,我首先想到的是第三方接口(如:百度AI),但本文重点在于免费使用,不花钱的那种。
下面就开始介绍两种免费去除照片背景的方法
第一种
第一种方法是:removebg(实际上还是第三方接口,不过removebg是免费的)

remove官方地址:
首先先注册一个账号,然后访问下方链接获取api_keys(代码里面会用到)
https://www.remove.bg/api#remove-background

点击Get API Key 即可获取key值

获取到key值后,咱们就开编写python程序
# 导入库
from removebg import RemoveBg
api_keys = "上面获取到的key值"
rmbg = RemoveBg(api_key, "error.log")
#rmbg.remove_background_from_img_file("图片路径")
rmbg.remove_background_from_img_file("chen.jpg")
样例效果:

(图片来源网络)
总结
优点:不限于证件照,任何图片都可以去除背景(包括全身照片以及多人合影照片等)
缺点:这个方法只能免费使用50次,超过50次就会提示报错(如下所示)

第二种
第二种方法就是backgroundremover,其实就是一个Python库
github地址:
https://github.com/nadermx/backgroundremover
使用很简单:就两步(github介绍安装中有一些没必要安装,可忽略)
第一步:安装库
pip install backgroundremover
第二步:执行命令
# backgroundremover -i "带背景照片" -o "去除背景照片"
backgroundremover -i "cg.jpg" -o "cg_outopt.jpg"
Python方式调用:
# 导入库
import os
os.system('backgroundremover -i "cg.jpg" -o "cg_output.jpg"')
原理:实际上就是python通过os去执行终端命令。
注意:
在第二步时,初次使用需要下载模型(大概170m),下载地址是google,因此需要能够访问google,才能下载。
不过不用担心,我已经把模型下载好了
链接:https://pan.baidu.com/s/13a4Aqmpm9ds7bswP-MgZhg a7de
下载好的模型需要放到当前系统用户的目录下:
## Window10:
C:\Users\用户\.u2net\u2net.pth
## Mac:
/Users/lyc/.u2net/u2net.pth
## Linux:
/root/.u2net/u2net.pth
如果找不到这个位置的,直接搜索.u2net****文件夹位置,将模型放到.u2net文件夹也可以
样例效果:

(图片来源网络)
同一张照片,使用这两种不同的方法去除背景
效果差别不大(推荐第二种方法)
总结
优点:不限次数使用,不仅可以对照片去除背景,还可以对视频去除背景(github上有使用方法,感兴趣的可以去看看)