python在线调用AI平台API的几种方法

1、最简单的是用requests,支持post/get,也支持header格式,例如:

# face++ detect face attribute (jpg/png)
def detface(image_file, return_landmark=0):
    http_url = "https://api-cn.faceplusplus.com/facepp/v3/detect"   # url地址


    f = open(image_file, 'rb')  # 用open,而不用imread,保留jpg格式信息 #frame = cv2.imread(imgfile)

    img = base64.b64encode(f.read()) # 参数images:图像base64编码,把byte类型的img转换为str类型
    data = {"api_key": api_key, "api_secret": api_secret, "image_base64":img}  #post的表格


    #采用image_file参数时,要用multipart/form-data的方式上传

    #request.add_header('Content-Type', 'multipart/form-data')  

    response = requests.post(http_url, data=data)  # 发出连接请求
   
    res = response.content.decode('utf-8')      #读取结果,并解码
    return res


   
2.用Popen调用curl命令,例如(face++):

def compareTtoT(face_token_1,face_token_2):
    result=Popen('curl -X POST "https://api-cn.faceplusplus.com/facepp/v3/compare" -F \
        "api_key={api_key}" -F \
        "api_secret={api_secret}" -F \
        "face_token1={face_token_1}" -F \
        "face_token2={face_token_2}"'
        .format(api_key=api_key,api_secret=api_secret,face_token_1=face_token_1,
          face_token_2=face_token_2),shell=True,stdout=PIPE) 
    wait=""
    result=(result.stdout.read())
    return result

3、用urllib库(百度),例如:

# 识别图片中的人脸
def detFace(token, imgfile):
    f = open(imgfile, 'rb')  # 用open,而不用imread,保留jpg格式信息 #frame = cv2.imread(imgfile)
    img = base64.b64encode(f.read()) # 参数images:图像base64编码,把byte类型的img转换为str类型
    
params= {"face_fields":"age,beauty,expression,faceshape,glasses,landmark,race,qualities","image":img,"max_face_num":5}
    params = urllib.parse.urlencode(params).encode("utf-8")

    request_url = "https://aip.baidubce.com/rest/2.0/face/v1/detect"
    request_url = request_url + "?access_token=" + token
    request = urllib.request.Request(url=request_url, data=params)
    request.add_header('Content-Type', 'application/x-www-form-urlencoded')
    
    response = urllib.request.urlopen(request)
    content = response.read()

    return content
   

4、用调用windows DLL (科大讯飞)

from ctypes import *  
import ctypes
import time

# 加载 dll
kdxf_dll = ctypes.windll.LoadLibrary("msc_x64.dll")    

#设置返回值类型
kdxf_dll.QTTSSessionBegin.restype = ctypes.c_char_p

# 字符串数组的类型及变量
#str = b"engine_type = cloud, voice_name = xiaoyan, text_encoding = UTF8 "
#paramsp = ctypes.cast(str, ctypes.POINTER(ctypes.c_ubyte))  #
paramsp = create_string_buffer(b"engine_type = cloud, voice_name = xiaoyan, text_encoding = UTF8 ")

# POINTER:类型指针化,但不能用作参数
errorCode =  ctypes.c_int()
errorCodep =  ctypes.byref(errorCode)      


print( "sessionID = ", kdxf_dll.QTTSSessionBegin(paramsp, errorCodep) )
print("params =", repr(paramsp.raw))

print("errorCode = ", errorCode)



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值