画像を読み込みます。
import numpy as np |
from PIL import Image |
from PIL import ImageDraw |
import face_recognition |
# 丸山所長 |
image_maruyama_1 = face_recognition.load_image_file("maruyama_san_1.png") |
image_maruyama_2 = face_recognition.load_image_file("maruyama_san_2.jpg") |
# 加藤 |
image_kato_1 = face_recognition.load_image_file("kato_1.png") |
image_kato_2 = face_recognition.load_image_file("kato_2.jpg") |
# 綾塚さん |
image_ayatuka_1 = face_recognition.load_image_file("ayatuka_san_1.jpg") |
image_ayatuka_2 = face_recognition.load_image_file("ayatuka_san_2.jpg") |
アライメントされた顔領域を取得します。
# 顔を囲む領域を抽出する |
# model=cnnにしないとbboxがかなりずれる。結果としてencodingの値もおかしくなるっぽい。 |
# 丸山所長 |
img_maruyama_1 = Image.fromarray(np.array(image_maruyama_1)) |
loc_maruyama_1 = face_recognition.face_locations(image_maruyama_1, model="cnn") |
top, right, bottom, left = loc_maruyama_1[0] |
draw = ImageDraw.Draw(img_maruyama_1) |
draw.rectangle((right, top, left, bottom)) |
img_maruyama_1 |
# 128bytesの顔の特徴ベクトルを取得する |
encoding_maruyama_1 = face_recognition.face_encodings(image_maruyama_1, known_face_locations=loc_maruyama_1)[0] |
encoding_maruyama_2 = face_recognition.face_encodings(image_maruyama_2, known_face_locations=loc_maruyama_2)[0] |
encoding_kato_1 = face_recognition.face_encodings(image_kato_1, known_face_locations=loc_kato_1)[0] |
encoding_kato_2 = face_recognition.face_encodings(image_kato_2, known_face_locations=loc_kato_2)[0] |
encoding_ayatuka_1 = face_recognition.face_encodings(image_ayatuka_1, known_face_locations=loc_ayatuka_1)[0] |
encoding_ayatuka_2 = face_recognition.face_encodings(image_ayatuka_2, known_face_locations=loc_ayatuka_2)[0] |
# 特徴ベクトル間の距離をメッシュで計算した表を可視化する |
encodings = np.array([encoding_maruyama_1, encoding_maruyama_2, encoding_kato_1, encoding_kato_2, encoding_ayatuka_1, encoding_ayatuka_2]) |
index = np.arange(encodings.shape[0]) |
ix, iy = np.meshgrid(index, index) |
distances = np.linalg.norm(encodings[ix]-encodings[iy], axis=2) |
import seaborn as sns |
import pandas as pd |
df = pd.DataFrame(distances, |
index=["maruyama", "maruyama", "kato", "kato", "ayatuka", "ayatuka"], |
columns=["maruyama", "maruyama", "kato", "kato", "ayatuka", "ayatuka"], |
) |
sns.heatmap(df, annot=True, fmt=".2f") |