小言_互联网的博客

[python] 证件照换底色

456人阅读  评论(0)

换底色小工具

1.准备

python3

pip install removebg
pip install pillow

2.申请API

RemoveBG网站
注册后获取API-每月免费50张

3.处理

from removebg import RemoveBg
from PIL import Image
import os

def process_bg(image_path, bg):    
	color = {
	        'r': (255, 0, 0),
	        'b': (0, 0, 255),        
	        'w': (255, 255, 255)
 	}    
 	im = Image.open(image_path)    
 	p = Image.new('RGBA', im.size, color[bg])    
 	x, y = im.size    
 	p.paste(im, (0, 0, x, y), im)    
 	p.save(image_path.replace('no_bg', bg))

if __name__ == "__main__":    
	api_key = '{API-key}'    
	rmbg = RemoveBg(api_key, "photo/error.log")  #错误日志路径    
	image_path = 'photo'    #存放待处理照片的目录
	for file in os.listdir(image_path):   
	    rmbg.remove_background_from_img_file(os.path.join(image_path, file))        		
	    no_bg_file = os.path.join(image_path, file+'_no_bg.png')        
	    process_bg(no_bg_file, 'r') # r红色,可替换b or w

转载:https://blog.csdn.net/weixin_42165585/article/details/102468822
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场