基於 PyTorch 和神經網路給 GirlFriend 製作漫畫風頭像
摘要:本文中我們介紹的 AnimeGAN 就是 GitHub 上一款爆火的二次元漫畫風格遷移工具,可以實現快速的動畫風格遷移。
本文分享自華為雲社區《AnimeGANv2 照片動漫化:如何基於 PyTorch 和神經網路給 GirlFriend 製作漫畫風頭像?【秋招特訓】》,作者:白鹿第一帥 。
前言
將現實世界場景的照片轉換為動漫風格影像的方法,這是電腦視覺和藝術風格轉換中一項有意義且具有挑戰性的任務,而本文中我們介紹的 AnimeGAN 就是 GitHub 上一款爆火的二次元漫畫風格遷移工具,可以實現快速的動畫風格遷移。該工具是基於神經風格遷移和生成對抗網路 (GAN) 技術打造的,相比於傳統的神經網路模型,GAN 是一種全新的非監督式的架構。最近 AnimeGAN 發布了其二代版本,據稱更新後 AnimeGANv2 支援了風景照片和風景影片的三種動漫化風格(分別是宮崎駿、新海誠和金敏),視覺效果更佳,模型體量也更小且容易訓練了。
一、基於 GAN 實現漫畫風格實現原理
1.1、傳統漫畫風格遷移工具的不足
- 生成的影像沒有明顯的動畫風格紋理。
- 生成的影像丟失了原始影像的內容。
- 網路的參數需要大的存儲容量。
1.2、基於生成對抗網路 (GAN) 的漫畫風格遷移工具
通過三種新穎的損失函數,使生成的影像具有更好的動畫視覺效果,這些損失函數是灰度樣式損失、灰度對抗損失和顏色重建損失。AnimeGAN 可以很容易地使用未配對的訓練數據進行端到端訓練。
- AnimeGAN 的參數需要較低的記憶體容量。實驗結果表明,該方法可以快速將真實世界的照片轉換為高品質的動漫影像,並且優於最先進的方法。
- AnimeGAN 的參數需要較低的記憶體容量。實驗結果表明,該方法可以快速將真實世界的照片轉換為高品質的動漫影像,並且優於最先進的方法。
- AnimeGAN 的參數需要較低的記憶體容量。實驗結果表明,該方法可以快速將真實世界的照片轉換為高品質的動漫影像,並且優於最先進的方法。
實現原理可以參考原論文://link.springer.com/chapter/10.1007/978-981-15-5577-0_18,具體如下圖所示:
二、AnimeGANv2 照片動漫化
2.1、與 AnimeGAN 的對比
AnimeGANv2 是照片漫畫工具 AnimeGAN 的升級版本,AnimeGANv2 在訓練 AI 時 GAN 包括了兩套獨立的網路 A 和 B,A 網路是需要訓練的分類器,用來分辨成圖是否符合標準;B 網路是生成器,生成類似於真實樣本的隨機樣本,並將其作為假樣本以欺騙網路 A。在 A 和 B 的對抗中,AI 的水平逐漸提升,最後實現質的飛躍,相較於之前版本,AnimeGANv2 主要在以下四個方面進行優化:
- 解決生成圖片的高頻偽影問題。
- 易於訓練,達到實物紙張效果。
- 減少生成器網路參數。
- 儘可能用高品質的圖片樣式數據。
2.2、AnimeGANv2 效果及項目介紹
AnimeGANv2 可以將現實場景的圖片處理為動漫畫風,目前支援宮崎駿、新海誠和今敏的三種風格,三者實現效果具體如下圖所示:
Github 地址://github.com/TachibanaYoshino/AnimeGANv2,詳情具體如下圖所示:
三、本次案例部署及實驗平台介紹
3.1、對象存儲服務 OBS
我們將本次案例中的相關程式碼和數據存放於華為雲提供的對象存儲服務 OBS 中,推薦大家使用://www.huaweicloud.com/product/obs.html,產品詳細資訊具體如下圖所示:
對象存儲服務(Object Storage Service,OBS)提供海量、安全、高可靠、低成本的數據存儲能力,可供用戶存儲任意類型和大小的數據。適合企業備份 / 歸檔、影片點播、影片監控等多種數據存儲場景,在我本人的使用以及測試中對象存儲服務 OBS 效果頗好,故推薦給大家使用,具體如下圖所示:
3.2、AI 開發平台 ModelArts
本次案例運行的實驗平台為華為雲的 AI 開發平台 ModelArts,詳細資訊請點擊://support.huaweicloud.com/modelarts/index.html,產品詳細資訊具體如下圖所示:
ModelArts 是面向開發者的一站式 AI 開發平台,為機器學習與深度學習提供海量數據預處理及半自動化標註、大規模分散式 Training、自動化模型生成,及端 – 邊 – 雲模型按需部署能力,幫助用戶快速創建和部署模型,管理全周期 AI 工作流,在我本人的使用以及測試中 ModelArts 效果頗好且提供了可以滿足不同開發需求的運行環境(部分免費),故推薦給大家使用,具體如下圖所示:
可以在華為雲 AI 開發平台 ModelArts 提供的 JupyterLab 中選擇不同的實驗環境內核,具體如下圖所示:
四、獲取程式碼和數據
獲取程式碼和數據,相關實現命令如下所示:
import os !wget https://obs-aigallery-zc.obs.cn-north-4.myhuaweicloud.com/clf/code/AnimeGAN/AnimeGAN.zip os.system('unzip AnimeGAN.zip')
我們可以在華為雲 AI 開發平台 ModelArts 提供的 JupyterLab 查看具體運行過程和結果,具體如下圖所示:
五、安裝依賴庫
安裝依賴庫,相關實現命令如下所示:
!pip install dlib !pip uninstall -y torch !pip uninstall -y torchvision !pip install torch !pip install torchvision %cd AnimeGANv2
我們可以在華為雲 AI 開發平台 ModelArts 提供的 JupyterLab 查看具體運行過程和結果,具體如下圖所示:
說明:由於運行結果過於冗長,僅截取首端與末端運行結果。
六、AnimeGANv2 源碼解析
## AnimeGANv2源碼解析 import os import dlib import collections from typing import Union, List import numpy as np from PIL import Image import matplotlib.pyplot as plt def get_dlib_face_detector(predictor_path: str = "shape_predictor_68_face_landmarks.dat"): if not os.path.isfile(predictor_path): model_file = "shape_predictor_68_face_landmarks.dat.bz2" os.system(f"wget //dlib.net/files/{model_file}") os.system(f"bzip2 -dk {model_file}") detector = dlib.get_frontal_face_detector() shape_predictor = dlib.shape_predictor(predictor_path) def detect_face_landmarks(img: Union[Image.Image, np.ndarray]): if isinstance(img, Image.Image): img = np.array(img) faces = [] dets = detector(img) for d in dets: shape = shape_predictor(img, d) faces.append(np.array([[v.x, v.y] for v in shape.parts()])) return faces return detect_face_landmarks def display_facial_landmarks( img: Image, landmarks: List[np.ndarray], fig_size=[15, 15] ): plot_style = dict( marker='o', markersize=4, linestyle='-', lw=2 ) pred_type = collections.namedtuple('prediction_type', ['slice', 'color']) pred_types = { 'face': pred_type(slice(0, 17), (0.682, 0.780, 0.909, 0.5)), 'eyebrow1': pred_type(slice(17, 22), (1.0, 0.498, 0.055, 0.4)), 'eyebrow2': pred_type(slice(22, 27), (1.0, 0.498, 0.055, 0.4)), 'nose': pred_type(slice(27, 31), (0.345, 0.239, 0.443, 0.4)), 'nostril': pred_type(slice(31, 36), (0.345, 0.239, 0.443, 0.4)), 'eye1': pred_type(slice(36, 42), (0.596, 0.875, 0.541, 0.3)), 'eye2': pred_type(slice(42, 48), (0.596, 0.875, 0.541, 0.3)), 'lips': pred_type(slice(48, 60), (0.596, 0.875, 0.541, 0.3)), 'teeth': pred_type(slice(60, 68), (0.596, 0.875, 0.541, 0.4)) } fig = plt.figure(figsize=fig_size) ax = fig.add_subplot(1, 1, 1) ax.imshow(img) ax.axis('off') for face in landmarks: for pred_type in pred_types.values(): ax.plot( face[pred_type.slice, 0], face[pred_type.slice, 1], color=pred_type.color, **plot_style ) plt.show() # https://github.com/NVlabs/ffhq-dataset/blob/master/download_ffhq.py import PIL.Image import PIL.ImageFile import numpy as np import scipy.ndimage def align_and_crop_face( img: Image.Image, landmarks: np.ndarray, expand: float = 1.0, output_size: int = 1024, transform_size: int = 4096, enable_padding: bool = True, ): # 將五官數據轉為數組 # pylint: disable=unused-variable lm = landmarks lm_chin = lm[0 : 17] # left-right lm_eyebrow_left = lm[17 : 22] # left-right lm_eyebrow_right = lm[22 : 27] # left-right lm_nose = lm[27 : 31] # top-down lm_nostrils = lm[31 : 36] # top-down lm_eye_left = lm[36 : 42] # left-clockwise lm_eye_right = lm[42 : 48] # left-clockwise lm_mouth_outer = lm[48 : 60] # left-clockwise lm_mouth_inner = lm[60 : 68] # left-clockwise # 計算輔助向量 eye_left = np.mean(lm_eye_left, axis=0) eye_right = np.mean(lm_eye_right, axis=0) eye_avg = (eye_left + eye_right) * 0.5 eye_to_eye = eye_right - eye_left mouth_left = lm_mouth_outer[0] mouth_right = lm_mouth_outer[6] mouth_avg = (mouth_left + mouth_right) * 0.5 eye_to_mouth = mouth_avg - eye_avg # 提取矩形框 x = eye_to_eye - np.flipud(eye_to_mouth) * [-1, 1] # flipud函數實現矩陣的上下翻轉;數組乘法,每行對應位置相乘 x /= np.hypot(*x) x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8) x *= expand y = np.flipud(x) * [-1, 1] c = eye_avg + eye_to_mouth * 0.1 quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y]) qsize = np.hypot(*x) * 2 # 縮放 shrink = int(np.floor(qsize / output_size * 0.5)) if shrink > 1: rsize = (int(np.rint(float(img.size[0]) / shrink)), int(np.rint(float(img.size[1]) / shrink))) img = img.resize(rsize, PIL.Image.ANTIALIAS) quad /= shrink qsize /= shrink # 裁剪 border = max(int(np.rint(qsize * 0.1)), 3) crop = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1])))) crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1])) if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]: img = img.crop(crop) quad -= crop[0:2] # 填充數據 pad = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1])))) pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0)) if enable_padding and max(pad) > border - 4: pad = np.maximum(pad, int(np.rint(qsize * 0.3))) img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect') h, w, _ = img.shape y, x, _ = np.ogrid[:h, :w, :1] mask = np.maximum(1.0 - np.minimum(np.float32(x) / pad[0], np.float32(w-1-x) / pad[2]), 1.0 - np.minimum(np.float32(y) / pad[1], np.float32(h-1-y) / pad[3])) blur = qsize * 0.02 img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0) img += (np.median(img, axis=(0,1)) - img) * np.clip(mask, 0.0, 1.0) img = PIL.Image.fromarray(np.uint8(np.clip(np.rint(img), 0, 255)), 'RGB') quad += pad[:2] # 轉化圖片 img = img.transform((transform_size, transform_size), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR) if output_size < transform_size: img = img.resize((output_size, output_size), PIL.Image.ANTIALIAS) return img #@title AnimeGAN model from https://github.com/bryandlee/animegan2-pytorch # ! git clone https://github.com/bryandlee/animegan2-pytorch model_fname = "face_paint_512_v2_0.pt" # model_urls = { # "face_paint_512_v0.pt": "//drive.google.com/uc?id=1WK5Mdt6mwlcsqCZMHkCUSDJxN1UyFi0-", # "face_paint_512_v2_0.pt": "//drive.google.com/uc?id=18H3iK09_d54qEDoWIc82SyWB2xun4gjU", # } # ! gdown {model_urls[model_fname]} import sys sys.path.append("animegan2-pytorch") import torch torch.set_grad_enabled(False) print(torch.__version__, torch.cuda.is_available()) from model import Generator device = "cpu" model = Generator().eval().to(device) model.load_state_dict(torch.load(model_fname)) from PIL import Image from torchvision.transforms.functional import to_tensor, to_pil_image def face2paint( img: Image.Image, size: int, side_by_side: bool = True, ) -> Image.Image: w, h = img.size s = min(w, h) img = img.crop(((w - s) // 2, (h - s) // 2, (w + s) // 2, (h + s) // 2)) img = img.resize((size, size), Image.LANCZOS) input = to_tensor(img).unsqueeze(0) * 2 - 1 output = model(input.to(device)).cpu()[0] if side_by_side: output = torch.cat([input[0], output], dim=2) output = (output * 0.5 + 0.5).clip(0, 1) return to_pil_image(output)
對應運行結果具體如下:
1.11.0+cu102 True
七、素材應用照片動漫化
7.1、通過文件路徑獲取素材文件
定義一個應用函數,通過文件路徑獲取素材文件,具體實現程式碼如下:
def inference_from_file(filepath): img = Image.open(filepath).convert("RGB") face_detector = get_dlib_face_detector() landmarks = face_detector(img) display_facial_landmarks(img, landmarks, fig_size=[5, 5]) for landmark in landmarks: face = align_and_crop_face(img, landmark, expand=1.3) display(face2paint(face, 512))
我們分別對命名為 「4.jpg」 和 「1.jpg」 的素材照片應用漫畫化效果,具體實現程式碼如下:
inference_from_file('1.jpg')
inference_from_file('4.jpg')
對於命名為 「1.jpg」 的圖片分析過程具體如下圖所示:
輸出結果,我們著重在臉部與原圖 「1.jpg」 進行對比,具體如下圖所示:
對於命名為 「4.jpg」 的圖片分析過程具體如下圖所示:
輸出結果,我們著重在臉部與原圖 「4.jpg」 進行對比,具體如下圖所示:
7.2、通過 URL 地址獲取素材文件
定義一個應用函數,通過 URL 地址獲取素材文件,具體實現程式碼如下:
import requests def inference_from_url(url): img = Image.open(requests.get(url, stream=True).raw).convert("RGB") face_detector = get_dlib_face_detector() landmarks = face_detector(img) display_facial_landmarks(img, landmarks, fig_size=[5, 5]) for landmark in landmarks: face = align_and_crop_face(img, landmark, expand=1.3) display(face2paint(face, 512))
我們通過獲取 URL 地址中的素材照片 「6.jpg」 實現,具體實現程式碼如下:
inference_from_url("//obs-aigallery-zc.obs.cn-north-4.myhuaweicloud.com/clf/code/AnimeGAN/6.jpg")
對於命名為 「6.jpg」 的圖片分析過程具體如下圖所示:
輸出結果,我們著重在臉部與原圖 「6.jpg」 進行對比,具體如下圖所示:
八、在線體驗
當然也考慮到一些同學因為某些原因無法進行實驗環境操作,在這裡為大家提供線上 AnimeGANv2 照片動漫化,感興趣的同學請點擊://huggingface.co/spaces/akhaliq/AnimeGANv2,在這裡呢就有一些局限性,目前僅支援兩個 version:
- version 1 ( stylization, robustness)
- version 2 ( robustness, stylization)
玩一玩,還是夠用的!嘿嘿嘿!馬斯克?!
不說了,我要去給女朋友整一個!你們看著辦,該不會是沒有女朋友吧?!
總結
在本文中我們給大家介紹了基於神經風格遷移和生成對抗網路 (GAN) 技術打造的照片漫畫風格遷移工具 AnimeGANv2,並通過華為雲平台提供的 AI 開發平台 ModelArts 進行了效果演示,其中對於 AnimeGANv2 源碼部分以及通過文件路徑獲取素材文件和通過 URL 地址獲取素材文件兩種不同的應用方式進行了重點拆分,這是一種設計模式的體現。通過技術手段在電腦視覺和藝術風格轉換方面的應用,實現照片的快速動漫化效果,對於作者來說是一種挑戰,那對於我們其他用戶來說呢?新領域新機遇?