使用Python调用百度API进行多目标检测

此篇文章在2022年2月20日被记录

直接上代码:

    # encoding:utf-8
    import requests 
    import base64
    import cv2
    from xpinyin import Pinyin
    p = Pinyin()
    img_src=r"C:\Users\TSK\Desktop\test.png"
    display_img = cv2.imread(img_src)
    # client_id 为官网获取的AK, client_secret 为官网获取的SK
    AK='KdM8qXGKlfaGVkZT4bHuwW2n'
    SK='ZEM9Kr2M44RPcdZWll7DHgFFIorBwFlg'
    request_url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/multi_object_detect"
    f = open(img_src, 'rb')
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+AK+'&client_secret='+SK
    response = requests.get(host)
    if response:
        access_token=response.json()['access_token']
        print("get access_token="+access_token)
    else :
        print("get access_token is failed!")
    
    img = base64.b64encode(f.read())
    params = {"image":img}
    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)
    if response:
        obj=response.json()['result']
        for x_obj in obj:
            if x_obj['score']>0.5:
                print(x_obj['location']['top'])
                print(x_obj['location']['left'])
                print(x_obj['location']['width'])
                print(x_obj['location']['height'])
                x=int(x_obj['location']['left'])
                y=int(x_obj['location']['top'])
                w=int(x_obj['location']['width'])
                h=int(x_obj['location']['height'])
                cv2.rectangle(display_img,(x,y),(x+w,y+h),(0, 255, 0), 2,0)
                cv2.putText(display_img,p.get_pinyin(x_obj['name']),(x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.5,( 0,255,0),1,cv2.LINE_AA)    
    cv2.imshow('img', display_img)
    cv2.waitKey(0)

识别结果:

img

代码思路:

调用百度API时,首先通过get的方式获取access_token,需要发送自己的client_id与client_secret,access_token是一成不变的,我们可以单独保存下来以后使用,但是在我的代码中我选择每次重新申请一次。
然后根据官方API需求设置头部headers = {'content-type': 'application/x-www-form-urlencoded'},在对post包进行封装,需要注意的是,图片是通过params传入,图片得格式需要转为base64格式,url封装完成后进行一次post请求,对结果进行解析,使用opencv画图函数将框花在图片上并且显示出来,需要注意的是,为了简单我在将类别名称转为拼音显示出来,而不是使用中文显示。

posted @ 2024-12-09 15:17  shumei52  阅读(39)  评论(0)    收藏  举报