앎을 경계하기

Machine Learning/For CV

MTCNN으로 Face landmark 추출

양갱맨 2020. 12. 3. 09:11

실행환경 : Google Colab

1. mtcnn 패키지 설치

!pip install mtcnn

2.필요 패키지임포트

import cv2
import glob
from mtcnn import MTCNN

import warnings
warnings.filterwarnings(action='ignore')

3. 랜드마크 추출할 이미지 리스트 얻기

path = '/content/*'
file_list = glob.glob(path)
input_list = [file for file in file_list if file.endswith(".png")]
input_list

4. MTCNN 으로 각 이미지 랜드마크 추출

result = {}
for img2 in input_list:
    img = cv2.cvtColor(cv2.imread(img2), cv2.COLOR_BGR2RGB)
    detector = MTCNN()
    result[img2]=detector.detect_faces(img)

박스 [x, y, width, height], confidence와 이미지에서 얼굴 특징점 위치를 딕셔너리 형태로 반환

>>> result['/content/test.png']

[{'box': [111, 117, 182, 238],
  'confidence': 0.999997615814209,
  'keypoints': {'left_eye': (140, 207),
   'mouth_left': (144, 289),
   'mouth_right': (226, 288),
   'nose': (165, 254),
   'right_eye': (219, 207)}}]

5. txt 파일로 저장

for key in result.keys():
    txt = key.replace(".png",".txt")
    f = open(txt, 'w')
    s = ''
    for point in result[key][0]['keypoints']:
        s = str(result[key][0]['keypoints'][point]).replace('(','').replace(')','\n').replace(',', ' ')
        f.write(s)
    f.close()