点击【阅读原文】
证件照用处较广,无论是四六级还是其它等级考试,我们都需要在报名时候上传一张符合要求的证件照。不会PS,怎么办?本文带您了解如何用Python程序处理证件照:修改证件照背景及尺寸。
Step 1:注册用户https://accounts.kaleido.ai/users/sign_up
Step 2:邮件激活账户
Step 3:复制API密钥
完整程序如下:
import os
import cv2
from PIL import Image
from removebg import RemoveBg
def img_show(path, title):
im = Image.open(path)
im.show(title)
def image_matting(old_image_path, new_image_path, api_key, color, width, height):
# API KEY获取官方网站:https://www.remove.bg/zh/api
rmbg = RemoveBg(api_key, "error.log")
rmbg.remove_background_from_img_file(old_image_path)
parent_path = os.path.dirname(old_image_path)
old_image_name = os.path.split(old_image_path)[-1]
no_bg_image_name = old_image_name + "_no_bg.png"
if no_bg_image_name in os.listdir(parent_path):
no_bg_image_path = parent_path + "/" + no_bg_image_name
no_bg_image = Image.open(no_bg_image_path)
x, y = no_bg_image.size
try:
new_image = Image.new('RGBA', no_bg_image.size, color=color)
new_image.paste(no_bg_image, (0, 0, x, y), no_bg_image)
resized_image = new_image.resize((width, height), Image.ANTIALIAS)
resized_image.save(new_image_path)
img_show(path = old_image_path, title = 'Before')
img_show(path = no_bg_image_path, title = 'No Bg')
img_show(path = new_image_path, title = 'After')
except:
print("image matting except")
else:
print("image matting fail")
if __name__ == '__main__':
#请填写上自己申请的API密钥
api_key = ''
color = (0, 134, 200)
old_image_path = './photo.png'
new_image_path = './photo_after.png'
width = 480
height = 640
image_matting(old_image_path = old_image_path,
new_image_path = new_image_path,
api_key = api_key, color = color,
width = width, height = height
从网上下载一图片,图1为原图,图2为去背景图,图3为换底与改变大小后效果。实验效果如下:
生成的图片是PNG格式的,如需JPG格式图片可直接修改文件后缀名即可。
毕业在即,无论是考试证还是其它证件,如小伙伴们搞不定的情况,本殿下可免费为各位PS制作符合要求的证件照,请将原图通过邮箱发送给本殿下即可!