福岡人データサイエンティストの部屋

データサイエンスを極めるため、日々の学習を綴っています。

【Pillow(PIL)】浜辺美波と橋本環奈【face_recognition】【Python】



こんにちは!こーたろーです。


前にOpenCVで顔の検出を行いましたが、今回はOpenCVではなく、【face_recognition】というものを使ってみました。


そして、浜辺美波と橋本環奈の顔を比較して、違いが分かるのかを評価していきます。


結果はいかに・・・・


それでは早速まいりましょう!


ライブラリのインポート



今回は、顔の検出に【face_recognition】、画像の操作にPillow(PIL)を使いました。

import face_recognition
from PIL import Image, ImageDraw


画像データの取得及び顔の位置検出



画像データとしては、Webで取得できる画像を持ってきて、事前に保存しておき、それを呼び出します。

image = face_recognition.load_image_file("minami1.png")
face_locations = face_recognition.face_locations(image)
face_locations  



face_recognitionのface_locationメソッドに画像データを投入し、顔の位置検出を行います。


この時のface_locationの出力としては、(x1,y1, x2,y2)の様に出力され、この4つのラインで囲まれた部分が顔の部分となります。




顔検出した位置の確認



顔検出の位置確認は、以前にもやったように赤ラインで枠で囲んでみるという形で行います。


face_detectionという関数を作り、画像情報と出力したロケーション情報から、元画像に対して赤四角ラインを追加するものをつくり、実行しています。

def face_detection(image, face_locations):
    face_locations = (face_locations[0][1],face_locations[0][0],face_locations[0][3],face_locations[0][2])
    im = Image.fromarray(image)
    draw = ImageDraw.Draw(im)
    draw.rectangle(face_locations, fill = None, outline = (255,0,0), width = 5)
    return im

face_detection(image, face_locations)



結果は次の様になっています。





ちゃんとかわいい顔が検出できていますね。

異なる画像の取り込み



次は、異なる画像の顔を検出し、それらが同一人物かを確認していきます。


まずはデータの取り込みから。

image1 = face_recognition.load_image_file("minami1.png")
image2 = face_recognition.load_image_file("minami2.png")
image3 = face_recognition.load_image_file("kanna.png")

encoding1 = face_recognition.face_encodings(image1)[0]
encoding2 = face_recognition.face_encodings(image2)[0]
encoding3 = face_recognition.face_encodings(image3)[0]



face_recognition.face_encordingsは、画像の顔の部分から識別に有用な特徴量を抽出するものです。


この特徴量に対して、どれだけ同じか・異なっているかをしきい値を与えて判別していきます。


ちなみに、今回使用した画像はコチラになります。





画像の識別



それでは早速、識別を行っていきます。


特徴量を比較して、同一人物かを判別するcompare_facesメソッドを使っていきます。


特徴量を抽出したencodingファイルを比較していきます。


この時、toleranceを指定しますが、このtoleranceは、どれぐらい厳しく判定するかを示す値で、値が小さいほど厳しくジャッジしていきます。

tolerance = 0.4
print(face_recognition.compare_faces([encoding1], encoding2, tolerance=tolerance))
print(face_recognition.compare_faces([encoding1], encoding3, tolerance=tolerance))
print(face_recognition.compare_faces([encoding2], encoding3, tolerance=tolerance))



結果はというと、





無事に識別できていそうです。


なお、toleranceを変更すると


tolerance = 0.5





tolerance = 0.3





ジャッジは厳しすぎても緩すぎてもいけないということですね。


ではでは。


ディジタル画像処理 [改訂第二版]