最近发现一个好玩的开放接口,可以一键把图片转换成动漫效果,接口给的demo是一张一张的转换,那么能不能写一个脚本批量将一个文件夹的图片转化成动漫效果,然后输出到另一个文件夹呢?本文将从脚本编写的思路来分析。
准备工作
- 申请开放接口:到百度开放平台申请;
脚本分析
- 获取百度accesstoken;
- 获取转化前图片文件夹列表并转换为路径list;
- 调用百度AI接口;
- 循环转化前路径list,并循环调用;
- 将转化后的图片从base64格式解析并保存为图片;
代码实现
# _*_ coding:utf-8 _*_
'''
@File : likeAnime.py
@Time : 2020/12/28 14:33:48
@Author : daniel lau
@Website : https://www.liuyude.com
@Contact : contact@liuyude.com
@Desc : 批量将人像照片转化为动漫图片
'''
# here put the import lib
import requests
import base64
import json
import os
import re
# 获取accesstoken
def get_access_token():
host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'
response = requests.get(host)
access_token = json.loads(response.text)
return access_token['access_token']
# 获取需要转换图片文件夹中的列表,将文件名称转换为list
def get_all_img():
filename_list = []
path = "转化前的路径"
for filename in os.listdir(r'转化前的路径'):
file_path = path + filename
filename_list.append(file_path)
# print(file_path)
return filename_list
# 调用百度AI接口生成图片
def gen_img():
request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime"
print(get_all_img())
# 二进制方式打开图片文件,要转换的图片路径
for filepath in get_all_img():
f = open(filepath, 'rb')
img = base64.b64encode(f.read())
params = {"image":img}
access_token = get_access_token()
request_url = request_url + "?access_token=" + access_token
headers = {'content-type': 'application/x-www-form-urlencoded'}
response = requests.post(request_url, data=params, headers=headers)
img = response.json()['image']
img_data = base64.b64decode(img)
# 转换之后保存的图片路径
fileName = re.findall(r"convert/(.+)", filepath)
file1 = "".join(fileName)
savepath = "转化后的路径" + file1
file = open(savepath, 'wb')
file.write(img_data)
file.close()
if __name__ == "__main__":
gen_img()
执行结果如下:
评论区