ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Face_recoginition 소개
    카테고리 없음 2020. 3. 12. 21:24

    face_recognition은 얼굴 인식 라이브러리로, python을 다룰 줄 알고, dlib를 설치하고 그리고 소스코드를 다운받으면 간단한 얼굴 인식 프로그램을 사용할 수 있습니다. 프로그램 사용 예는 밑에 사진과 같습니다.

     

    코드와 밑에 설명할 예제는 다음과 같이 두 사이트에서 다운받을 수 있고, 확인할 수 있습니다.

    https://github.com/ageitgey/face_recognition

    https://ukayzm.github.io/python-face-recognition/

    face_recognition library를 사용해서 얼굴 인식을 한 예

    본 라이브러리의 특징은 세가지가 있습니다.

     

    1. 사진에서 얼굴을 찾습니다

     

    사진에 등장하는 모든 얼굴들을 찾을 수 있습니다. 

    import face_recognition 
    
    image = face_recognition.load_image_file("your_file.jpg") 
    
    face_locations = face_recognition.face_locations(image)

     

    2. 사진에 있는 얼굴의 특징을 찾고 조작합니다

     

    사람의 눈, 코, 입, 턱의 위치와 윤곽을 잡아냅니다.

    import face_recognition 
    
    image = face_recognition.load_image_file("your_file.jpg") 
    
    face_landmarks_list = face_recognition.face_landmarks(image)

     

    3. 사진 속 신원을 확인합니다.

     

    사진에서 누가 등장하였는지 인식합니다.

    import face_recognition 
    
    known_image = face_recognition.load_image_file("biden.jpg") 
    
    unknown_image = face_recognition.load_image_file("unknown.jpg") 
    
    biden_encoding = face_recognition.face_encodings(known_image)[0] 
    
    unknown_encoding = face_recognition.face_encodings(unknown_image)[0] 
    
    results = face_recognition.compare_faces([biden_encoding], unknown_encoding)

    face_recognition zip에는 3개의 Python 파일이 들어있습니다.

    • camera.py : 카메라가 정상적으로 작동하는지 확인하기 위한 파일

    • face_recog.py : 촬영된 동영상에 등장하는 얼굴이 knowns 파일안에 있는 얼굴과 비교하여 그에 맞는 이름을 출력 

    • live_streaming.py : 동영상을 네트워크 상에 전송 ; 파이썬이 실행되는 툴이 설치되어 있지 않은 경우에 사용 가능, 임의의 컴퓨터에서 http://IP_addr:5000 로 접속하면 됩니다!

    소스 코드 설명 (face_recog.py)

    import face_recognition
    import cv2
    import camera
    import os
    import numpy as np
    
    class FaceRecog():
    
        def __init__(self):
    
            # Using OpenCV to capture from device 0. If you have trouble capturing
            # from a webcam, comment the line below out and use a video file
            # instead.
    
            self.camera = camera.VideoCamera()
    
            self.known_face_encodings = []
    
            self.known_face_names = []
    
    
    		# Load sample pictures and learn how to recognize it.
    		# Knowns 디렉토리에서 사진 파일을 읽고, 파일 이름으로부터 사람 이름을 추출합니다.
    
            dirname = 'knowns' 
    
            files = os.listdir(dirname)
    
            for filename in files:
    
                name, ext = os.path.splitext(filename)
    
                if ext == '.jpg':
    
                    self.known_face_names.append(name)
    
                    pathname = os.path.join(dirname, filename)
    
              # 사진에서 얼굴 영역을 알아내고, 얼굴 특징의 위치를 분석한 데이터를 know_face_encodings에 저장합니다.
    
                    img = face_recognition.load_image_file(pathname)
    
                    face_encoding = face_recognition.face_encodings(img)[0]
    
                    self.known_face_encodings.append(face_encoding)
       
              # Initialize some variables
    
                    self.face_locations = []
    
                    self.face_encodings = []
    
             		self.face_names = []
    
    	        	self.process_this_frame = True
    
        def __del__(self):
    
            del self.camera
    
    
    
        def get_frame(self):
    
            # Grab a single frame of video
            # 카메라로부터 frame을 읽어서 1/4 크기로 줄입니다. 그 이유는 계산양을 줄이기 위해서 입니다.
    
            frame = self.camera.get_frame()
    
            # 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
    
            # 계산 양을 더 줄이기 위해서 두 frame당 1번씩만 계산합니다.
    
            if self.process_this_frame:
    
                # Find all the faces and face encodings in the current frame of video
    
                # 읽은 frame에서 얼굴 영역과 특징을 추출합니다.
    
                self.face_locations = face_recognition.face_locations(rgb_small_frame)
    
                self.face_encodings = face_recognition.face_encodings(rgb_small_frame, self.face_locations)
    
    
                self.face_names = []
    
                for face_encoding in self.face_encodings:
    
                    # See if the face is a match for the known face(s)
    
                    # frame에서 추출한 얼굴 특징과 knowns에 있던 사진 얼굴의 특징을 비교하여, 비슷한 정도를
    
                       distance의 척도로 환산합니다. distance가 작다는 것은 서로 비슷한 얼굴임을 뜻합니다.
    
                    distances = face_recognition.face_distance(self.known_face_encodings, face_encoding)
    
                    min_value = min(distances)
    
    
    
                    # tolerance: How much distance between faces to consider it a match. Lower is more strict.
    
                    # 0.6 is typical best performance.
    
                    # 거리가 0.6 이면 다른 사람의 얼굴입니다. 이런 경우 이름은 unknown 으로 표시됩니다.
    
                    name = "Unknown"
    
                    if min_value < 0.6:
    
                        index = np.argmin(distances)
    
                        name = self.known_face_names[index]
    
                    self.face_names.append(name)
    
            self.process_this_frame = not self.process_this_frame
    
            # Display the results
    
            # 찾은 사람의 얼굴 영역과 이름을 비디오 화면에 나타냅니다.
    
            for (top, right, bottom, left), name in zip(self.face_locations, self.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)
    
            return frame
    
        def get_jpg_bytes(self):
    
            frame = self.get_frame()
    
            # We are using Motion JPEG, but OpenCV defaults to capture raw images,
    
            # so we must encode it into JPEG in order to correctly display the
    
            # video stream.
    
            ret, jpg = cv2.imencode('.jpg', frame)
    
            return jpg.tobytes()

     

     

    참조

    https://ukayzm.github.io/python-face-recognition

    https://github.com/ageitgey/face_recognition/blob/master/README_Korean.md

Designed by Tistory.