KAMEYA_WORKS
本章では、Pythonを使用して簡単な顔認証システムを構築します。face_recognition
ライブラリを使用し、事前に登録した顔とカメラからの画像を比較して認証を行います。
pip install face-recognition opencv-python numpy
以下のコードは、カメラを使用してリアルタイムで顔認証を行うプログラムです。
import cv2
import face_recognition
import numpy as np
# 事前に登録する顔画像の読み込み
known_image = face_recognition.load_image_file("known_face.jpg")
known_encoding = face_recognition.face_encodings(known_image)[0]
# カメラの起動
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
# 現在のフレームの顔を検出
rgb_frame = frame[:, :, ::-1] # OpenCVはBGR、face_recognitionはRGB
face_locations = face_recognition.face_locations(rgb_frame)
face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)
for face_encoding, face_location in zip(face_encodings, face_locations):
# 顔の照合
matches = face_recognition.compare_faces([known_encoding], face_encoding)
name = "Unknown"
if True in matches:
name = "Authenticated"
# 顔の周りに枠を描画
top, right, bottom, left = face_location
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# 映像を表示
cv2.imshow('Face Recognition', frame)
# 'q'キーで終了
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
face_recognition.load_image_file()
known_image = face_recognition.load_image_file("known_face.jpg")
known_face.jpg
は事前に登録する顔画像です。face_recognition.face_encodings()
known_encoding = face_recognition.face_encodings(known_image)[0]
face_encodings()
はリストを返すため、[0]
で最初の顔のエンコーディングを取得します。face_recognition.face_locations()
face_locations = face_recognition.face_locations(rgb_frame)
(top, right, bottom, left)
の形式で返します。face_recognition.compare_faces()
matches = face_recognition.compare_faces([known_encoding], face_encoding)
compare_faces()
は、登録された顔とカメラから検出された顔の類似度を比較します。matches
は True
または False
のリストを返します。cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
cv2.putText(frame, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
Authenticated
または Unknown
)を表示します。face_recognition
を使うと簡単に顔認証が実装できる。face_encodings()
で顔の特徴を取得し、compare_faces()
で認証を行う。cv2
) を使って、カメラ画像の処理や描画が可能。q
キーを押すとプログラムを終了できる。このコードを応用すれば、複数の顔を登録したり、出席管理やドアロックシステムに組み込むことも可能です。