Python 打造顏值評分應用(一):使用百度開發者平臺API獲取顏值

首先打開百度AI開放平臺: https://ai.baidu.com/ ,登錄自己的百度賬號(與百度網盤賬號相同)。然後打開控制檯,在左側導航選擇人臉分析。(圖片不清晰的話可以放大看)

然後點擊創建應用,把必填的填寫一下。然後就可以拿到API Key和Secret Key:

接下來,我們就需要使用這些密鑰進行人臉分析了。

首先,我們需要根據API Key,和SecretKey來獲取token:

def getToken():
    # client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=YourOwnAK&client_secret=YourOwnSK'
    response = requests.get(url=host,verify=False)
    if response:
        # print(response.json())
        accessToken=response.json()['access_token']
        return accessToken
    else:
        raise ValueError('無網絡連接')

拿到token後,我們還需要將一張圖片轉換爲字符格式以便於雲端識別:

# 將一張圖片轉換爲字符格式
def getImage2Base64(imagePath):
    f = open(imagePath, 'rb')
    img = base64.b64encode(f.read()).decode('utf-8')
    return img

接下來是整體函數liao:

def getAttribute(imagePath):
    img=getImage2Base64(imagePath)
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
    params = {"image": img, "image_type": "BASE64",
              "face_field": "age,gender,beauty"}
    header = {'Content-Type': 'application/json'}

    access_token = getToken()

    request_url = request_url + "?access_token=" + access_token
    response1 = requests.post(url=request_url, data=params, headers=header,verify=False)
    json1 = response1.json()
    # print("性別爲", json1["result"]["face_list"][0]['gender']['type'])
    # print("年齡爲", json1["result"]["face_list"][0]['age'], '歲')
    print(json1)
    theSex=json1["result"]["face_list"][0]['gender']['type']
    theAge=json1["result"]["face_list"][0]['age']
    theBeauty=json1["result"]["face_list"][0]['beauty']
    return theSex,str(theAge),theBeauty

getAttribute函數中需要注意的一個是params,你可以選擇你需要得到人臉圖片的哪些信息(年齡,性別,顏值等)。看起來是不是很簡單。但其實這裏涉及到一個坑。我們這裏代碼的request.get和request.post函數參數中,verify都設置爲了False,爲什麼這麼設置?如果不這樣設置,pyintaller打包應用時,會顯出證書錯誤。想要具體瞭解的話,可以查看我的博客:tkinter+request+pyinstaller證書錯誤解決辦法

下一篇主要內容:基於tkinter開發界面。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章