调用百度API,图片无损放大

本文介绍了一种利用百度AI平台的图像质量增强服务来提升图片清晰度的方法。通过获取访问令牌并调用图像质量增强API,可以将原始图片转换为更高质量的版本。文章详细展示了如何使用Python代码实现这一过程。
# -*- coding: UTF-8 -*-
import base64
import requests

def get_img_base64str(image):
    with open(image,'rb') as fp:
        imgbase64 = base64.b64encode(fp.read())
        return imgbase64.decode()

def get_access_token(APP_ID,API_KEY,SECRET_KEY):
    params     = {
        "grant_type":   "client_credentials",
        'client_id':    API_KEY,
        'client_secret':SECRET_KEY,}
    token_url = 'https://aip.baidubce.com/oauth/2.0/token'
    res = requests.get(token_url,params = params)
    try:
        data = res.json()
        return data['access_token']
    except:
        return ''

def enlarge_image(image_file,access_token):
    image       = get_img_base64str(image_file)
    data        = {"image":image}
    params       = {'access_token':access_token}
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/image_quality_enhance"
    res = requests.post(request_url,params = params,data = data)
    try:
        image_data = res.json()['image']
        img_bytes  = base64.b64decode(image_data)
        with open("res.png",'wb') as fp:
            fp.write(img_bytes)
        print ("Success!")
    except:
        print ("ERROR!")


if __name__ == '__main__':
    APP_ID     = '******'
    API_KEY    = '*******'
    SECRET_KEY = '*******'

    file = "3.png"
    access_token = get_access_token(APP_ID,API_KEY,SECRET_KEY)
    enlarge_image(file,access_token)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值