【基於百度AI的人臉識別Python實現】

調用百度AI的baidu-aip庫進行人臉識別,baidu-aip庫可以使用pip install baidu-aip進行安裝

關於人臉檢測請求參數可參考傳送門

運行代碼如下:

# coding=UTF-8
# 利用baidu-aip庫進行人臉識別
import cv2
import matplotlib.pyplot as plt
from aip import AipFace


def detection(APP_ID, API_KEY, SECRET_KEY, filename, maxnum):
    '''

    :param APP_ID: https://console.bce.baidu.com/ai/創建人臉檢測應用對應的APP_ID
    :param API_KEY: https://console.bce.baidu.com/ai/創建人臉檢測應用對應的API_KEY
    :param SECRET_ID: https://console.bce.baidu.com/ai/創建人臉檢測應用對應的SECRET_ID
    :param filename: 圖片路徑
    :param maxnum: 最大檢測數
    :return:
    '''
    # 初始化AirFace對象
    aipface = AipFace(APP_ID, API_KEY, SECRET_KEY)

    # 設置
    options = {
        'max_face_num': 10,  # 檢測人臉的最大數量
        'face_fields': "age,beauty,expression,faceshape",
    }

    # 讀取文件內容
    def get_file_content(filePath):
        with open(filePath, 'rb') as fp:
            return fp.read()

    result = aipface.detect(get_file_content(filename), options)
    return result


def result_show(filename, result):
    '''

    :param filename: 原始圖像
    :param result: 檢測結果
    :return:
    '''
    img = cv2.imread(filename)
    face_num = len(result['result'])
    for i in range(face_num):
        location = result['result'][i]['location']
        left_top = (location['left'], location['top'])
        right_bottom = (left_top[0] + location['width'], left_top[1] + location['height'])
        cv2.rectangle(img, left_top, right_bottom, (200, 100, 0), 2)

    cv2.imshow('img', img)
    cv2.waitKey(0)


if __name__ =='__main__':

    # 定義APP_ID、API_KEY、SECRET_KEY
    APP_ID = '10761235'
    API_KEY = 'PF4Ytr53mYdeKY8fjChE4Elh'
    SECRET_KEY = 'q83srw3x3YDg6nTIh4I7ZzscntT7qWWO '

    filename = 'girl.jpg'
    result = detection(APP_ID, API_KEY, SECRET_KEY, filename, 10)
    result_show(filename, result)



運行結果如下:



換張圖像試試效果:


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