python 簡單實現人臉檢測

目錄

 

一、準備

二、實現

三、結果

四、代碼


一、準備

  1. python 3.7版本(其他版本也可以)
  2. matplotlib  畫圖工具,安裝方式:pip install matplotlib
  3. PIL 圖像處理 ,安裝方式:pip install pillow
  4. 實現人臉檢測的算法通過引用百度智能雲的人臉檢測API

二、實現

要想成功調用百度的人臉檢測接口,需要先獲取access token。首先在百度智能雲後臺創建一個新應用獲取到AppID、API Key、Secret Key。

然後向授權服務地址https://aip.baidubce.com/oauth/2.0/token發送請求(推薦使用POST)

# encoding:utf-8
import requests 

# client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK
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:
    print(response.json())

詳細的接口文檔說明見:https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu

獲取到Access Token 後就能正常訪問人臉檢測接口了,請求URL: https://aip.baidubce.com/rest/2.0/face/v3/detect

參數landmark、landmark72、 landmark150返回特徵點

詳細說明見官方文檔:https://cloud.baidu.com/doc/FACE/s/yk37c1u4t

最後利用matplotlib在圖像上繪製特徵點

 

三、結果

四、代碼

import requests
from PIL import Image
import matplotlib.pyplot as plt
import base64

APP_ID = ''                                # 百度後臺應用生成的AppID、API Key和Secret Key
API_KEY = ''
SECRET_KEY = ''


# post請求
def post_url(url, param):
    headers = {'content-type': 'application/json'}
    response = requests.post(url, data=param, headers=headers)
    return response.json()


# 獲取Access Token
def get_access_token():
    host = 'https://aip.baidubce.com/oauth/2.0/token'
    param = {'grant_type': 'client_credentials', 'client_id': API_KEY, 'client_secret': SECRET_KEY}
    response = post_url(host, param)
    return response['access_token']


# 人臉檢測
def face_detect(file, access_token):
    host = 'https://aip.baidubce.com/rest/2.0/face/v3/detect'   # 接口地址
    url = host + "?access_token=" + access_token
    with open(file, 'rb') as f:
        img_base64 = base64.b64encode(f.read())                 # 將圖像進行base64轉換
    param = {'image': img_base64,
             'image_type': 'BASE64', 'max_face_num': 10,        # 設置圖像類型爲base64,最大檢測人臉數量爲10
             'face_field': 'age,beauty,expression,face_shape,gender,glasses,landmark,landmark150,race,quality,'
                           'eye_status,emotion,face_type,mask,spoofing'}
    response = post_url(url, param)
    print(response)
    return response


# 繪製特徵點
def img_draw(file, arr):
    image = Image.open(file)
    plt.figure("face")
    plt.imshow(image)
    x_arr = []
    y_arr = []
    for m in range(len(arr)):
        point = arr[m]
        x = point['x']
        y = point['y']
        x_arr.append(x)
        y_arr.append(y)
    plt.plot(x_arr, y_arr, 'r.')
    plt.axis('off')
    plt.show()


if __name__ == '__main__':
    access_token = get_access_token()                       # 獲取access token
    file_path = '7.jpg'                                     # 圖像路徑
    img_info = face_detect(file_path, access_token)         # 調用百度的人臉識別API
    face_list = img_info['result']['face_list']
    face_num = img_info['result']['face_num']
    data = []
    for i in range(face_num):
        data = data + face_list[i]['landmark72']            # 獲取特徵點
    img_draw(file_path, data)                               # 繪製圖像

 

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