利用Python制做证件照、证件照换底色

这两件事都用到了一个功能强大的api,网址为 https://www.remove.bg/welcomeapi

这个api功能为去除图片的背景色,每一个邮箱能够注册一个帐户,每一个帐户可无偿使用50张/月post

邀请别人,本身和别人能够额外得到积分,换取更多的使用次数

https://www.remove.bg/r/ybjFyg6rouZDrJVs7LcBUTRH命令行

(哈哈这是个人邀请连接,以为文章不错,能够从这边点进去) 点我申请code

 


  • 制做证件照思路: 普通图片---->> 去除背景图片----->>填充背景色
  • 证件照换底色思路:证件照图片---->> 去除背景证件照----->>填充新的背景色证件照

 第一阶段是利用上述api实现,第二阶段能够利用PIL库功能实现blog

Tips:安装PIL库时,在命令行使用pip install Pillow安装,不能pip install PIL,引入时写from PIL import Image图片

废话不说了,上demo:(使用时须要把demo里的api的key换成本身申请的ip

import requests
from PIL import Image
#第一阶段,利用api去除背景色
response = requests.post(
    'https://api.remove.bg/v1.0/removebg',
    files={'image_file': open('test.jpg', 'rb')},
    data={'size': 'auto'},
    headers={'X-Api-Key': 'your key'},
)
if response.status_code == requests.codes.ok:
    with open('no-bg.png', 'wb') as out:
        out.write(response.content)
else:
    print("Error:", response.status_code, response.text)
print("想换成的颜色: blue for 蓝色,red for 红色 white for 白色 ,回车 for no_change\n:")
#第二阶段,利用PIL库填充背景色
color=input()
im = Image.open('no-bg.png')
x,y = im.size
try:
  # (alpha band as paste mask).
  if color=='':
      print('no change')
      pass
  elif color=='blue':
      p = Image.new('RGBA', im.size, (0, 0, 255))
      p.paste(im, (0, 0, x, y), im)
      p.save('bg_blue.png')
  elif color=='red':
      p = Image.new('RGBA', im.size, (255, 0, 0))
      p.paste(im, (0, 0, x, y), im)
      p.save('bg_red.png')
  elif color=='white':
      p = Image.new('RGBA', im.size, (255, 255, 255))
      p.paste(im, (0, 0, x, y), im)
      p.save('bg_white.png')
  else:
      print('no match!')
except:
  pass

效果展现:rem

分别换成了红底,白底,蓝底证件照get