カメラに映った人物を認識し、名前をリアルタイムで表示する顔認識システムは、出席管理や入退室記録、受付無人化などで活用されています。Pythonでは、OpenCVとface_recognitionライブラリを使うことで、簡単に顔認識システムを構築できます。
この記事では、複数人の顔データを登録し、Webカメラからの映像に対して「誰か」を特定し、名前を表示する仕組みを構築する方法を解説します。
必要なライブラリのインストール
pip install face_recognition opencv-python
face_recognition
は、Dlibベースの高精度な顔認識ライブラリです。
1. 事前に顔画像と名前を登録する
「known_faces」フォルダに、名前付きの画像ファイルを以下のように保存します。
known_faces/
├── tanaka.jpg
├── yamada.jpg
└── suzuki.jpg
2. 顔特徴量データベースを構築する
import face_recognition
import os
known_encodings = []
known_names = []
for filename in os.listdir("known_faces"):
if filename.endswith(".jpg") or filename.endswith(".png"):
name = os.path.splitext(filename)[0]
image = face_recognition.load_image_file(f"known_faces/{filename}")
encodings = face_recognition.face_encodings(image)
if encodings:
known_encodings.append(encodings[0])
known_names.append(name)
3. Webカメラでリアルタイム認識
import cv2
video = cv2.VideoCapture(0)
while True:
ret, frame = video.read()
rgb = frame[:, :, ::-1] # BGR→RGB
face_locations = face_recognition.face_locations(rgb)
face_encodings = face_recognition.face_encodings(rgb, face_locations)
for (top, right, bottom, left), encoding in zip(face_locations, face_encodings):
matches = face_recognition.compare_faces(known_encodings, encoding)
name = "不明"
if True in matches:
match_index = matches.index(True)
name = known_names[match_index]
# 枠と名前を表示
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2)
cv2.imshow("Face Recognition", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video.release()
cv2.destroyAllWindows()
特徴と注意点
- 顔画像は正面・高解像度のものを使用すると精度が上がります
- マスク・帽子・眼鏡などで精度が低下する場合があります
- 比較対象が多くなると処理速度が落ちるため、事前の特徴量保存や高速化が必要です
応用例
- 入退室ログをCSVファイルに記録
- SlackやLINEで「◯◯さんが入室しました」と通知
- 顔認識後、自動でドアを解錠する仕組みに連携
まとめ
PythonとOpenCV、face_recognitionを使えば、顔認識と名前表示のリアルタイムシステムを簡単に構築できます。カメラに映った人物を即座に特定できる仕組みは、防犯や勤怠、施設管理など多くのシーンで活用が見込まれます。
今後は、深層学習モデルによる顔認識やクラウドとの連携によるスケーラブルな顔認証システムへ発展させることも可能です。