aiface's picture
Upload 12 files
327b68f
raw
history blame
3.66 kB
import cv2 # OpenCV ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
import numpy as np
from skimage import transform as tf # ์ด๋ฏธ์ง€ ๋ณ€ํ™˜ ๋ชจ๋“ˆ
# -- Landmark interpolation:
def linear_interpolate(landmarks, start_idx, stop_idx):
start_landmarks = landmarks[start_idx] # ๋žœ๋“œ๋งˆํฌ ์‹œ์ž‘
stop_landmarks = landmarks[stop_idx] # ๋žœ๋“œ๋งˆํฌ ๋
delta = stop_landmarks - start_landmarks # ๋žœ๋“œ๋งˆํฌ ๊ฐ’ ์ฐจ์ด
for idx in range(1, stop_idx-start_idx):
landmarks[start_idx+idx] = start_landmarks + idx/float(stop_idx-start_idx) * delta # ๋žœ๋“œ๋งˆํฌ ์—…๋ฐ์ดํŠธ(๋ณด๊ฐ„)
return landmarks
# -- Face Transformation
# src: ์ž…๋ ฅ ์˜์ƒ, dst: ์ถœ๋ ฅ/๊ฒฐ๊ณผ ์˜์ƒ
def warp_img(src, dst, img, std_size):
tform = tf.estimate_transform('similarity', src, dst) # find the transformation matrix # ๋ณ€ํ™˜ ํ–‰๋ ฌ ๊ตฌํ•˜๊ธฐ
warped = tf.warp(img, inverse_map=tform.inverse, output_shape=std_size) # wrap the frame image # ์ฃผ์–ด์ง„ ์ขŒํ‘œ ๋ณ€ํ™˜์— ๋”ฐ๋ผ ํ”„๋ ˆ์ž„ ์ด๋ฏธ์ง€ ์™œ๊ณก
warped = warped * 255 # note output from wrap is double image (value range [0,1])
warped = warped.astype('uint8') # numpy ๋ฐ์ดํ„ฐ ํƒ€์ž… uint8 ์œผ๋กœ ๋ณ€๊ฒฝ
return warped, tform
def apply_transform(transform, img, std_size):
warped = tf.warp(img, inverse_map=transform.inverse, output_shape=std_size) # wrap the frame image # ์ฃผ์–ด์ง„ ์ขŒํ‘œ ๋ณ€ํ™˜์— ๋”ฐ๋ผ ํ”„๋ ˆ์ž„ ์ด๋ฏธ์ง€ ์™œ๊ณก
warped = warped * 255 # note output from wrap is double image (value range [0,1])
warped = warped.astype('uint8') # numpy ๋ฐ์ดํ„ฐ ํƒ€์ž… uint8 ์œผ๋กœ ๋ณ€๊ฒฝ
return warped
# -- Crop
def cut_patch(img, landmarks, height, width, threshold=5):
center_x, center_y = np.mean(landmarks, axis=0) # ๊ฐ ๊ทธ๋ฃน์˜ ๊ฐ™์€ ์›์†Œ๋ผ๋ฆฌ ํ‰๊ท 
# ์ขŒํ‘œ ์ฒ˜๋ฆฌ
if center_y - height < 0:
center_y = height
if center_y - height < 0 - threshold:
raise Exception('too much bias in height')
if center_x - width < 0:
center_x = width
if center_x - width < 0 - threshold:
raise Exception('too much bias in width')
if center_y + height > img.shape[0]:
center_y = img.shape[0] - height
if center_y + height > img.shape[0] + threshold:
raise Exception('too much bias in height')
if center_x + width > img.shape[1]:
center_x = img.shape[1] - width
if center_x + width > img.shape[1] + threshold:
raise Exception('too much bias in width')
# ๋ฐฐ์—ด ๋ณต์‚ฌ
cutted_img = np.copy(img[ int(round(center_y) - round(height)): int(round(center_y) + round(height)),
int(round(center_x) - round(width)): int(round(center_x) + round(width))])
return cutted_img
# -- RGB to GRAY
def convert_bgr2gray(data):
# np.stack(๋ฐฐ์—ด_1, ๋ฐฐ์—ด_2, axis=0): ์ง€์ •ํ•œ axis๋ฅผ ์™„์ „ํžˆ ์ƒˆ๋กœ์šด axis๋กœ ์ƒ๊ฐ
return np.stack([cv2.cvtColor(_, cv2.COLOR_BGR2GRAY) for _ in data], axis=0) # gray ๋ณ€ํ™˜