<< home

Pythonによる顔認証システムの構築

本章では、Pythonを使用して簡単な顔認証システムを構築します。face_recognitionライブラリを使用し、事前に登録した顔とカメラからの画像を比較して認証を行います。


1. 顔認証システムのソースコード

1.1 必要なライブラリのインストール

pip install face-recognition opencv-python numpy

1.2 ソースコード

以下のコードは、カメラを使用してリアルタイムで顔認証を行うプログラムです。

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()

2. 顔認証システムのポイント

2.1 face_recognition.load_image_file()

known_image = face_recognition.load_image_file("known_face.jpg")

2.2 face_recognition.face_encodings()

known_encoding = face_recognition.face_encodings(known_image)[0]

2.3 face_recognition.face_locations()

face_locations = face_recognition.face_locations(rgb_frame)

2.4 face_recognition.compare_faces()

matches = face_recognition.compare_faces([known_encoding], face_encoding)

2.5 OpenCVを使った描画

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)

3. まとめ

このコードを応用すれば、複数の顔を登録したり、出席管理やドアロックシステムに組み込むことも可能です。



<< home