ホームページ  >  記事  >  バックエンド開発  >  Pythonを使って顔認識機能を実装するにはどうすればよいですか?

Pythonを使って顔認識機能を実装するにはどうすればよいですか?

WBOY
WBOY転載
2023-04-20 22:16:143004ブラウズ

1. 顔検出

顔検出とは、画像またはビデオから顔の位置を検出することを指します。顔検出機能の実装にはOpenCVライブラリを使用します。 OpenCV は、さまざまな画像およびビデオ処理関数をサポートし、複数のプラットフォームで実行できる人気のあるコンピューター ビジョン ライブラリです。

以下は、Python での顔検出のコード例です:

import cv2

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

for (x,y,w,h) in faces:
    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)

cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

このコード例では、OpenCV の CascadeClassifier クラスを使用して、「haarcascade_frontalface_default.xml」という名前の分類子を読み込みます。この分類子には付属しています。 OpenCV は顔検出に使用されます。次に、「test.jpg」という画像を読み取り、グレースケール画像に変換します。次に、detectMultiScale 関数を使用して画像内の顔を検出します。 detectMultiScale 関数は、顔の位置とサイズを含む長方形のリストを返します。最後に、元の画像に長方形を描画して、検出された顔をマークします。

2. 顔の特徴抽出

顔の特徴抽出とは、目、鼻、口などのいくつかの特徴を顔画像から抽出することを指します。顔特徴抽出機能の実装にはDlibライブラリを使用します。 Dlib は、機械学習、コンピューター ビジョン、画像処理に使用される一般的な C ライブラリです。 Dlib は C で書かれていますが、Python インターフェイスも提供しており、Python を使用して Dlib ライブラリの関数を呼び出すことができます。

以下は、Python での顔の特徴抽出のコード例です:

import dlib
import cv2

detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')

img = cv2.imread('test.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

faces = detector(gray)

for face in faces:
    landmarks = predictor(gray, face)
    for n in range(68):
        x = landmarks.part(n).x
        y = landmarks.part(n).y
        cv2.circle(img, (x, y), 2, (255, 0, 0), -1)

cv2.imshow("Output", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

このコード例では、Dlib ライブラリの get_frontal_face_detector 関数とshape_predictor クラスを使用して、「」という名前のファイルを読み込みます。 「shape_predictor_68_face_landmarks.dat」顔の特徴抽出ツール。次に、「test.jpg」という画像を読み取り、グレースケール画像に変換します。次に、検出機能を使用して画像内の顔を検出し、予測機能を使用して顔の特徴を抽出します。予測関数は、顔の特徴点の 68 個の座標を含むリストを返します。最後に、元の画像に円を描いて顔の特徴点をマークします。

3. 顔認識

顔認識とは、抽出された特徴をデータベース内の顔情報と比較して、顔の身元を識別することを指します。顔認識機能の実装にはDlibライブラリを使用します。具体的な実装プロセスは次のとおりです。

  1. 顔データの収集: データベースとしていくつかの顔データを収集する必要があります。カメラを使用してこのデータをキャプチャし、ハードドライブに保存できます。

  2. 顔の特徴抽出: 顔画像ごとに、その特徴を抽出する必要があります。 2 番目のコード例のメソッドを使用して、顔の特徴を抽出できます。

  3. 顔認識モデルの構築: 抽出された顔の特徴を使用して顔認識モデルを構築する必要があります。これは、Dlib ライブラリの face_recognition モジュールを使用して実現できます。 face_recognition モジュールは、顔画像を 128 個の特徴を含むベクトルに変換する「face_encodings」と呼ばれる関数を提供します。これらのベクトルを顔データベースとしてハード ドライブに保存できます。

  4. 顔認識: 顔画像を認識するには、2 番目のコード例のメソッドを使用してその特徴を抽出できます。次に、face_recognition モジュールの Compare_faces 関数を使用して、抽出された特徴を顔データベース内の特徴と比較します。一致すれば、顔が特定されたことになります。

以下は、Python で顔認識を実装するコード例です:

import cv2
import dlib
import face_recognition

known_face_encodings = []
known_face_names = []

# Load the known faces and embeddings
for name in ["person_1", "person_2", "person_3"]:
    image = face_recognition.load_image_file(f"{name}.jpg")
    face_encoding = face_recognition.face_encodings(image)[0]
    known_face_encodings.append(face_encoding)
    known_face_names.append(name)

# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

video_capture = cv2.VideoCapture(0)

while True:
    # Grab a single frame of video
    ret, frame = video_capture.read()

    # Resize frame of video to 1/4 size for faster face recognition processing
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    # Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
    rgb_small_frame = small_frame[:, :, ::-1]

    # Only process every other frame of video to save time
    if process_this_frame:
        # Find all the faces and face encodings in the current frame of video
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            # See if the face is a match for the known face(s)
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            # If a match was found in known_face_encodings, just use the first one.
            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_match_index]

            face_names.append(name)

    process_this_frame = not process_this_frame

    # Display the results
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    # Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()

このコード例では、まず顔データをロードし、face_recognition モジュールを使用して顔認識を実行します。顔特徴ベクトルに変換されます。次に、cv2.VideoCapture 関数を使用してカメラのビデオ ストリームを読み取り、face_recognition モジュールを使用してビデオ ストリーム内の顔を認識します。最後に、OpenCV の関数を使用して、顔認識結果をビデオ ストリームに表示します。

以上がPythonを使って顔認識機能を実装するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。