百度智能云产品体验之图像风格转换
鹿鼎记肯定 发布于2020-08 浏览:3168 回复:1
0
收藏
最后编辑于2022-04

注意: 图片文件类型支持PNG、JPG、JPEG、BMP,图片大小不超过2M。

 

图像风格转换

import requests, base64, sys

####################
### 自己修改的地方 ###
####################
API_Key = 【API Key】    # 填写API Key
Secret_Key = 【Secret Key】    # 填写Secret Key
photo = 【image】    # 输入图片的路径
option = 【option】    # 选择一个风格
'''
cartoon:卡通画风格
pencil:铅笔风格
color_pencil:彩色铅笔画风格
warm:彩色糖块油画风格
wave:神奈川冲浪里油画风格
lavender:薰衣草油画风格
mononoke:奇异油画风格
scream:呐喊油画风格
gothic:哥特油画风格
'''


# 第一次 Post 请求,获取access_token
def get_access_token():
    # URL
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    # 参数
    params = {
        'grant_type': 'client_credentials',    # 固定值  
        'client_id': API_Key,  
        'client_secret': Secret_Key  
    }
    res = requests.post(url, data=params)
    # 请求成功 返回access_token和expires_in
    # 请求失败 返回error和error_description
    res = res.json()
    access_token = res['access_token']
    return access_token
    
# 第二次 Post 请求
# 二进制方式打开图片文件
with open(photo, 'rb') as f:
    # 图像转为base64的格式
    img = base64.b64encode(f.read()) 
    # 定义params和header
    params = {"image": img, "option": option}
    header = {'content-type': 'application/x-www-form-urlencoded'}
    # 发送请求
    request_url = "https://aip.baidubce.com/rest/2.0/image-process/v1/style_trans"
    try:
        request_url = request_url + "?access_token=" + get_access_token()
    except KeyError:
        print("access_token有误!请检查API Key 或 Secret Key是否复制正确")
        sys.exit(0)
    response = requests.post(request_url, data=params, headers=header)
    res = response.json()

with open(photo.split(".")[0] + "_" + option + ".jpg", 'wb') as f:
    processed_img = res['image']
    processed_img = base64.b64decode(processed_img)
    f.write(processed_img)
收藏
点赞
0
个赞
共1条回复 最后由用户已被禁言回复于2022-04
#2鹿鼎记肯定回复于2020-08

社区的markdown什么时候能出一个语法高亮啊。。哎,编辑的时候是有的,一发帖就没了

0
TOP
切换版块