본문 바로가기

그냥, 코딩

GAN실습 - 환경구축 & BeautyGAN(1)

반응형
이 자료는 한국인공지능협회에서 진행한 2021년 사업주 직업능력 개발훈련으로 BASIC AI(32시간)-박성주 강사의 온라인 교육내용을 참고한 것입니다. 

 

BeautyGAN - 쌩얼에 화장해주기 or 화장한 얼굴로 쌩얼만들기

학습을 시킨 코드는 저작권때문에 공개되지 않았지만, 학습 모델은 공개되어 있음.

 

# 개발환경설정


  • anaconda ID 생성: p36t19_beauty
  • python버전 : 3.6.x
  • tensorflow 버전: 1.9
  • 개발툴: jupyter notebook
  • 기타 라이브러리 설치하기
    • matplotlib 
    • dlib
  • 작업경로: C:\ai_exam\beautyGAN
  • 훈련모델 다운로드(Pretrained Model)
  • 소스다운로드 :https://github.com/kairess/BeautyGAN
 

GitHub - kairess/BeautyGAN: transfer the makeup style of a reference face image to a non-makeup face

transfer the makeup style of a reference face image to a non-makeup face - GitHub - kairess/BeautyGAN: transfer the makeup style of a reference face image to a non-makeup face

github.com


 

# 자주 사용되는 용어

  • dlib : 사람의 얼굴을 인식하기 위한 랜드마크(landmark)를 찾아내는 라이브러리. 5p, 68p 2개로 구분하여 사람의 얼굴을 인식한다. 
  • Pretrained Model : 다운로드 소스를 공개한 개발자가 인공지능을 학습시켜 놓은 최종 학습된 파일
  • checkpoint : 인공지능이 학습에 가장 좋은 점수가 나왔던 상태를 임시로 저장 
  • 전처리 : 인공지능이 학습하기 용이하도록 동일한 조건으로 만들어주는 것

 


# BeautyGAN 인공지능 실습

  1. 개발환경 구축(Anaconda) 
    • [시작] - anaconda3(64bit) - anaconda prompt(anaconda3)
    • anaconda 사용자 ID 생성하기 : conda create -n p36t19_beauty python=3.6
    • (계정삭제하는 방법)
      • 계정리스트 확인: conda env list
      • 계정 삭제: conda env remove -n (이름)
      • (base) C:\WINDOWS\system32>conda env remove -n p36
    • 로그인하기 : conda activate p36t19_beauty
  2. 라이브러리와 개발툴 설치하기
    • tensorflow(V1.9) : (p36t19_beauty) C:\WINDOWS\system32>pip install tensorflow==1.9
      • 버전 확인
      • import tensorflow as tf
        tf.__version__
        '1.9.0'
    • jupyter : (p36t19_beauty) C:\WINDOWS\system32>pip install jupyter
    • matplotlib : (p36t19_beauty) C:\WINDOWS\system32>pip install matplotlib
    • dlib 설치 순서
      1. cmake 설치 : (p36t19_beauty) C:\WINDOWS\system32>pip install cmake
      2. dlib 설치 : (p36t19_beauty) C:\WINDOWS\system32>conda install -c conda-forge dlib
      3. Proceed ([y]/n)? y 
  3. git 설치여부 확인
    • git이 없다면? 'git'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는 배치 파일이 아닙니다. 
      • windows 다운로드 : http://git-scm.com/download/win
      • Git-2.32.0.2-64-bit.exe 실행 및 설치
      • 설치 후에도 위의 메세지가 계속 뜬다면 anaconda prompt 종료 후 다시 시작 
    • git이 있다면? See 'git help git' for an overview of the system.
  4. 개발작업경로로 이동
    • (p36t19_beauty) C:\WINDOWS\system32>cd C:\ai_exam
    • (p36t19_beauty) C:\ai_exam>
  5. git으로 소스코드 다운로드
    • git을 이용하면 해당 디렉토리에 github의 소스를 바로 받을 수 있다. 
    • (p36t19_beauty) C:\ai_exam>git clone https://github.com/kairess/BeautyGAN
    • github의 소스 다운로드 확인
    • 해당경로로 소스코드 그대로 복제했음
       
  6. Pretrained Model 다운로드 
  7. 개발작업경로 이동
    • (p36t19_beauty) C:\ai_exam>cd C:\ai_exam\BeautyGAN
    • (p36t19_beauty) C:\ai_exam\BeautyGAN>
  8. jupyter notebook 실행
    • (p36t19_beauty) C:\ai_exam\BeautyGAN>jupyter notebook

 


 

# tensorflow의 버전이 낮아서, 상위버전으로 바꾸라는 메시지가 뜰 수 있음
import dlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import tensorflow as tf
import numpy as np


###########################################################################################
#Load Models
detector = dlib.get_frontal_face_detector() #얼굴의 정면을 찾는 작업
sp = dlib.shape_predictor('models/shape_predictor_5_face_landmarks.dat') #얼굴을 5개의 포인트로 인식해서 사용하겠다는 것
#5p:5포인트 지정, 68p:얼굴에 68포인트 지정

###########################################################################################

#Load Images 
img = dlib.load_rgb_image('imgs/test4.jpg')

plt.figure(figsize=(16, 10))
plt.imshow(img)


###########################################################################################

#Find Faces
img_result = img.copy() #이미지원본에 카피해서 좌표를 지정

dets = detector(img, 1) # 얼굴에 관한 좌표를 찾아줌
print("face info = ", dets) 
print("face info = ", len(dets))

if len(dets) == 0:
    print('cannot find faces!')

fig, ax = plt.subplots(1, figsize=(16, 10))

for det in dets:
    x, y, w, h = det.left(), det.top(), det.width(), det.height()

    rect = patches.Rectangle((x, y), w, h, linewidth=2, edgecolor='r', facecolor='none')
    ax.add_patch(rect)

ax.imshow(img_result)


###########################################################################################

#Find Landmarks 5points 
fig, ax = plt.subplots(1, figsize=(16, 10))

objs = dlib.full_object_detections() #사람얼굴의 포인트마다 점을 찍어주는 것(눈과 눈사이, 코)

for detection in dets:
    s = sp(img, detection)
    objs.append(s)
    
    for point in s.parts():
        circle = patches.Circle((point.x, point.y), radius=3, edgecolor='r', facecolor='r')
        ax.add_patch(circle)

ax.imshow(img_result)


###########################################################################################

#Align Faces # 얼굴의 회전하는 작업(수평을 맞춰줌)
faces = dlib.get_face_chips(img, objs, size=256, padding=0.3)

fig, axes = plt.subplots(1, len(faces)+1, figsize=(20, 16))

axes[0].imshow(img)

for i, face in enumerate(faces):
    axes[i+1].imshow(face)
    

###########################################################################################

#Functionalize - 여러명의 사람이 들어간 이미지에서 사람의 얼굴만 가져오기
def align_faces(img):
    dets = detector(img, 1)
    
    objs = dlib.full_object_detections()

    for detection in dets:
        s = sp(img, detection)
        objs.append(s)
        
    faces = dlib.get_face_chips(img, objs, size=256, padding=0.35)
    
    return faces

# test
test_img = dlib.load_rgb_image('imgs/test5.jpg')

test_faces = align_faces(test_img)

fig, axes = plt.subplots(1, len(test_faces)+1, figsize=(20, 16))
axes[0].imshow(test_img)

for i, face in enumerate(test_faces):
    axes[i+1].imshow(face)
    
    
############################################################################################    

#Load BeautyGAN pretrained - tensorflow v1.9라서 현재 v2.7과 사용하는 구조가 아예 다르다
sess = tf.Session()
sess.run(tf.global_variables_initializer())

saver = tf.train.import_meta_graph('models/model.meta')
saver.restore(sess, tf.train.latest_checkpoint('models'))
graph = tf.get_default_graph()

X = graph.get_tensor_by_name('X:0') # source
Y = graph.get_tensor_by_name('Y:0') # reference
Xs = graph.get_tensor_by_name('generator/xs:0') # output


############################################################################################

#Load Images
img1 = dlib.load_rgb_image('imgs/test2.jpg')
img1_faces = align_faces(img1)

img2 = dlib.load_rgb_image('imgs/makeup/jolly.png')
img2_faces = align_faces(img2)

fig, axes = plt.subplots(1, 2, figsize=(16, 10))
axes[0].imshow(img1_faces[0])
axes[1].imshow(img2_faces[0])


############################################################################################

#Run
src_img = img1_faces[0]
ref_img = img2_faces[0]

X_img = preprocess(src_img)
X_img = np.expand_dims(X_img, axis=0)

Y_img = preprocess(ref_img)
Y_img = np.expand_dims(Y_img, axis=0)

output = sess.run(Xs, feed_dict={
    X: X_img,
    Y: Y_img
})

output_img = postprocess(output[0])

fig, axes = plt.subplots(1, 3, figsize=(20, 10))
axes[0].set_title('Source')
axes[0].imshow(src_img)
axes[1].set_title('Reference')
axes[1].imshow(ref_img)
axes[2].set_title('Result')
axes[2].imshow(output_img)
반응형