2020/12/27
前回の続きです。今回はAzure Computer Visionの顔認識のお話をします。
コードは、画像を読み込み、画像の中の顔を抽出し、性別と年齢、および検出した画像エリアの座標(左上と右下の点)を返すものです。AzureのComputer Visionの
Quick Startと
GitHubにコードがありますので、参考にしました。実行したコードは以下の通り。
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
from array import array
import os
from PIL import Image
import sys
import time
# Azure setting
subscription_key = "・・・・・・"
endpoint = "https://azure-computer-vision.cognitiveservices.azure.com/"
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
# Image file
local_image_path = "./faces.jpg"
#--------------------
# Detect Faces
#--------------------
# Open local image
local_image = open(local_image_path, "rb")
# Select visual features(s) you want
local_image_features = ["faces"]
# Call API with local image and features
detect_faces_results_local = computervision_client.analyze_image_in_stream(local_image, local_image_features)
print("===== Detect Faces =====")
# Print results with confidence score
print("Faces in the local image: ")
if (len(detect_faces_results_local.faces) == 0):
print("No faces detected.")
else:
for face in detect_faces_results_local.faces:
print("'{}' of age {} at location {}, {}, {}, {}".format(face.gender, face.age, \
face.face_rectangle.left, face.face_rectangle.top, \
face.face_rectangle.left + face.face_rectangle.width, \
face.face_rectangle.top + face.face_rectangle.height))
print()
13、14行目には個人のazure-computer-visionのキーとエンドポイントを設定しました。
実行結果です。

コードを実行するだけでは以下のテキストデータの結果しか得られません。
===== Detect Faces =====
Faces in the local image:
'Male' of age 39 at location 118, 159, 212, 253
'Male' of age 54 at location 492, 111, 582, 201
'Female' of age 55 at location 18, 153, 102, 237
'Female' of age 33 at location 386, 166, 467, 247
'Female' of age 18 at location 235, 158, 311, 234
'Female' of age 8 at location 323, 163, 391, 231
性別と年齢、検出エリアの座標(Left、Top、Right、Bottomの順)です。この座標情報から検出エリアと検出順番(0番スタート)を生画像に描画するコードを書いたのが上の画像です。

さすがにサンプル画像なので判定された性別も年齢も正しそうですね。
顔認識の実力を知るには大勢の人が写っている画像が良いと思って試してみたのがこれです。元画像サイズは1200×800ピクセルです。

人が密集しているせいか、頭の陰になっている人や漫画チックのものは検出出来ていないようですね。
ネット情報から検出されたのが誰なのか調べた結果が以下の表です。


性別は正しく判断しているようですが、年齢の判定結果がひどいですね。George、John、Paul、Ringoがそれぞれ48歳、46歳、38歳、35歳で年を取りすぎています・・。蝋人形は実物よりも若く出ていますが、それでも年取っていますね。Beatlesメンバー以外の人の名前、年齢は良く分からないので判断が難しいです。左下の福助人形が検出できなかったのも残念。下にうつむいているのがNGなのかな??
仕切り直して、次はフルベッキの幕末志士の画像です。合成写真のいわく付きのものですね。元画像サイズは2004×1428ピクセルです。左最上段一人だけ前の人の陰になって検出できませんでしたが、その他は全部検出できています。

これも写っているのが誰なのかを
ネット情報でまとめると以下の通り。ネット情報では年齢も記載されていたので、転記しました。


性別間違いが見られます。幕末の髪型(ちょんまげ)まではAIで学習されていないのでしょう・・。顔が童顔なのでしょうか、年齢が実年齢より若く判定されているケースが多く見受けられます。10番の大村益次郎が9歳はないやろ・・(笑)。フルベッキの長男が44番に写っているのですが、子供であることは分かるんですね。大したものです。
今回も楽しくAzure Computer Visionの顔認識で遊ぶことができました。次回は、文字認識についてお話します。