1 换取抠图API

RemoveBg官网注册账号免费获得API,每月可用50次。
RemoveBg官网:https://www.remove.bg/r/a9Dy3RhvgnKDphmsMbarJYrG
image.png

2 安装现需要的库

  1. pip install removebg
  2. pip install pillowpython2安装:pip install PIL
  3. pip install shutil

3 编写代码

  1. #!/usr/bin/env python
  2. # _*_ coding: utf-8 _*_
  3. # @Time : 2021/10/12 15:07
  4. # @Author : cfxin
  5. # @File : photo-background-color-change.py
  6. # @Software: PyCharm
  7. # -*- 功能说明 -*-
  8. # 图片抠图和更换背景颜色
  9. # -*- 功能说明 -*-
  10. import os
  11. import shutil
  12. from PIL import Image
  13. from removebg import RemoveBg
  14. # 证件照背景色
  15. Background_Color = {
  16. 'Red': (255, 0, 0, 255),
  17. 'Blue': (67, 142, 219, 255),
  18. 'White': (255, 255, 255, 255)
  19. }
  20. pic = input("Tip:请将图片移至当前所在目录下!\n请输入图片文件名(含文件后缀):") # 图片文件名
  21. print("当前所在目录:" + os.getcwd())
  22. if os.path.exists('img'):
  23. print("\n当前目录已存在img文件夹!!!")
  24. else:
  25. print("\n正在新建输出目录img ...")
  26. new_folder = '%s' % os.mkdir(os.getcwd() + '\\img') # 新建文件夹
  27. print("输出目录img创建成功!!!\n")
  28. os.chdir('./img') # 切换至img目录下
  29. if not os.path.exists(pic):
  30. print("\n正在复制图片至img文件夹......")
  31. shutil.copy('../' + pic, pic)
  32. print("目标图片已复制到img文件夹!\n")
  33. path = '%s' % os.getcwd() # 当前所在路径
  34. print("当前目标图片路径:\t" + '%s\%s' % (path, pic)) # 输出图片所在路径
  35. # Api每月可用50次,降低同一张图片重复抠图频率
  36. if os.path.exists(pic + '_no_bg.png'):
  37. print("\n当前目录已存在透明背景图片" + pic + '_no_bg.png\n')
  38. else:
  39. print("\n正在生成错误日志(可不用理会)......")
  40. rmbg = RemoveBg("Your-RemoveBg-Api-Key", "error.log") # 密钥,错误日志
  41. print("正在进行抠图......")
  42. rmbg.remove_background_from_img_file('%s\%s' % (path, pic)) # 抠图
  43. print("已生成透明背景图片:" + pic + "_no_bg.png\n")
  44. select_bgColor = input("Tip:更换红色背景按 r,更换蓝色背景按 b,更换白色背景按 w \n请选择需要更换的证件照底色:") # 选择所需更换的底色
  45. while True:
  46. if select_bgColor == 'r':
  47. color = 'Red'
  48. break
  49. elif select_bgColor == 'b':
  50. color = 'Blue'
  51. break
  52. elif select_bgColor == 'w':
  53. color = 'White'
  54. break
  55. else:
  56. select_bgColor = input("\n输入有误!请重新输入:")
  57. foreground = Image.open(pic + '_no_bg.png') # 前景图
  58. background = Image.new('RGBA', foreground.size, Background_Color[color]) # 背景图,大小同前景图
  59. background.paste(foreground, mask=foreground)
  60. print("\n正在展示图片......")
  61. background.show() # 显示图片
  62. print("正在保存图片......\n")
  63. new_pic = pic + '_' + color + '.png' # 输出文件名
  64. background.save(os.getcwd() + '\\' + new_pic) # 保存图片
  65. print("输出路径为:" + os.getcwd())
  66. os.chdir('../') # 切换回原工作目录
  67. print("\n保存成功!输出文件为:" + new_pic + "\n\n按任意键退出\n") # 显示保存图片名
  68. os.system('pause') # 按任意键继续

到此处已经可以实现抠图并更换背景颜色的功能。为了方便使用可以按下面的步骤打包成可执行程序。

4 打包成exe可执行文件

  1. 安装PyInstaller包:pip install PyInstaller
  2. 切换至该刚才编写的 .py 文件所在目录下,命令行窗口输入pyinstaller -F Your_File_Name.py

image.png

  1. 打包成功后会出现3个文件夹和一个文件,打包成功的.exe 文件在 dist 目录下

image.png