[AvatarCLIP] 機械学習でテキストから3Dアバターを生成する

2022年5月26日木曜日

Artificial Intelligence

本記事では、AvatarCLIPと呼ばれる機械学習手法を用いて、テキストから3Dアバターを生成する方法をご紹介します。

アイキャッチ
出典: AvatarCLIP: Zero-Shot Text-Driven Generation and Animation of 3D Avatars

AvatarCLIP

概要

AvatarCLIPは、ゼロショットでテキストから3Dアバターを生成する技術です。

名称にも含まれるようにCLIPを用いて、自然言語のテキストを入力に、3Dアバターの形状、テクスチャ、アニメーションを生成します。

具体的には、shape VAE(Variational Autoencoder)を用いて3D Human Meshを初期化し、CLIPガイドに基づき3D Human Meshの形状、テクスチャを詳細化していきます。次に、motion VAEで学習した事前情報を活用し、生成された3Dアバターにモーションを合成することにより、自然言語からの3Dアバター生成を実現しています。

overview
出典: AvatarCLIP: Zero-Shot Text-Driven Generation and Animation of 3D Avatars

CLIPの詳細については以下の記事などをご参照ください。

AvatarCLIPの詳細はこちらの論文をご参照ください。

本記事では上記手法を用いて、テクストから3Dアバターの形状、テクスチャ生成を行っていきます。

デモ(Colaboratory)

それでは、実際に動かしながらテクストから3Dアバターの形状、テクスチャ生成を行っていきます。
ソースコードは本記事にも記載していますが、下記のGitHubでも取得可能です。
GitHub - Colaboratory demo

また、下記から直接Google Colaboratoryで開くこともできます。
Open In Colab

また、このデモはPythonで実装しています。
Pythonの実装に不安がある方、Pythonを使った機械学習について詳しく勉強したい方は、以下の書籍やオンライン講座などがおすすめです。

環境セットアップ

それではセットアップしていきます。 Colaboratoryを開いたら下記を設定しGPUを使用するようにしてください。

「ランタイムのタイプを変更」→「ハードウェアアクセラレータ」をGPUに変更

初めにGithubからソースコードを取得します。

%cd /content

!git clone https://github.com/hongfz16/AvatarCLIP.git
!git clone https://github.com/hongfz16/neural_renderer.git

次にライブラリをインストールします。

%cd /content/AvatarCLIP

# Install Pytorch
!pip install torch==1.7.1+cu101 torchvision==0.8.2+cu101 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html
# Install lib
!pip install -r requirements.txt

neural_rendererのファイルを一部修正します。

%cd /content/neural_renderer/neural_renderer

with open('./perspective.py', 'r') as f:
  lines = f.readlines()
lines.insert(19, '    x[z<=0] = 0\n')
lines.insert(20, '    y[z<=0] = 0\n')
lines.insert(21, '    z[z<=0] = 0\n')
with open('./perspective.py', 'w') as f:
  for l in lines:
    f.write(l)

ファイル修正後コンパイルします。

%cd /content/neural_renderer

!python3 setup.py install

次にSAMLモデルをダウンロードします。
SAMLの規約上二次配布不可のため、下記よりユーザー登録の上モデル(Download version 1.1.0 for Python 2.7 (female/male/neutral, 300 shape PCs))をダウンロードし、ご自身のGoogle Driveに配置ください。
SAML

%cd /content/AvatarCLIP

from google.colab import drive
drive.mount('/content/gdrive')

# Google DriveのファイルをGoogle Colabにコピー
!mkdir -p ./smpl_models/smpl
!cp "/content/gdrive/MyDrive/Colab Notebooks/SMPL_python_v.1.1.0.zip" "./smpl_models/smpl/SMPL_python_v.1.1.0.zip"
!unzip -d ./smpl_models/smpl/ ./smpl_models/smpl/SMPL_python_v.1.1.0.zip
!cp ./smpl_models/smpl/SMPL_python_v.1.1.0/smpl/models/basicmodel_neutral_lbs_10_207_0_v1.1.0.pkl ./smpl_models/smpl/SMPL_NEUTRAL.pkl

以上で、環境セットアップは完了です。 ここで一度、ランタイムを再起動しておきます。

Appearance Generation

それではセットアップした環境を使って3Dアバターの形状とテクスチャを生成していきます。
初めにライブラリをインポートします。

%cd /content/AvatarCLIP/AvatarGen/AppearanceGen
import os
import time
import logging
import argparse
import random
import numpy as np
import cv2 as cv
import trimesh
import torch
import torch.nn.functional as F
from torchvision import transforms
from torch.utils.tensorboard import SummaryWriter
from shutil import copyfile
from icecream import ic
from tqdm import tqdm
from pyhocon import ConfigFactory
from models.dataset import Dataset
from models.dataset import SMPL_Dataset
from models.fields import RenderingNetwork, SDFNetwork, SingleVarianceNetwork, NeRF
from models.renderer import NeuSRenderer
from models.utils import lookat, random_eye, random_at, render_one_batch, batch_rodrigues
from models.utils import sphere_coord, random_eye_normal, rgb2hsv, differentiable_histogram
from models.utils import my_lbs, readOBJ
import clip
from smplx import build_layer
import imageio
import glob

import os
from tqdm import tqdm
import numpy as np
from IPython import display
from PIL import Image
from base64 import b64encode

to8b = lambda x : (255*np.clip(x,0,1)).astype(np.uint8)
from main import Runner

次に、入力テキストを設定しconfigに反映します。

AppearanceDescription = "Iron Man" #@param {type:"string"}

torch.set_default_tensor_type('torch.cuda.FloatTensor')
FORMAT = "[%(filename)s:%(lineno)s - %(funcName)20s() ] %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)
conf_path = 'confs/examples_small/example.conf'
f = open(conf_path)
conf_text = f.read()
f.close()
conf_text = conf_text.replace('{TOREPLACE}', AppearanceDescription)

#@markdown google driveに保存する場合はTrue
save_gdrive = True #@param {type:"boolean"}
#@markdown save_gdrive指定時の出力先
custom_exp_dir = "/content/gdrive/MyDrive/Colab Notebooks" #@param {type:"string"}
if save_gdrive:
  conf_text = conf_text.replace('base_exp_dir = ./exp/smpl/example', 'base_exp_dir = ' + custom_exp_dir + '/exp/smpl/example')


# print(conf_text)
conf = ConfigFactory.parse_string(conf_text)
print("Prompt: {}".format(conf.get_string('clip.prompt')))
print("Face Prompt: {}".format(conf.get_string('clip.face_prompt')))
print("Back Prompt: {}".format(conf.get_string('clip.back_prompt')))

3Dアバターを生成していきます。 なお、デフォルトのイテレーションは30000で、Tesla T4で6時間弱を要しました。
Tesla K80ではそれ以上の時間を要することが予想されます。

%%time
runner = Runner(conf_path, 'train_clip', 'smpl', False, True, conf)
runner.init_clip()
runner.init_smpl()
runner.train_clip()

最後に100イテレーションごとに生成した出力結果を動画にまとめて表示します。

image_folder = 'exp/smpl/example/validations_extra_fine'
video_path = 'video.mp4'
if save_gdrive:
  image_folder = os.path.join(custom_exp_dir, image_folder)
  video_path = os.path.join(custom_exp_dir, video_path)
image_fname = glob.glob(os.path.join(image_folder, "*.png"))

init_frame = 1
last_frame = len(image_fname)
min_fps = 10
max_fps = 60
total_frames = last_frame - init_frame

length = 15 #Desired time of the video in seconds

frames = []
for i in range(init_frame, last_frame): #
    frames.append(Image.open(image_fname[i]))

#fps = last_frame/10
fps = np.clip(total_frames/length,min_fps,max_fps)

from subprocess import Popen, PIPE
p = Popen(['ffmpeg', '-y', '-f', 'image2pipe', '-vcodec', 'png', '-r', str(fps), '-i', '-', '-vcodec', 'libx264', '-r', str(fps), '-pix_fmt', 'yuv420p', '-crf', '17', '-preset', 'veryslow', video_path], stdin=PIPE)
for im in tqdm(frames):
    im.save(p.stdin, 'PNG')
p.stdin.close()
p.wait()
mp4 = open(video_path,'rb').read()
data_url = "data:video/mp4;base64," + b64encode(mp4).decode()

display.HTML("""
<video controls="" width="400">
      <source src="%s" type="video/mp4"></source>
</video>
""" % data_url)

出力結果は以下の通りです。

Iron Man result

アイアンマンに似たテクスチャが3D Human Meshにマッピングされています。
ただ繰り返すようですが、無料版のColaboratoryでは、処理速度にやや難ありです。

まとめ

本記事では、AvatarCLIPを用いて、テキストから3Dアバターを生成する方法をご紹介しました。

メタバースなどと相まって3Dアバターの自動生成技術はこれから盛り上がりを見せるかもしれません。 CLIP+GANの論文の流れから推察すると、高速化・軽量化を図った論文がそのうち発表されそうです。

また本記事では、機械学習を動かすことにフォーカスしてご紹介しました。
もう少し学術的に体系立てて学びたいという方には以下の書籍などがお勧めです。ぜひご一読下さい。


また動かせるだけから理解して応用できるエンジニアの足掛かりに下記のUdemyなどもお勧めです。

参考文献

1.  論文 - AvatarCLIP: Zero-Shot Text-Driven Generation and Animation of 3D Avatars

2. GitHub - hongfz16/AvatarCLIP

AIで副業ならココから!

まずは無料会員登録

プロフィール

メーカーで研究開発を行う現役エンジニア
組み込み機器開発や機会学習モデル開発に従事しています

本ブログでは最新AI技術を中心にソースコード付きでご紹介します


Twitter

カテゴリ

このブログを検索

ブログ アーカイブ

TeDokology