【目次】
【文献】 Zhou, Yichao and Qi, Haozhi and Huang, Jingwei and Ma, Yi, NeurVPS: Neural Vanishing Point Scanning via Conic Convolution, NeurIPS, 2019.
Gitは,バージョン管理システム.ソースコードの管理や複数人での共同に役立つ.
【サイト内の関連ページ】
Windows での Git のインストール: 別ページ »で説明している.
【関連する外部ページ】
Git の公式ページ: https://git-scm.com/
【サイト内の関連ページ】
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
【サイト内の関連ページ】
NVIDIA グラフィックスボードを搭載しているパソコンの場合には, NVIDIA ドライバ, NVIDIA CUDA ツールキット, NVIDIA cuDNN のインストールを行う.
【関連する外部ページ】
コマンドプロンプトを管理者として実行: 別ページ »で説明
PyTorch のページ: https://pytorch.org/index.html
次のコマンドを実行することにより, 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())"
【サイト内の関連ページ】
【関連する外部ページ】
Windows での FFmpeg のインストール(Windows 上): 別ページ »で説明している.
7-Zipは,ファイル圧縮・展開(解凍)ツール
コマンドプロンプトを管理者として実行: 別ページ »で説明
次のコマンドは,7-Zipをインストールするものである.
winget install --scope machine 7zip.7zip powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\7-Zip\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
【関連する外部ページ】
mkdir %USERPROFILE%\7zip cd %USERPROFILE%\7zip curl -O https://www.7-zip.org/a/7z2405-x64.exe .\7z2405-x64.exe powershell -command "$oldpath = [System.Environment]::GetEnvironmentVariable(\"Path\", \"Machine\"); $oldpath += \";c:\Program Files\7-Zip\"; [System.Environment]::SetEnvironmentVariable(\"Path\", $oldpath, \"Machine\")"
コマンドプロンプトを管理者として実行: 別ページ »で説明
cd %USERPROFILE% rmdir /s /q neurvps git clone https://github.com/zhou13/neurvps python -m pip install -U tensorboardx pyyaml docopt matplotlib scikit-image opencv-python tqdm gdown ninja mkdir data logs cd data gdown 1yRwLv28ozRvjsf9wGwAqzya1xFZ5wYET -O su3.tar.xz gdown 1rpQNbZQEUff2j2rxr3mBl6xohGFl6sLv -O tmm17.tar.xz gdown 1y_O9PxZhJ_Ml297FgoWMBLvjC1BvTs9A -O scannet.tar.xz "c:\Program Files\7-Zip\7z.exe" x su3.tar.xz "c:\Program Files\7-Zip\7z.exe" x tmm17.tar.xz "c:\Program Files\7-Zip\7z.exe" x scannet.tar.xz "c:\Program Files\7-Zip\7z.exe" x su3.tar "c:\Program Files\7-Zip\7z.exe" x tmm17.tar "c:\Program Files\7-Zip\7z.exe" x scannet.tar
次のページの「Pre-trained Models」のところから学習済みモデルをダウンロード
https://github.com/zhou13/neurvps
3種類あるので,使いたいもの1つをダウンロードする.
zip ファイルがダウンロードされるので,展開(解凍)し,%HOMEPATH%\neurvps に置く.
公式ページ https://github.com/zhou13/neurvps の記載に従い,eval.py を実行
起動は,Windows のメニューで「Visual Studio 20..」の下の「x64 Native Tools コマンドプロンプト (x64 Native Tools Command Prompt)」を選ぶ.「x64」は,64ビット版の意味である.
「x64 Native Tools コマンドプロンプト (x64 Native Tools Command Prompt)」がないとき:
C++ ビルドツール (Build Tools) のインストールを行うことで, 「x64 Native Tools コマンドプロンプト (x64 Native Tools Command Prompt)」がインストールされる.その手順は,別ページ »で説明
cd %USERPROFILE% cd neurvps python eval.py -d 0 config.yaml checkpoint_latest.pth.tar
画像ファイルは,%HOMEPATH%\neurvps に「sample.png」というファイル名で保存すること.あとで使用する.
https://github.com/zhou13/neurvps で公開されている公式のプログラム eval.py を書き換えたものを使用.
#!/usr/bin/env python3 """Compute vanishing points using corase-to-fine method Usage: eval.py [options]Arguments: Path to the yaml hyper-parameter file Path to the checkpoint """ import os import sys import math import shlex import pprint import random import os.path as osp import threading import subprocess import numpy as np import torch from torchvision import transforms import matplotlib as mpl import skimage.io from PIL import Image import numpy.linalg as LA import matplotlib.pyplot as plt import mpl_toolkits.mplot3d from tqdm import tqdm from docopt import docopt import neurvps import neurvps.models.vanishing_net as vn from neurvps.config import C, M from neurvps.datasets import Tmm17Dataset, ScanNetDataset, WireframeDataset IMAGENAME="sample.png" def AA(x, y, threshold): index = np.searchsorted(x, threshold) x = np.concatenate([x[:index], [threshold]]) y = np.concatenate([y[:index], [threshold]]) return ((x[1:] - x[:-1]) * y[:-1]).sum() / threshold transform = transforms.Compose( [ transforms.ToTensor(), ] ) def main(): args = docopt(__doc__) config_file = args[" "] C.update(C.from_yaml(filename=config_file)) C.model.im2col_step = 32 # override im2col_step for evaluation M.update(C.model) pprint.pprint(C, indent=4) random.seed(0) np.random.seed(0) torch.manual_seed(0) device_name = "cpu" os.environ["CUDA_VISIBLE_DEVICES"] = args["--devices"] if torch.cuda.is_available(): device_name = "cuda" torch.backends.cudnn.deterministic = True torch.cuda.manual_seed(0) print("Let's use", torch.cuda.device_count(), "GPU(s)!") else: print("CUDA is not available") device = torch.device(device_name) if M.backbone == "stacked_hourglass": model = neurvps.models.hg( planes=64, depth=M.depth, num_stacks=M.num_stacks, num_blocks=M.num_blocks ) else: raise NotImplementedError checkpoint = torch.load(args[" "]) model = neurvps.models.VanishingNet( model, C.model.output_stride, C.model.upsample_scale ) model = model.to(device) model = torch.nn.DataParallel( model, device_ids=list(range(args["--devices"].count(",") + 1)) ) model.load_state_dict(checkpoint["model_state_dict"]) # model.eval() if C.io.dataset.upper() == "WIREFRAME": Dataset = WireframeDataset elif C.io.dataset.upper() == "TMM17": Dataset = Tmm17Dataset elif C.io.dataset.upper() == "SCANNET": Dataset = ScanNetDataset else: raise NotImplementedError loader = torch.utils.data.DataLoader( Dataset(C.io.datadir, split="valid"), batch_size=1, shuffle=False, num_workers=C.io.num_workers if os.name != "nt" else 0, pin_memory=True, ) if args["--dump"] is not None: os.makedirs(args["--dump"], exist_ok=True) err = [] n = C.io.num_vpts im = Image.open(IMAGENAME).resize((512,512)) image = transform(im).unsqueeze(0).to(device) input_dict = {"image": image, "test": True} vpts = sample_sphere(np.array([0, 0, 1]), np.pi / 2, 64) input_dict["vpts"] = vpts with torch.no_grad(): score = model(input_dict)[:, -1].cpu().numpy() index = np.argsort(-score) candidate = [index[0]] for i in index[1:]: if len(candidate) == n: break dst = np.min(np.arccos(np.abs(vpts[candidate] @ vpts[i]))) if dst < np.pi / n: continue candidate.append(i) vpts_pd = vpts[candidate] for res in range(1, len(M.multires)): vpts = [sample_sphere(vpts_pd[vp], M.multires[-res], 64) for vp in range(n)] input_dict["vpts"] = np.vstack(vpts) with torch.no_grad(): score = model(input_dict)[:, -res - 1].cpu().numpy().reshape(n, -1) for i, s in enumerate(score): vpts_pd[i] = vpts[i][np.argmax(s)] plt.imshow(im) cc = ["blue", "cyan", "orange"] for c, w in zip(cc, vpts_pd): x = w[0] / w[2] * C.io.focal_length * 256 + 256 y = -w[1] / w[2] * C.io.focal_length * 256 + 256 print(x,y) plt.scatter(x, y, color=c) for xy in np.linspace(0, 512, 10): plt.plot( [x, xy, x, xy, x, 0, x, 511], [y, 0, y, 511, y, xy, y, xy], color=c, ) plt.show() err = np.sort(np.array(err)) np.savez(args["--output"], err=err) y = (1 + np.arange(len(err))) / len(loader) / n def sample_sphere(v, alpha, num_pts): v1 = orth(v) v2 = np.cross(v, v1) v, v1, v2 = v[:, None], v1[:, None], v2[:, None] indices = np.linspace(1, num_pts, num_pts) phi = np.arccos(1 + (math.cos(alpha) - 1) * indices / num_pts) theta = np.pi * (1 + 5 ** 0.5) * indices r = np.sin(phi) return (v * np.cos(phi) + r * (v1 * np.cos(theta) + v2 * np.sin(theta))).T def orth(v): x, y, z = v o = np.array([0.0, -z, y] if abs(x) < abs(y) else [-z, 0.0, x]) o /= LA.norm(o) return o if __name__ == "__main__": main()
コマンドプロンプトで次を実行
cd %HOMEPATH%\neurvps python run.py -d 0 config.yaml checkpoint_latest.pth.tar