創建圖像增強與特效應用
測試代碼
import base64 import requests def get_access_token(): # 獲取token的API url = 'https://aip.baidubce.com/oauth/2.0/token' # 獲取access_token需要的參數 params = { # 固定參數 'grant_type': 'client_credentials', # 必選參數,傳入你的API Key 'client_id': 'xxx', # 必選參數,傳入你的Secret Key 'client_secret': 'xxx' } # 發送請求,獲取響應數據 response = requests.post(url, params) # 將響應的數據轉成字典類型,然后取出access_token access_token = eval(response.text)['access_token'] # 將access_token返回 return access_token def img2Cartoon(img): # 頭像動漫化的API url = 'https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime' # 以二進制的方式讀取原始圖片 origin_im = open(img, 'rb') # 將圖片進行base64編碼 img = base64.b64encode(origin_im.read()) # 關閉原圖片 origin_im.close() # 請求的headers信息,固定寫法 headers = {'content-type': 'application/x-www-form-urlencoded'} # 請求的參數 params = { # 開始獲取的access_token 'access_token': get_access_token(), # 圖片的base64編碼 'image': img, } # 發送請求 response = requests.post(url, data=params, headers=headers) # 對響應結果進行處理 if response: # 打開一個文件 f = open('result.jpg', 'wb') # 獲取動漫頭像 anime = response.json()['image'] # 對返回的頭像進行解碼 anime = base64.b64decode(anime) # 將頭像寫入文件當中 f.write(anime) f.close() if __name__ == '__main__': img2Cartoon('origin.PNG')