>  기사  >  백엔드 개발  >  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 클래스를 사용하여 OpenCV와 함께 제공되는 "haarcascade_frontalface_default.xml"이라는 분류자를 로드합니다. 그런 다음 "test.jpg"라는 이미지를 읽고 이를 회색조 이미지로 변환합니다. 다음으로, discoverMultiScale 함수를 사용하여 이미지에서 얼굴을 감지합니다. discoverMultiScale 함수는 얼굴의 위치와 크기를 포함하는 직사각형 목록을 반환합니다. 마지막으로 원본 이미지에 직사각형을 그려 감지된 얼굴을 표시합니다.

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. 얼굴 특징 추출: 각 얼굴 이미지에 대해 특징을 추출해야 합니다. 두 번째 코드 예제의 방법을 사용하여 얼굴 특징을 추출할 수 있습니다.

  3. 얼굴 인식 모델 구축: 얼굴 인식 모델을 구축하려면 추출된 얼굴 특징을 사용해야 합니다. Dlib 라이브러리의 Face_recognition 모듈을 사용하여 이를 달성할 수 있습니다. Face_recognition 모듈은 얼굴 이미지를 128개의 특징이 포함된 벡터로 변환하는 "face_encodings"라는 함수를 제공합니다. 이러한 벡터를 얼굴 데이터베이스로 하드 드라이브에 저장할 수 있습니다.

  4. 얼굴 인식: 얼굴 이미지를 인식하려면 두 번째 코드 예제의 방법을 사용하여 특징을 추출할 수 있습니다. 그런 다음 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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 yisu.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제