首先,我们需要借用一个工具removebg
可能很多人没听过这是啥,其实要不是以为抠图,我可能也不知道这是个啥。
接下来,我们就来瞅瞅这个神奇的网站,
这就是 神奇的图片背景消除工具,链接已覆上,点击即可。
秘钥截图
非常重要的 就是API Key,
平民版(免费)一个月就30次,
人民币玩家,一个月就 NNN次了 ~ ~
网站,就是张这个样子,感兴趣的,可以自行注册。
接下来,我们就要在代码实现去除图片背景操作,
- # -*- coding: utf-8 -*-
- """
- @ auth : carl_DJ
- @ time : 2020-8-12
- """
- from removebg import RemoveBg
- '''去除一张图片'''
-
- #这里需要的是 removebg网站上的秘钥,如果错误,则输出到log文件中
- rmbg = RemoveBg('输入removebg上的秘钥','rmgb_error.log')
-
- #图片的地址
- pict_path ='../image/remobg'
-
- #执行去图片背景操作
- rmbg.remove_background_from_img_file(f"{pict_path}/my_pict.jgp")
-
-
执行结果如何呢??
嘿嘿,
原图
去除后的图片
如果一次要去除多张照片的背景色,我们需要咋做呢?
很简单喽,就是for循环咯
来,直接上代码,
- # -*- coding: utf-8 -*-
- """
- @ auth : carl_DJ
- @ time : 2020-8-12
- """
-
- from removebg import RemoveBg
- import os
- #这里需要的是 removebg网站上的秘钥,如果错误,则输出到log文件中
- rmbg = RemoveBg('输入removebg上的秘钥','rmgb_error.log')
- #图片的地址
- pict_path ='../image/remobg'
-
- #循环遍历remobg文件夹中的所有图片
- for pict in os.listdir(pict_path):
- img_path = os.path.join(pict_path,pict)
- #执行去除背景色操作
- rmbg.remove_background_from_img_file(img_path)
- print("%s is done" %img_path)
-
想看效果,那执行下! !