Shap-E のインストールと動作確認(テキストや画像からの立体生成)(Python,PyTorch を使用)(Windows 上)
Shap-e のインストールと立体生成を行う.
Shap-E
Shap-e は、テクスチャ付きメッシュ (textured mesh)や neural radient fields としてレンダリングできる出力を生成 する能力を特徴とする。 Point-E との比較では、高速、高品質の生成が可能であるとされている。
【目次】
【文献】
Heewoo Jun, Alex Nichol, Shap-E: Generating Conditional 3D Implicit Functions, https://arxiv.org/abs/2305.02463, 2023.
https://arxiv.org/pdf/2305.02463v1.pdf
【関連する外部ページ】
- GitHub の公式ページ: https://github.com/openai/shap-e
- hysts による Hugging Face 上のデモ: https://huggingface.co/spaces/hysts/Shap-E
前準備
Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)または Visual Studio 2022 のインストール(Windows 上)
【インストールの判断】 Build Tools for Visual Studio は,開発ツールセットである. Visual Studio は統合開発環境であり,いくつかの種類があり,Build Tools for Visual Studioの機能を含むか連携して使用するものである.インストールは以下の基準で判断してください:
- Build Tools for Visual Studio の機能のみが必要な場合
- Visual Studio の機能が必要である,あるいは,よく分からない場合
Visual Studio 2022 をインストールする際に,「C++ によるデスクトップ開発」を選択することで, Build Tools for Visual Studio 2022 の機能も一緒にインストールされる.
不明な点がある場合は,Visual Studio 全体をインストール を行う方が良い.
Build Tools for Visual Studio 2022 のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
次のコマンドは,Build Tools for Visual Studio 2022と VC2015 再配布可能パッケージをインストールするものである.
- Build Tools for Visual Studio 2022 での C++ によるデスクトップ開発,CLI,ATL,MFC のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Build Tools 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をクリック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」,「ATL」,「MFC」をチェックする.その後,「変更」をクリック.
- Visual Studio Installer の起動
Visual Studio のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
- コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- インストールコマンドの実行
winget install Microsoft.VisualStudio.2022.Community --scope machine --override "--add Microsoft.VisualStudio.Workload.NativeDesktop Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core Microsoft.VisualStudio.Component.VC.CLI.Support Microsoft.VisualStudio.Component.CoreEditor Microsoft.VisualStudio.Component.NuGet Microsoft.VisualStudio.Component.Roslyn.Compiler Microsoft.VisualStudio.Component.TextTemplating Microsoft.VisualStudio.Component.Windows.SDK.Latest Microsoft.VisualStudio.Component.VC.Tools.x86.x64 Microsoft.VisualStudio.Component.VC.ATL Microsoft.VisualStudio.Component.VC.ATLMFC" winget install Microsoft.VisualStudio.2022.Community --scope machine Microsoft.VCRedist.2015+.x64
インストールされるコンポーネントの説明:
NativeDesktop
:C++によるデスクトップアプリケーション開発のためのワークロード一式NativeDesktop.Core
:C++デスクトップ開発に必要な基本コンポーネント群VC.CLI.Support
:マネージドコードとネイティブコードの統合開発を可能にするC++/CLIサポートCoreEditor
:コード編集,デバッグ,検索などの基本機能を提供するVisual StudioのコアエディタNuGet
:.NETライブラリの依存関係を管理するパッケージ管理システムWindows.SDK.Latest
:Windows 向けアプリケーション開発用SDK(Software Development Kit)VC.Tools.x86.x64
:32ビット及び64ビット向けC++コンパイラとビルドツールVC.ATL
:Windowsコンポーネント開発用のActive Template LibraryVC.ATLMFC
:デスクトップアプリケーション開発用のMicrosoft Foundation Class Library
システム要件と注意事項:
- 管理者権限でのインストールが必須
- 必要ディスク容量:10GB以上
- 推奨メモリ:8GB以上のRAM
- インストール過程でシステムの再起動が要求される可能性がある
- 安定したインターネット接続環境が必要
追加のコンポーネントが必要な場合は,Visual Studio Installerを使用して個別にインストールすることが可能である.
- インストール完了の確認
winget list Microsoft.VisualStudio.2022.Community
トラブルシューティング:
インストール失敗時は,以下のログファイルを確認:
%TEMP%\dd_setup_<timestamp>.log %TEMP%\dd_bootstrapper_<timestamp>.log
- Visual Studio での C++ によるデスクトップ開発,CLI のインストール(Windows 上)
- Visual Studio Installer の起動
起動方法: スタートメニューの「Visual Studio Installer」を選ぶ.
- Visual Studio Community 2022 で「変更」を選ぶ.
- 「C++ によるデスクトップ開発」をチェック.そして,画面右側の「インストール」の詳細で「v143 ビルドツール用 C++/CLI サポート(最新)」をチェックする.その後,「インストール」をクリック.
- Visual Studio Installer の起動
Python 3.10,Git のインストール(Windows 上)
Pythonは,プログラミング言語の1つ. Gitは,分散型のバージョン管理システム.
【手順】
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
次のコマンドを実行
次のコマンドは,Python ランチャーとPython 3.10とGitをインストールし,Gitにパスを通すものである.
次のコマンドでインストールされるGitは 「git for Windows」と呼ばれるものであり, Git,MinGW などから構成されている.
winget install --scope machine Python.Launcher winget install --scope machine Python.Python.3.10 winget install --scope machine Git.Git powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\Git\cmd\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
【関連する外部ページ】
- Python の公式ページ: https://www.python.org/
- Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連項目】 Python, Git バージョン管理システム, Git の利用
Build Tools for Visual Studio 2022,NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN 8.9.7 のインストール(Windows 上)
【サイト内の関連ページ】 NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
- Windows での Build Tools for Visual Studio 2022 のインストール: 別ページ »で説明
- Windows での NVIDIA ドライバ,NVIDIA CUDA ツールキット 11.8,NVIDIA cuDNN v8.9.7 のインストール手順: 別ページ »で説明
【関連する外部ページ】
- Build Tools for Visual Studio 2022 (ビルドツール for Visual Studio 2022)の公式ダウンロードページ: https://visualstudio.microsoft.com/ja/visual-cpp-build-tools/
- NVIDIA ドライバのダウンロードの公式ページ: https://www.nvidia.co.jp/Download/index.aspx?lang=jp
- NVIDIA CUDA ツールキットのアーカイブの公式ページ: https://developer.nvidia.com/cuda-toolkit-archive
- NVIDIA cuDNN のダウンロードの公式ページ: https://developer.nvidia.com/cudnn
PyTorch のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- PyTorch のページを確認
- 次のようなコマンドを実行(実行するコマンドは,PyTorch のページの表示されるコマンドを使う).
次のコマンドを実行することにより, PyTorch 2.3 (NVIDIA CUDA 11.8 用)がインストールされる. 但し,Anaconda3を使いたい場合には別手順になる.
事前に NVIDIA CUDA のバージョンを確認しておくこと(ここでは,NVIDIA CUDA ツールキット 11.8 が前もってインストール済みであるとする).
PyTorch で,GPU が動作している場合には,「torch.cuda.is_available()」により,True が表示される.
python -m pip install -U --ignore-installed pip python -m pip uninstall -y torch torchvision torchaudio torchtext xformers python -m pip install -U torch torchvision torchaudio numpy --index-url https://download.pytorch.org/whl/cu118 python -c "import torch; print(torch.__version__, torch.cuda.is_available())"
Anaconda3を使いたい場合には, Anaconda プロンプト (Anaconda Prompt) を管理者として実行し, 次のコマンドを実行する. (PyTorch と NVIDIA CUDA との連携がうまくいかない可能性があるため,Anaconda3を使わないことも検討して欲しい).
conda install -y pytorch torchvision torchaudio pytorch-cuda=11.8 cudnn -c pytorch -c nvidia py -c "import torch; print(torch.__version__, torch.cuda.is_available())"
【サイト内の関連ページ】
【関連する外部ページ】
Shap-E のインストール(Windows 上)
Blender のインストール
Windows でのインストールと日本語化: 別ページ »で説明
Shap-E のインストール(Windows 上)
- Windows で,コマンドプロンプトを管理者権限で起動する(例:Windowsキーを押し,「cmd」と入力し,「管理者として実行」を選択)
- インストール
cd /d c:%HOMEPATH% rmdir /s /q shap-e git clone --recursive https://github.com/openai/shap-e cd shap-e python -m pip install -e .
(以下省略)
Shap-E の動作確認(Windows 上)
テキストからの立体生成を行ってみる.
参考ページ: https://github.com/openai/shap-e/blob/main/shap_e/examples/sample_text_to_3d.ipynb
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH%\shap-e notepad a.py
- エディタで,次のプログラムを保存
このプログラムは, 公式ページ https://github.com/openai/shap-e/blob/main/shap_e/examples/sample_text_to_3d.ipynbで公開されているものを変更して使用している.
import torch import matplotlib.pyplot as plt from PIL import Image from shap_e.diffusion.sample import sample_latents from shap_e.diffusion.gaussian_diffusion import diffusion_from_config from shap_e.models.download import load_model, load_config from shap_e.util.notebooks import create_pan_cameras, decode_latent_images, gif_widget device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') xm = load_model('transmitter', device=device) model = load_model('text300M', device=device) diffusion = diffusion_from_config(load_config('diffusion')) batch_size = 4 guidance_scale = 15.0 prompt = "a shark" latents = sample_latents( batch_size=batch_size, model=model, diffusion=diffusion, guidance_scale=guidance_scale, model_kwargs=dict(texts=[prompt] * batch_size), progress=True, clip_denoised=True, use_fp16=True, use_karras=True, karras_steps=64, sigma_min=1e-3, sigma_max=160, s_churn=0, ) render_mode = 'nerf' # you can change this to 'stf' size = 64 # this is the size of the renders; higher values take longer to render. cameras = create_pan_cameras(size, device) for i, latent in enumerate(latents): images = decode_latent_images(xm, latent, cameras, rendering_mode=render_mode) fig, axes = plt.subplots(nrows=len(images), figsize=(8, 8)) for ax, image in zip(axes, images): ax.imshow(image) ax.axis('off') plt.tight_layout() plt.show() # Example of saving the latents as meshes. from shap_e.util.notebooks import decode_latent_mesh for i, latent in enumerate(latents): t = decode_latent_mesh(xm, latent).tri_mesh() with open(f'example_mesh_{i}.ply', 'wb') as f: t.write_ply(f) with open(f'example_mesh_{i}.obj', 'w') as f: t.write_obj(f)
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
【サイト内の関連ページ】 Python のまとめ: 別ページ »
プログラムを a.pyのようなファイル名で保存したので, 「python a.py」のようなコマンドで行う.
python a.py
GPU のメモリが足りなくて実行できない場合,GPUがない場合は,a.py の次の2箇所を変更して実行.
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
「device = 'cpu'」に変更
- use_fp16=True
「use_fp16=False」に変更
- 実行後に,画像が複数回表示される.そのたびに,右上の「x」で閉じる.
- 実行終了を確認.
- example_mesh_0.obj, example_mesh_0.ply,
example_mesh_1.obj, example_mesh_1.ply,
example_mesh_2.obj, example_mesh_2.ply,
example_mesh_3.obj, example_mesh_3.ply
ができる.
このうち example_mesh_0.obj をBlenderで確認してみる.結果は次の通り.
Shap-E を使う Python プログラムの実行(Windows 上)
実行時にプロンプトを指定する.
- 前準備として,コマンドプロンプトを管理者として開き,
次のコマンドを実行する
このコマンドの実行は1回だけで良い
python -m pip install PyOpenGL PyOpenGL-accelerate pygame pywavefront
- Windows で,コマンドプロンプトを実行
- エディタを起動
cd /d c:%HOMEPATH%\shap-e notepad d.py
- エディタで,次のプログラムを保存
このプログラムは, 公式ページ https://github.com/openai/shap-e/blob/main/shap_e/examples/sample_text_to_3d.ipynbで公開されているものを変更して使用している.
後半には,ply ファイルを表示するプログラムを追加している.
import torch import matplotlib.pyplot as plt from PIL import Image from shap_e.diffusion.sample import sample_latents from shap_e.diffusion.gaussian_diffusion import diffusion_from_config from shap_e.models.download import load_model, load_config from shap_e.util.notebooks import create_pan_cameras, decode_latent_images, gif_widget print("prompt=") prompt = input() device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') xm = load_model('transmitter', device=device) model = load_model('text300M', device=device) diffusion = diffusion_from_config(load_config('diffusion')) batch_size = 4 guidance_scale = 15.0 latents = sample_latents( batch_size=batch_size, model=model, diffusion=diffusion, guidance_scale=guidance_scale, model_kwargs=dict(texts=[prompt] * batch_size), progress=True, clip_denoised=True, use_fp16=True, use_karras=True, karras_steps=64, sigma_min=1e-3, sigma_max=160, s_churn=0, ) render_mode = 'nerf' # you can change this to 'stf' size = 64 # this is the size of the renders; higher values take longer to render. cameras = create_pan_cameras(size, device) for i, latent in enumerate(latents): images = decode_latent_images(xm, latent, cameras, rendering_mode=render_mode) # Example of saving the latents as meshes. from shap_e.util.notebooks import decode_latent_mesh for i, latent in enumerate(latents): t = decode_latent_mesh(xm, latent).tri_mesh() with open(f'example_mesh_{i}.ply', 'wb') as f: t.write_ply(f) with open(f'example_mesh_{i}.obj', 'w') as f: t.write_obj(f) import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLUT import * from OpenGL.GLU import * from plyfile import PlyData, PlyElement # PLYファイルを読み込む import tkinter as tk from tkinter import filedialog root = tk.Tk() root.withdraw() fpath = filedialog.askopenfilename() plydata = PlyData.read(fpath) vertex_data = plydata['vertex'].data face_data = plydata['face'].data # 頂点と面をリストとして取得 vertices = [list(elem) for elem in vertex_data] faces = [face[0] for face in face_data] # PygameとOpenGLを初期化 pygame.init() display = (800, 600) pygame.display.set_mode(display, DOUBLEBUF | OPENGL) gluPerspective(45, (display[0] / display[1]), 0.1, 50.0) glTranslatef(0.0, 0.0, -5) # マウス操作のための変数 rotation_enabled = False rotation_start = (0, 0) zoom = 0.0 # メインループ while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() elif event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # 左クリック rotation_enabled = True rotation_start = pygame.mouse.get_pos() elif event.button == 4: # ホイール回転(上方向) zoom = 1 elif event.button == 5: # ホイール回転(下方向) zoom = -1 elif event.type == pygame.MOUSEBUTTONUP: if event.button == 1: # 左クリック解除 rotation_enabled = False elif event.type == pygame.MOUSEMOTION: if rotation_enabled: dx = event.pos[0] - rotation_start[0] dy = event.pos[1] - rotation_start[1] glRotatef(dx, 0, 1, 0) # y軸周りに回転 glRotatef(dy, 1, 0, 0) # x軸周りに回転 rotation_start = event.pos glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # 視点の移動範囲を制限 max_zoom = 5.0 min_zoom = -5.0 zoom = max(min_zoom, min(max_zoom, zoom)) glTranslatef(0.0, 0.0, -zoom) zoom = 0 glBegin(GL_TRIANGLES) for face in faces: for vertex_i in face: glVertex3fv(vertices[vertex_i][:3]) glEnd() pygame.display.flip() pygame.time.wait(10)
- Python プログラムの実行
Python プログラムの実行
- Windows では python (Python ランチャーは py)
- Ubuntu では python3
【サイト内の関連ページ】 Python のまとめ: 別ページ »
プログラムを d.pyのようなファイル名で保存したので, 「python d.py」のようなコマンドで行う.
python d.py
GPU のメモリが足りなくて実行できない場合,GPUがない場合は,a.py の次の2箇所を変更して実行.
- device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
「device = 'cpu'」に変更
- use_fp16=True
「use_fp16=False」に変更
その後,プロンプトを入力する.
example_mesh_0.obj, example_mesh_0.ply, example_mesh_1.obj, example_mesh_1.ply, example_mesh_2.obj, example_mesh_2.ply, example_mesh_3.obj, example_mesh_3.ply ができる.
- ファイルダイアログが開く.確認したい ply ファイルを1つ選ぶ
- 選んだファイルが表示される.これは確認のため.
マウスの左クリックとマウス移動により回転できる.マウスホイールにより,前後移動する.
- example_mesh_0.obj をBlenderで確認してみる.結果は次の通り.
プロンプトを tree に変えて実行してみた結果