1+ from PIL import Image
2+ import requests
3+ import base64
4+
5+
6+ def get_access_token ():
7+ """
8+ 获取 access_token
9+ """
10+ host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=ak&client_secret=sk'
11+ response = requests .get (host )
12+ if response :
13+ return response .json ()['access_token' ]
14+
15+
16+ def get_foreground (originalImagePath ):
17+ """
18+ 人像分割
19+ """
20+ # 二进制方式打开图片文件
21+ f = open (originalImagePath , 'rb' )
22+ img = base64 .b64encode (f .read ())
23+
24+ # 请求 百度 AI 开放平台
25+ request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg?access_token=" + get_access_token ()
26+ headers = {'content-type' : 'application/x-www-form-urlencoded' }
27+ params = {"image" : img }
28+ response = requests .post (request_url , data = params , headers = headers )
29+
30+ if response :
31+ foreground = response .json ()['foreground' ]
32+ img_data = base64 .b64decode (foreground )
33+ img_path = 'foreground.png'
34+ with open (img_path , 'wb' ) as f :
35+ f .write (img_data )
36+ return Image .open (img_path )
37+
38+
39+ def get_background ():
40+ """
41+ 背景图片
42+ """
43+ color = ('red' , 'blue' , 'white' )
44+ imgs = []
45+ for c in color :
46+ # 一寸照片大小
47+ img = Image .new ("RGBA" , (295 , 413 ), c )
48+ imgs .append (img )
49+ return imgs
50+
51+ def mian ():
52+ fore = get_foreground ('original.jpg' )
53+ p = fore .resize ((330 , 415 ))
54+ r ,g ,b ,a = p .split ()
55+
56+ imgs = get_background ()
57+ for img in imgs :
58+ img .paste (p , (- 30 , 50 ), mask = a )
59+ img .show ()
60+
61+ if __name__ == '__main__' :
62+ mian ()
0 commit comments