首先來看一下識別的效果:這裏需要完整代碼以及SDK的請點擊此處下載:百度圖像處理人像分割
首先需要註冊百度賬號並且創建對應的應用,這裏具體方法如圖:
訪問:http://ai.baidu.com/ 點擊控制檯
登錄後創建應用:
此處注意:圖像識別中的各項功能共用的是一個SDK包,只是不同功能實現的時候使用的函數以及返回參數不同,點擊完創建應用後就可以生成三個我們後期識別過程中必須使用的參數:AppID,API Key和secert key,這裏我們可以點擊查看應用詳情來獲取
至此,前期的準備工作就完成了,這時我們通過Pip或者官網直接下載SDK包,pip下載指令爲:
這裏支持Python版本:2.7.+ ,3.+
如果已安裝pip,執行pip install baidu-aip即可。
如果已安裝setuptools,執行python setup.py install即可。
接下來,在下載的SDK文檔下新建Python文件,當然你也可以使用導入包的模式:
然後創建一個AipBodyAnalysis(亦可以簡單的理解爲一個和百度的一個連接),這裏代碼爲:
from aip import AipBodyAnalysis
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
完成上述工作後我們就可以正式進入到人像分割的實現過程了,具體的官方代碼爲:
""" 讀取圖片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('example.jpg')
""" 調用人像分割 """
client.bodySeg(image);
注意,調用完成後,我們還需要進行二次處理才能獲取到我們需要的圖像(二值圖,前景圖),我們執行人像分割的調用後函數的返回爲:
{
"log_id": 716033439,
"labelmap": "xxxx",
"scoremap": "xxxx",
"foreground": "xxxx"
}
這裏,各個返回值的含義爲:
字段 | 是否必選 | 類型 | 說明 |
---|---|---|---|
labelmap | 是 | string | 分割結果圖片,base64編碼之後的二值圖像,需二次處理方能查看分割效果 |
scoremap | 是 | string | 分割後人像前景的scoremap,歸一到0-255。Base64編碼後的灰度圖文件,圖片中每個像素點的灰度值 = 置信度 * 255,置信度爲原圖對應像素點位於人體輪廓內的置信度,取值範圍[0, 1] |
foreground | 是 | string | 分割後的人像前景摳圖,透明背景,Base64編碼後的png格式圖片。將置信度大於0.5的像素摳出來,並通過image matting技術消除鋸齒 |
log_id | 是 | int64 | 唯一的log id,用於問題定位 |
接下來是博主實現的核心代碼:
from aip import AipBodyAnalysis
import cv2
import numpy as np
import base64
import os
import json
""" 你的 APPID AK SK """
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
client = AipBodyAnalysis(APP_ID, API_KEY, SECRET_KEY)
""" 讀取圖片 """
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
image = get_file_content('test.png')
""" 調用人像分割 """
client.bodySeg(image);
res = client.bodySeg(image)
foreground = base64.b64decode(res['foreground'])
labelmap = base64.b64decode(res['labelmap'])
scoremap = base64.b64decode(res['scoremap'])
nparr_foreground = np.fromstring(foreground,np.uint8)
foregroundimg = cv2.imdecode(nparr_foreground,1)
foregroundimg = cv2.resize(foregroundimg,(512,512),interpolation=cv2.INTER_NEAREST)
im_new_foreground = np.where(foregroundimg==1, 10, foregroundimg)
cv2.imwrite('foreground.png', im_new_foreground)
nparr_labelmap = np.fromstring(labelmap,np.uint8)
labelmapimg = cv2.imdecode(nparr_labelmap,1)
labelmapimg = cv2.resize(labelmapimg,(512,512),interpolation=cv2.INTER_NEAREST)
im_new_labelmapimg = np.where(labelmapimg==1, 255, labelmapimg)
cv2.imwrite('labelmap.png', im_new_labelmapimg)
nparr_scoremap = np.fromstring(scoremap,np.uint8)
scoremapimg = cv2.imdecode(nparr_scoremap,1)
scoremapimg = cv2.resize(scoremapimg,(512,512),interpolation=cv2.INTER_NEAREST)
im_new_scoremapimg = np.where(scoremapimg==1, 255, scoremapimg)
cv2.imwrite('scoremap.png', im_new_scoremapimg)