LoginSignup
1
0

More than 5 years have passed since last update.

PowerShell で FaceAPI に投げてみる

Last updated at Posted at 2018-11-04

今日の投稿背景

次の案件で、PowershellでいろんなAPIに投げてみたいという要望があったので
備忘録的にやってみた

参考にした記事

@miyamiya さんの PowerShell で Cognitive Services の呼び出し方
Invoke-RestMethod

FaceAPI用に作ったPowershell

FaceAPI_Detect_Post.ps1
$Face_API_KEY = '<FaceAPI Key>'
$URL = 'https://japaneast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=true&returnFaceAttributes=age,gender,smile,facialHair,headPose,glasses,emotion,hair,makeup,accessories,blur,exposure,noise'
$image = '<FaceAPIに投げるファイルのフルパス>'
$headers = @{ 
    'Ocp-Apim-Subscription-Key' = $Face_API_KEY
    'Accept' = 'application/json'
    'Content-Type' = 'application/octet-stream'
}

$result = Invoke-RestMethod `
    -Uri $URL `
    -Method Post `
    -Headers $headers `
    -InFile $image

$result | format-list

出力結果

faceId         : 
faceRectangle  : @{top=337; left=746; width=318; height=318}
faceLandmarks  : @{pupilLeft=; pupilRight=; noseTip=; mouthLeft=; mouthRight=; eyebrowLeftOuter=; eyebrowLeftInner=; ey
                 eLeftOuter=; eyeLeftTop=; eyeLeftBottom=; eyeLeftInner=; eyebrowRightInner=; eyebrowRightOuter=; eyeRi
                 ghtInner=; eyeRightTop=; eyeRightBottom=; eyeRightOuter=; noseRootLeft=; noseRootRight=; noseLeftAlarT
                 op=; noseRightAlarTop=; noseLeftAlarOutTip=; noseRightAlarOutTip=; upperLipTop=; upperLipBottom=; unde
                 rLipTop=; underLipBottom=}
faceAttributes : @{smile=0.743; headPose=; gender=female; age=21.0; facialHair=; glasses=NoGlasses; emotion=; blur=; ex
                 posure=; noise=; makeup=; accessories=System.Object[]; hair=}

出力結果の形式はともかく、とりあえず投げることができますね!

JSONをPSCustomObjectに変換する

とりあえず、上記の出力結果だと、データが取り出せないので意味ないですよね。
なので、ConvertFrom-Jsonを使って、PowerShell内で扱えるようにしましょう。

JSON応答対応版

FaceAPI_Detect_Post.ps1
$Face_API_KEY = '<FaceAPI Key>'
$URL = 'https://japaneast.api.cognitive.microsoft.com/face/v1.0/detect?returnFaceId=true&returnFaceLandmarks=true&returnFaceAttributes=age,gender,smile,facialHair,headPose,glasses,emotion,hair,makeup,accessories,blur,exposure,noise'
$image = '<FaceAPIに投げるファイルのフルパス>'
$headers = @{ 
    'Ocp-Apim-Subscription-Key' = $Face_API_KEY
    'Accept' = 'application/json'
    'Content-Type' = 'application/octet-stream'
}

$result = Invoke-RestMethod `
    -Uri $URL `
    -Method Post `
    -Headers $headers `
    -InFile $image

$result_ps = ($result | ConvertFrom-Json)

データの取り出し方

たとえば、一番出現率の高い髪の色は何だ?というときはこういう風にします。

($result_ps.faceAttributes.hair.hairColor | `
 Sort-Object -Property confidence -Descending | `
 Select-Object -First 1).Color

Powershell でも

APIに問い合わせることができますし
JSONも難なくつかえますね!

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0