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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {
|
6 |
+
"id": "saNBv0dY-Eef"
|
7 |
+
},
|
8 |
+
"source": [
|
9 |
+
"# Nerfies Dataset Processing.\n",
|
10 |
+
"\n",
|
11 |
+
"**Author**: [Keunhong Park](https://keunhong.com)\n",
|
12 |
+
"\n",
|
13 |
+
"[[Project Page](https://nerfies.github.io)]\n",
|
14 |
+
"[[Paper](https://storage.googleapis.com/nerfies-public/videos/nerfies_paper.pdf)]\n",
|
15 |
+
"[[Video](https://www.youtube.com/watch?v=MrKrnHhk8IA)]\n",
|
16 |
+
"[[GitHub](https://github.com/google/nerfies)]\n",
|
17 |
+
"\n",
|
18 |
+
"This notebook contains an example workflow for converting a video file to a Nerfies dataset.\n",
|
19 |
+
"\n",
|
20 |
+
"### Instructions\n",
|
21 |
+
"\n",
|
22 |
+
"1. Convert a video into our dataset format using this notebook.\n",
|
23 |
+
"2. Train a Nerfie using the [training notebook](https://colab.sandbox.google.com/github/google/nerfies/blob/main/notebooks/Nerfies_Training.ipynb).\n",
|
24 |
+
"\n",
|
25 |
+
"\n",
|
26 |
+
"### Notes\n",
|
27 |
+
"* While this will work for small datasets in a Colab runtime, larger datasets will require more compute power.\n",
|
28 |
+
"* If you would like to train a model on a serious dataset, you should consider copying this to your own workstation and running it there. Some minor modifications will be required, and you will have to install the dependencies separately.\n",
|
29 |
+
"* Please report issues on the [GitHub issue tracker](https://github.com/google/nerfies/issues).\n",
|
30 |
+
"\n",
|
31 |
+
"If you find this work useful, please consider citing:\n",
|
32 |
+
"```bibtex\n",
|
33 |
+
"@article{park2021nerfies\n",
|
34 |
+
" author = {Park, Keunhong \n",
|
35 |
+
" and Sinha, Utkarsh \n",
|
36 |
+
" and Barron, Jonathan T. \n",
|
37 |
+
" and Bouaziz, Sofien \n",
|
38 |
+
" and Goldman, Dan B \n",
|
39 |
+
" and Seitz, Steven M. \n",
|
40 |
+
" and Martin-Brualla, Ricardo},\n",
|
41 |
+
" title = {Nerfies: Deformable Neural Radiance Fields},\n",
|
42 |
+
" journal = {ICCV},\n",
|
43 |
+
" year = {2021},\n",
|
44 |
+
"}\n",
|
45 |
+
"```"
|
46 |
+
]
|
47 |
+
},
|
48 |
+
{
|
49 |
+
"cell_type": "markdown",
|
50 |
+
"metadata": {
|
51 |
+
"id": "cbXoNhFF-D8Q"
|
52 |
+
},
|
53 |
+
"source": [
|
54 |
+
"## Install dependencies."
|
55 |
+
]
|
56 |
+
},
|
57 |
+
{
|
58 |
+
"cell_type": "code",
|
59 |
+
"execution_count": null,
|
60 |
+
"metadata": {
|
61 |
+
"colab": {
|
62 |
+
"base_uri": "https://localhost:8080/",
|
63 |
+
"height": 1000
|
64 |
+
},
|
65 |
+
"id": "8QlvguTr92ko",
|
66 |
+
"outputId": "685cdf9f-4998-43e0-d3f3-3e88d196410e"
|
67 |
+
},
|
68 |
+
"outputs": [],
|
69 |
+
"source": [
|
70 |
+
"#!apt-get install colmap ffmpeg\n",
|
71 |
+
"\n",
|
72 |
+
"#!pip install numpy==1.19.3\n",
|
73 |
+
"#!pip install mediapipe\n",
|
74 |
+
"#!pip install tensorflow_graphics\n",
|
75 |
+
"#!pip install git+https://github.com/google/nerfies.git@v2\n",
|
76 |
+
"#!pip install \"git+https://github.com/google/nerfies.git#egg=pycolmap&subdirectory=third_party/pycolmap\"\n",
|
77 |
+
"\n",
|
78 |
+
"!wget https://raw.githubusercontent.com/xieyizheng/hypernerf/main/requirements.txt\n",
|
79 |
+
"!python --version\n",
|
80 |
+
"!pip install -r requirements.txt\n",
|
81 |
+
"\n",
|
82 |
+
"#recommend to restart runtime if freshly installed the reqirements"
|
83 |
+
]
|
84 |
+
},
|
85 |
+
{
|
86 |
+
"cell_type": "markdown",
|
87 |
+
"metadata": {
|
88 |
+
"id": "7Z-ASlgBUPXJ"
|
89 |
+
},
|
90 |
+
"source": [
|
91 |
+
"## Configuration.\n",
|
92 |
+
"\n",
|
93 |
+
"Mount Google Drive onto `/content/gdrive`. You can skip this if you want to run this locally."
|
94 |
+
]
|
95 |
+
},
|
96 |
+
{
|
97 |
+
"cell_type": "code",
|
98 |
+
"execution_count": null,
|
99 |
+
"metadata": {
|
100 |
+
"colab": {
|
101 |
+
"base_uri": "https://localhost:8080/"
|
102 |
+
},
|
103 |
+
"id": "1AL4QpsBUO9p",
|
104 |
+
"outputId": "1d1cdf4e-47a9-449c-d585-1e794ae8fc63"
|
105 |
+
},
|
106 |
+
"outputs": [],
|
107 |
+
"source": [
|
108 |
+
"from google.colab import drive\n",
|
109 |
+
"drive.mount('/content/gdrive')"
|
110 |
+
]
|
111 |
+
},
|
112 |
+
{
|
113 |
+
"cell_type": "code",
|
114 |
+
"execution_count": null,
|
115 |
+
"metadata": {
|
116 |
+
"cellView": "form",
|
117 |
+
"colab": {
|
118 |
+
"base_uri": "https://localhost:8080/"
|
119 |
+
},
|
120 |
+
"id": "5NR5OGyeUOKU",
|
121 |
+
"outputId": "c11dd81a-8030-4699-d790-628c6b8d56e4"
|
122 |
+
},
|
123 |
+
"outputs": [],
|
124 |
+
"source": [
|
125 |
+
"# @title Configure dataset directories\n",
|
126 |
+
"from pathlib import Path\n",
|
127 |
+
"\n",
|
128 |
+
"# @markdown The base directory for all captures. This can be anything if you're running this notebook on your own Jupyter runtime.\n",
|
129 |
+
"save_dir = '/content/gdrive/My Drive/nerfies/captures' # @param {type: 'string'}\n",
|
130 |
+
"# @markdown The name of this capture. The working directory will be `$save_dir/$capture_name`. **Make sure you change this** when processing a new video.\n",
|
131 |
+
"capture_name = 'dvd' # @param {type: 'string'}\n",
|
132 |
+
"# The root directory for this capture.\n",
|
133 |
+
"root_dir = Path(save_dir, capture_name)\n",
|
134 |
+
"# Where to save RGB images.\n",
|
135 |
+
"rgb_dir = root_dir / 'rgb'\n",
|
136 |
+
"rgb_raw_dir = root_dir / 'rgb-raw'\n",
|
137 |
+
"# Where to save the COLMAP outputs.\n",
|
138 |
+
"colmap_dir = root_dir / 'colmap'\n",
|
139 |
+
"colmap_db_path = colmap_dir / 'database.db'\n",
|
140 |
+
"colmap_out_path = colmap_dir / 'sparse'\n",
|
141 |
+
"\n",
|
142 |
+
"colmap_out_path.mkdir(exist_ok=True, parents=True)\n",
|
143 |
+
"rgb_raw_dir.mkdir(exist_ok=True, parents=True)\n",
|
144 |
+
"\n",
|
145 |
+
"print(f\"\"\"Directories configured:\n",
|
146 |
+
" root_dir = {root_dir}\n",
|
147 |
+
" rgb_raw_dir = {rgb_raw_dir}\n",
|
148 |
+
" rgb_dir = {rgb_dir}\n",
|
149 |
+
" colmap_dir = {colmap_dir}\n",
|
150 |
+
"\"\"\")"
|
151 |
+
]
|
152 |
+
},
|
153 |
+
{
|
154 |
+
"cell_type": "markdown",
|
155 |
+
"metadata": {
|
156 |
+
"id": "to4QpKLFHf2s"
|
157 |
+
},
|
158 |
+
"source": [
|
159 |
+
"## Dataset Processing."
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "markdown",
|
164 |
+
"metadata": {
|
165 |
+
"id": "nscgY8DW-DHk"
|
166 |
+
},
|
167 |
+
"source": [
|
168 |
+
"### Load Video.\n",
|
169 |
+
"\n",
|
170 |
+
"In this step we upload a video file and flatten it into PNG files using ffmpeg."
|
171 |
+
]
|
172 |
+
},
|
173 |
+
{
|
174 |
+
"cell_type": "code",
|
175 |
+
"execution_count": null,
|
176 |
+
"metadata": {
|
177 |
+
"colab": {
|
178 |
+
"base_uri": "https://localhost:8080/",
|
179 |
+
"height": 74
|
180 |
+
},
|
181 |
+
"id": "SFzPpUoM99nd",
|
182 |
+
"outputId": "aefa3e8b-a4fc-426e-b51e-d837a73b7f3e"
|
183 |
+
},
|
184 |
+
"outputs": [],
|
185 |
+
"source": [
|
186 |
+
"# @title Upload video file.\n",
|
187 |
+
"# @markdown Select a video file (.mp4, .mov, etc.) from your disk. This will upload it to the local Colab working directory.\n",
|
188 |
+
"from google.colab import files\n",
|
189 |
+
"\n",
|
190 |
+
"uploaded = files.upload()"
|
191 |
+
]
|
192 |
+
},
|
193 |
+
{
|
194 |
+
"cell_type": "code",
|
195 |
+
"execution_count": null,
|
196 |
+
"metadata": {
|
197 |
+
"cellView": "form",
|
198 |
+
"colab": {
|
199 |
+
"base_uri": "https://localhost:8080/"
|
200 |
+
},
|
201 |
+
"id": "rjnL6FdlCGhE",
|
202 |
+
"outputId": "e308f5b2-e386-4ad9-bf6b-b23ab8c26a18"
|
203 |
+
},
|
204 |
+
"outputs": [],
|
205 |
+
"source": [
|
206 |
+
"# @title Flatten into images.\n",
|
207 |
+
"\n",
|
208 |
+
"import cv2\n",
|
209 |
+
"\n",
|
210 |
+
"\n",
|
211 |
+
"# @markdown Flattens the video into images. The results will be saved to `rgb_raw_dir`.\n",
|
212 |
+
"#if local, just set the video_path here\n",
|
213 |
+
"video_path = next(iter(uploaded.keys()))\n",
|
214 |
+
"\n",
|
215 |
+
"# @markdown Adjust `max_scale` to something smaller for faster processing.\n",
|
216 |
+
"max_scale = 1.0 # @param {type:'number'}\n",
|
217 |
+
"# @markdown A smaller FPS will be much faster for bundle adjustment, but at the expensive of a lower sampling density for training. For the paper we used ~15 fps but we default to something lower here to get you started faster.\n",
|
218 |
+
"# @markdown If given an fps of -1 we will try to auto-compute it.\n",
|
219 |
+
"fps = -1 # @param {type:'number'}\n",
|
220 |
+
"target_num_frames = 200 # @param {type: 'number'}\n",
|
221 |
+
"\n",
|
222 |
+
"cap = cv2.VideoCapture(video_path)\n",
|
223 |
+
"input_fps = cap.get(cv2.CAP_PROP_FPS)\n",
|
224 |
+
"num_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n",
|
225 |
+
"\n",
|
226 |
+
"if num_frames < target_num_frames:\n",
|
227 |
+
" raise RuntimeError(\n",
|
228 |
+
" 'The video is too short and has fewer frames than the target.')\n",
|
229 |
+
"\n",
|
230 |
+
"if fps == -1:\n",
|
231 |
+
" fps = int(target_num_frames / num_frames * input_fps)\n",
|
232 |
+
" print(f\"Auto-computed FPS = {fps}\")\n",
|
233 |
+
"\n",
|
234 |
+
"# @markdown Check this if you want to reprocess the frames.\n",
|
235 |
+
"overwrite = False # @param {type:'boolean'}\n",
|
236 |
+
"\n",
|
237 |
+
"if (rgb_dir / '1x').exists() and not overwrite:\n",
|
238 |
+
" raise RuntimeError(\n",
|
239 |
+
" f'The RGB frames have already been processed. Check `overwrite` and run again if you really meant to do this.')\n",
|
240 |
+
"else:\n",
|
241 |
+
" filters = f\"mpdecimate,setpts=N/FRAME_RATE/TB,scale=iw*{max_scale}:ih*{max_scale}\"\n",
|
242 |
+
" tmp_rgb_raw_dir = 'rgb-raw'\n",
|
243 |
+
" out_pattern = str('rgb-raw/%06d.png')\n",
|
244 |
+
" !mkdir -p \"$tmp_rgb_raw_dir\"\n",
|
245 |
+
" !ffmpeg -i \"$video_path\" -r $fps -vf $filters \"$out_pattern\"\n",
|
246 |
+
" !mkdir -p \"$rgb_raw_dir\"\n",
|
247 |
+
" !rsync -av \"$tmp_rgb_raw_dir/\" \"$rgb_raw_dir/\""
|
248 |
+
]
|
249 |
+
},
|
250 |
+
{
|
251 |
+
"cell_type": "code",
|
252 |
+
"execution_count": null,
|
253 |
+
"metadata": {
|
254 |
+
"cellView": "form",
|
255 |
+
"colab": {
|
256 |
+
"base_uri": "https://localhost:8080/"
|
257 |
+
},
|
258 |
+
"id": "5YsXeX4ckaKJ",
|
259 |
+
"outputId": "d1ca040f-2fad-4fbe-e741-03adffa025d2"
|
260 |
+
},
|
261 |
+
"outputs": [],
|
262 |
+
"source": [
|
263 |
+
"# @title Resize images into different scales.\n",
|
264 |
+
"# @markdown Here we save the input images at various resolutions (downsample by a factor of 1, 2, 4, 8). We use area relation interpolation to prevent moire artifacts.\n",
|
265 |
+
"import concurrent.futures\n",
|
266 |
+
"import numpy as np\n",
|
267 |
+
"import cv2\n",
|
268 |
+
"import imageio\n",
|
269 |
+
"from PIL import Image\n",
|
270 |
+
"\n",
|
271 |
+
"\n",
|
272 |
+
"def save_image(path, image: np.ndarray) -> None:\n",
|
273 |
+
" print(f'Saving {path}')\n",
|
274 |
+
" if not path.parent.exists():\n",
|
275 |
+
" path.parent.mkdir(exist_ok=True, parents=True)\n",
|
276 |
+
" with path.open('wb') as f:\n",
|
277 |
+
" image = Image.fromarray(np.asarray(image))\n",
|
278 |
+
" image.save(f, format=path.suffix.lstrip('.'))\n",
|
279 |
+
"\n",
|
280 |
+
"\n",
|
281 |
+
"def image_to_uint8(image: np.ndarray) -> np.ndarray:\n",
|
282 |
+
" \"\"\"Convert the image to a uint8 array.\"\"\"\n",
|
283 |
+
" if image.dtype == np.uint8:\n",
|
284 |
+
" return image\n",
|
285 |
+
" if not issubclass(image.dtype.type, np.floating):\n",
|
286 |
+
" raise ValueError(\n",
|
287 |
+
" f'Input image should be a floating type but is of type {image.dtype!r}')\n",
|
288 |
+
" return (image * 255).clip(0.0, 255).astype(np.uint8)\n",
|
289 |
+
"\n",
|
290 |
+
"\n",
|
291 |
+
"def make_divisible(image: np.ndarray, divisor: int) -> np.ndarray:\n",
|
292 |
+
" \"\"\"Trim the image if not divisible by the divisor.\"\"\"\n",
|
293 |
+
" height, width = image.shape[:2]\n",
|
294 |
+
" if height % divisor == 0 and width % divisor == 0:\n",
|
295 |
+
" return image\n",
|
296 |
+
"\n",
|
297 |
+
" new_height = height - height % divisor\n",
|
298 |
+
" new_width = width - width % divisor\n",
|
299 |
+
"\n",
|
300 |
+
" return image[:new_height, :new_width]\n",
|
301 |
+
"\n",
|
302 |
+
"\n",
|
303 |
+
"def downsample_image(image: np.ndarray, scale: int) -> np.ndarray:\n",
|
304 |
+
" \"\"\"Downsamples the image by an integer factor to prevent artifacts.\"\"\"\n",
|
305 |
+
" if scale == 1:\n",
|
306 |
+
" return image\n",
|
307 |
+
"\n",
|
308 |
+
" height, width = image.shape[:2]\n",
|
309 |
+
" if height % scale > 0 or width % scale > 0:\n",
|
310 |
+
" raise ValueError(f'Image shape ({height},{width}) must be divisible by the'\n",
|
311 |
+
" f' scale ({scale}).')\n",
|
312 |
+
" out_height, out_width = height // scale, width // scale\n",
|
313 |
+
" resized = cv2.resize(image, (out_width, out_height), cv2.INTER_AREA)\n",
|
314 |
+
" return resized\n",
|
315 |
+
"\n",
|
316 |
+
"\n",
|
317 |
+
"\n",
|
318 |
+
"image_scales = \"1,2,4,8,16\" # @param {type: \"string\"}\n",
|
319 |
+
"image_scales = [int(x) for x in image_scales.split(',')]\n",
|
320 |
+
"\n",
|
321 |
+
"tmp_rgb_dir = Path('rgb')\n",
|
322 |
+
"\n",
|
323 |
+
"for image_path in Path(tmp_rgb_raw_dir).glob('*.png'):\n",
|
324 |
+
" image = make_divisible(imageio.imread(image_path), max(image_scales))\n",
|
325 |
+
" for scale in image_scales:\n",
|
326 |
+
" save_image(\n",
|
327 |
+
" tmp_rgb_dir / f'{scale}x/{image_path.stem}.png',\n",
|
328 |
+
" image_to_uint8(downsample_image(image, scale)))\n",
|
329 |
+
"\n",
|
330 |
+
"!rsync -av \"$tmp_rgb_dir/\" \"$rgb_dir/\""
|
331 |
+
]
|
332 |
+
},
|
333 |
+
{
|
334 |
+
"cell_type": "code",
|
335 |
+
"execution_count": null,
|
336 |
+
"metadata": {
|
337 |
+
"cellView": "form",
|
338 |
+
"colab": {
|
339 |
+
"base_uri": "https://localhost:8080/",
|
340 |
+
"height": 720
|
341 |
+
},
|
342 |
+
"id": "ql9r4rufLQue",
|
343 |
+
"outputId": "71246106-1765-4d70-8f75-c610f925e541"
|
344 |
+
},
|
345 |
+
"outputs": [],
|
346 |
+
"source": [
|
347 |
+
"# @title Example frame.\n",
|
348 |
+
"# @markdown Make sure that the video was processed correctly.\n",
|
349 |
+
"# @markdown If this gives an exception, try running the preceding cell one more time--sometimes uploading to Google Drive can fail.\n",
|
350 |
+
"\n",
|
351 |
+
"from pathlib import Path\n",
|
352 |
+
"import imageio\n",
|
353 |
+
"from PIL import Image\n",
|
354 |
+
"\n",
|
355 |
+
"image_paths = list((rgb_dir / '1x').iterdir())\n",
|
356 |
+
"Image.open(image_paths[0])"
|
357 |
+
]
|
358 |
+
},
|
359 |
+
{
|
360 |
+
"cell_type": "markdown",
|
361 |
+
"metadata": {
|
362 |
+
"id": "0YnhY66zOShI"
|
363 |
+
},
|
364 |
+
"source": [
|
365 |
+
"### Camera registration with COLMAP."
|
366 |
+
]
|
367 |
+
},
|
368 |
+
{
|
369 |
+
"cell_type": "code",
|
370 |
+
"execution_count": null,
|
371 |
+
"metadata": {
|
372 |
+
"colab": {
|
373 |
+
"base_uri": "https://localhost:8080/"
|
374 |
+
},
|
375 |
+
"id": "T2xqbzxILqZO",
|
376 |
+
"outputId": "8194b820-d57f-4517-c28b-ede47fa7195c"
|
377 |
+
},
|
378 |
+
"outputs": [],
|
379 |
+
"source": [
|
380 |
+
"# @title Extract features.\n",
|
381 |
+
"# @markdown Computes SIFT features and saves them to the COLMAP DB.\n",
|
382 |
+
"share_intrinsics = True # @param {type: 'boolean'}\n",
|
383 |
+
"assume_upright_cameras = True # @param {type: 'boolean'}\n",
|
384 |
+
"\n",
|
385 |
+
"# @markdown This sets the scale at which we will run COLMAP. A scale of 1 will be more accurate but will be slow.\n",
|
386 |
+
"colmap_image_scale = 4 # @param {type: 'number'}\n",
|
387 |
+
"colmap_rgb_dir = rgb_dir / f'{colmap_image_scale}x'\n",
|
388 |
+
"\n",
|
389 |
+
"# @markdown Check this if you want to re-process SfM.\n",
|
390 |
+
"overwrite = False # @param {type: 'boolean'}\n",
|
391 |
+
"\n",
|
392 |
+
"if overwrite and colmap_db_path.exists():\n",
|
393 |
+
" colmap_db_path.unlink()\n",
|
394 |
+
"#added code by yizheng\n",
|
395 |
+
"#colmap_db_path.parent.mkdir(parents=True)\n",
|
396 |
+
"\n",
|
397 |
+
"print(colmap_db_path.parent.exists())\n",
|
398 |
+
"#end of added code\n",
|
399 |
+
"\n",
|
400 |
+
"!colmap feature_extractor \\\n",
|
401 |
+
"--SiftExtraction.use_gpu 0 \\\n",
|
402 |
+
"--SiftExtraction.upright {int(assume_upright_cameras)} \\\n",
|
403 |
+
"--ImageReader.camera_model OPENCV \\\n",
|
404 |
+
"--ImageReader.single_camera {int(share_intrinsics)} \\\n",
|
405 |
+
"--database_path \"{str(colmap_db_path)}\" \\\n",
|
406 |
+
"--image_path \"{str(colmap_rgb_dir)}\""
|
407 |
+
]
|
408 |
+
},
|
409 |
+
{
|
410 |
+
"cell_type": "code",
|
411 |
+
"execution_count": null,
|
412 |
+
"metadata": {
|
413 |
+
"colab": {
|
414 |
+
"base_uri": "https://localhost:8080/"
|
415 |
+
},
|
416 |
+
"id": "V0YDFELH-hBh",
|
417 |
+
"outputId": "3b1e60cd-ea11-471f-8f0e-f93a9d3d308a"
|
418 |
+
},
|
419 |
+
"outputs": [],
|
420 |
+
"source": [
|
421 |
+
"#colmap_db_path.parent.mkdir(parents=True)\n",
|
422 |
+
"\n",
|
423 |
+
"print(colmap_db_path.parent.exists())"
|
424 |
+
]
|
425 |
+
},
|
426 |
+
{
|
427 |
+
"cell_type": "code",
|
428 |
+
"execution_count": null,
|
429 |
+
"metadata": {
|
430 |
+
"cellView": "form",
|
431 |
+
"colab": {
|
432 |
+
"base_uri": "https://localhost:8080/"
|
433 |
+
},
|
434 |
+
"id": "7f_n95abLqw6",
|
435 |
+
"outputId": "f750d404-6afb-492a-a638-c42c278cc069"
|
436 |
+
},
|
437 |
+
"outputs": [],
|
438 |
+
"source": [
|
439 |
+
"# @title Match features.\n",
|
440 |
+
"# @markdown Match the SIFT features between images. Use `exhaustive` if you only have a few images and use `vocab_tree` if you have a lot of images.\n",
|
441 |
+
"\n",
|
442 |
+
"match_method = 'vocab_tree' # @param [\"exhaustive\", \"vocab_tree\"]\n",
|
443 |
+
"\n",
|
444 |
+
"if match_method == 'exhaustive':\n",
|
445 |
+
" !colmap exhaustive_matcher \\\n",
|
446 |
+
" --SiftMatching.use_gpu 0 \\\n",
|
447 |
+
" --database_path \"{str(colmap_db_path)}\"\n",
|
448 |
+
"else:\n",
|
449 |
+
" # Use this if you have lots of frames.\n",
|
450 |
+
" !wget https://demuc.de/colmap/vocab_tree_flickr100K_words32K.bin\n",
|
451 |
+
" !colmap vocab_tree_matcher \\\n",
|
452 |
+
" --VocabTreeMatching.vocab_tree_path vocab_tree_flickr100K_words32K.bin \\\n",
|
453 |
+
" --SiftMatching.use_gpu 0 \\\n",
|
454 |
+
" --database_path \"{str(colmap_db_path)}\""
|
455 |
+
]
|
456 |
+
},
|
457 |
+
{
|
458 |
+
"cell_type": "code",
|
459 |
+
"execution_count": null,
|
460 |
+
"metadata": {
|
461 |
+
"colab": {
|
462 |
+
"base_uri": "https://localhost:8080/"
|
463 |
+
},
|
464 |
+
"id": "aR52ZlXJOAn3",
|
465 |
+
"outputId": "8a593560-07a0-4e0a-b760-f6cf2a3176bf"
|
466 |
+
},
|
467 |
+
"outputs": [],
|
468 |
+
"source": [
|
469 |
+
"# @title Reconstruction.\n",
|
470 |
+
"# @markdown Run structure-from-motion to compute camera parameters.\n",
|
471 |
+
"\n",
|
472 |
+
"refine_principal_point = True #@param {type:\"boolean\"}\n",
|
473 |
+
"min_num_matches = 32# @param {type: 'number'}\n",
|
474 |
+
"filter_max_reproj_error = 2 # @param {type: 'number'}\n",
|
475 |
+
"tri_complete_max_reproj_error = 2 # @param {type: 'number'}\n",
|
476 |
+
"#added code\n",
|
477 |
+
"colmap_out_path.mkdir(parents=True, exist_ok=True)\n",
|
478 |
+
"\n",
|
479 |
+
"#end\n",
|
480 |
+
"!colmap mapper \\\n",
|
481 |
+
" --Mapper.ba_refine_principal_point {int(refine_principal_point)} \\\n",
|
482 |
+
" --Mapper.filter_max_reproj_error $filter_max_reproj_error \\\n",
|
483 |
+
" --Mapper.tri_complete_max_reproj_error $tri_complete_max_reproj_error \\\n",
|
484 |
+
" --Mapper.min_num_matches $min_num_matches \\\n",
|
485 |
+
" --database_path \"{str(colmap_db_path)}\" \\\n",
|
486 |
+
" --image_path \"{str(colmap_rgb_dir)}\" \\\n",
|
487 |
+
" --output_path \"{str(colmap_out_path)}\""
|
488 |
+
]
|
489 |
+
},
|
490 |
+
{
|
491 |
+
"cell_type": "code",
|
492 |
+
"execution_count": null,
|
493 |
+
"metadata": {
|
494 |
+
"id": "vZtg9tmIC2xc"
|
495 |
+
},
|
496 |
+
"outputs": [],
|
497 |
+
"source": [
|
498 |
+
"#!colmap mapper --help"
|
499 |
+
]
|
500 |
+
},
|
501 |
+
{
|
502 |
+
"cell_type": "code",
|
503 |
+
"execution_count": null,
|
504 |
+
"metadata": {
|
505 |
+
"colab": {
|
506 |
+
"base_uri": "https://localhost:8080/"
|
507 |
+
},
|
508 |
+
"id": "1ckBrtc9O4s4",
|
509 |
+
"outputId": "75f269ca-4f6d-4992-b6c1-9d0315cfd900"
|
510 |
+
},
|
511 |
+
"outputs": [],
|
512 |
+
"source": [
|
513 |
+
"# @title Verify that SfM worked.\n",
|
514 |
+
"\n",
|
515 |
+
"if not colmap_db_path.exists():\n",
|
516 |
+
" raise RuntimeError(f'The COLMAP DB does not exist, did you run the reconstruction?')\n",
|
517 |
+
"elif not (colmap_dir / 'sparse/0/cameras.bin').exists():\n",
|
518 |
+
" raise RuntimeError(\"\"\"\n",
|
519 |
+
"SfM seems to have failed. Try some of the following options:\n",
|
520 |
+
" - Increase the FPS when flattenting to images. There should be at least 50-ish images.\n",
|
521 |
+
" - Decrease `min_num_matches`.\n",
|
522 |
+
" - If you images aren't upright, uncheck `assume_upright_cameras`.\n",
|
523 |
+
"\"\"\")\n",
|
524 |
+
"else:\n",
|
525 |
+
" print(\"Everything looks good!\")"
|
526 |
+
]
|
527 |
+
},
|
528 |
+
{
|
529 |
+
"cell_type": "markdown",
|
530 |
+
"metadata": {
|
531 |
+
"id": "DqpRdhDBdRjT"
|
532 |
+
},
|
533 |
+
"source": [
|
534 |
+
"## Parse Data."
|
535 |
+
]
|
536 |
+
},
|
537 |
+
{
|
538 |
+
"cell_type": "code",
|
539 |
+
"execution_count": null,
|
540 |
+
"metadata": {
|
541 |
+
"id": "LB_2BCY3ELmi"
|
542 |
+
},
|
543 |
+
"outputs": [],
|
544 |
+
"source": [
|
545 |
+
"#!pip install pycolmap --upgrade"
|
546 |
+
]
|
547 |
+
},
|
548 |
+
{
|
549 |
+
"cell_type": "code",
|
550 |
+
"execution_count": null,
|
551 |
+
"metadata": {
|
552 |
+
"cellView": "form",
|
553 |
+
"id": "5LuJwJawdXKw"
|
554 |
+
},
|
555 |
+
"outputs": [],
|
556 |
+
"source": [
|
557 |
+
"# @title Define Scene Manager.\n",
|
558 |
+
"from absl import logging\n",
|
559 |
+
"from typing import Dict\n",
|
560 |
+
"import numpy as np\n",
|
561 |
+
"from nerfies.camera import Camera\n",
|
562 |
+
"import pycolmap\n",
|
563 |
+
"from pycolmap import Quaternion\n",
|
564 |
+
"\n",
|
565 |
+
"\n",
|
566 |
+
"def convert_colmap_camera(colmap_camera, colmap_image):\n",
|
567 |
+
" \"\"\"Converts a pycolmap `image` to an SFM camera.\"\"\"\n",
|
568 |
+
" camera_rotation = colmap_image.R()\n",
|
569 |
+
" camera_position = -(colmap_image.t @ camera_rotation)\n",
|
570 |
+
" new_camera = Camera(\n",
|
571 |
+
" orientation=camera_rotation,\n",
|
572 |
+
" position=camera_position,\n",
|
573 |
+
" focal_length=colmap_camera.fx,\n",
|
574 |
+
" pixel_aspect_ratio=colmap_camera.fx / colmap_camera.fx,\n",
|
575 |
+
" principal_point=np.array([colmap_camera.cx, colmap_camera.cy]),\n",
|
576 |
+
" radial_distortion=np.array([colmap_camera.k1, colmap_camera.k2, 0.0]),\n",
|
577 |
+
" tangential_distortion=np.array([colmap_camera.p1, colmap_camera.p2]),\n",
|
578 |
+
" skew=0.0,\n",
|
579 |
+
" image_size=np.array([colmap_camera.width, colmap_camera.height])\n",
|
580 |
+
" )\n",
|
581 |
+
" return new_camera\n",
|
582 |
+
"\n",
|
583 |
+
"\n",
|
584 |
+
"def filter_outlier_points(points, inner_percentile):\n",
|
585 |
+
" \"\"\"Filters outlier points.\"\"\"\n",
|
586 |
+
" outer = 1.0 - inner_percentile\n",
|
587 |
+
" lower = outer / 2.0\n",
|
588 |
+
" upper = 1.0 - lower\n",
|
589 |
+
" centers_min = np.quantile(points, lower, axis=0)\n",
|
590 |
+
" centers_max = np.quantile(points, upper, axis=0)\n",
|
591 |
+
" result = points.copy()\n",
|
592 |
+
"\n",
|
593 |
+
" too_near = np.any(result < centers_min[None, :], axis=1)\n",
|
594 |
+
" too_far = np.any(result > centers_max[None, :], axis=1)\n",
|
595 |
+
"\n",
|
596 |
+
" return result[~(too_near | too_far)]\n",
|
597 |
+
"\n",
|
598 |
+
"\n",
|
599 |
+
"def average_reprojection_errors(points, pixels, cameras):\n",
|
600 |
+
" \"\"\"Computes the average reprojection errors of the points.\"\"\"\n",
|
601 |
+
" cam_errors = []\n",
|
602 |
+
" for i, camera in enumerate(cameras):\n",
|
603 |
+
" cam_error = reprojection_error(points, pixels[:, i], camera)\n",
|
604 |
+
" cam_errors.append(cam_error)\n",
|
605 |
+
" cam_error = np.stack(cam_errors)\n",
|
606 |
+
"\n",
|
607 |
+
" return cam_error.mean(axis=1)\n",
|
608 |
+
"\n",
|
609 |
+
"\n",
|
610 |
+
"def _get_camera_translation(camera):\n",
|
611 |
+
" \"\"\"Computes the extrinsic translation of the camera.\"\"\"\n",
|
612 |
+
" rot_mat = camera.orientation\n",
|
613 |
+
" return -camera.position.dot(rot_mat.T)\n",
|
614 |
+
"\n",
|
615 |
+
"\n",
|
616 |
+
"def _transform_camera(camera, transform_mat):\n",
|
617 |
+
" \"\"\"Transforms the camera using the given transformation matrix.\"\"\"\n",
|
618 |
+
" # The determinant gives us volumetric scaling factor.\n",
|
619 |
+
" # Take the cube root to get the linear scaling factor.\n",
|
620 |
+
" scale = np.cbrt(linalg.det(transform_mat[:, :3]))\n",
|
621 |
+
" quat_transform = ~Quaternion.FromR(transform_mat[:, :3] / scale)\n",
|
622 |
+
"\n",
|
623 |
+
" translation = _get_camera_translation(camera)\n",
|
624 |
+
" rot_quat = Quaternion.FromR(camera.orientation)\n",
|
625 |
+
" rot_quat *= quat_transform\n",
|
626 |
+
" translation = scale * translation - rot_quat.ToR().dot(transform_mat[:, 3])\n",
|
627 |
+
" new_transform = np.eye(4)\n",
|
628 |
+
" new_transform[:3, :3] = rot_quat.ToR()\n",
|
629 |
+
" new_transform[:3, 3] = translation\n",
|
630 |
+
"\n",
|
631 |
+
" rotation = rot_quat.ToR()\n",
|
632 |
+
" new_camera = camera.copy()\n",
|
633 |
+
" new_camera.orientation = rotation\n",
|
634 |
+
" new_camera.position = -(translation @ rotation)\n",
|
635 |
+
" return new_camera\n",
|
636 |
+
"\n",
|
637 |
+
"\n",
|
638 |
+
"def _pycolmap_to_sfm_cameras(manager: pycolmap.SceneManager) -> Dict[int, Camera]:\n",
|
639 |
+
" \"\"\"Creates SFM cameras.\"\"\"\n",
|
640 |
+
" # Use the original filenames as indices.\n",
|
641 |
+
" # This mapping necessary since COLMAP uses arbitrary numbers for the\n",
|
642 |
+
" # image_id.\n",
|
643 |
+
" image_id_to_colmap_id = {\n",
|
644 |
+
" image.name.split('.')[0]: image_id\n",
|
645 |
+
" for image_id, image in manager.images.items()\n",
|
646 |
+
" }\n",
|
647 |
+
"\n",
|
648 |
+
" sfm_cameras = {}\n",
|
649 |
+
" for image_id in image_id_to_colmap_id:\n",
|
650 |
+
" colmap_id = image_id_to_colmap_id[image_id]\n",
|
651 |
+
" image = manager.images[colmap_id]\n",
|
652 |
+
" camera = manager.cameras[image.camera_id]\n",
|
653 |
+
" sfm_cameras[image_id] = convert_colmap_camera(camera, image)\n",
|
654 |
+
"\n",
|
655 |
+
" return sfm_cameras\n",
|
656 |
+
"\n",
|
657 |
+
"\n",
|
658 |
+
"class SceneManager:\n",
|
659 |
+
" \"\"\"A thin wrapper around pycolmap.\"\"\"\n",
|
660 |
+
"\n",
|
661 |
+
" @classmethod\n",
|
662 |
+
" def from_pycolmap(cls, colmap_path, image_path, min_track_length=10):\n",
|
663 |
+
" \"\"\"Create a scene manager using pycolmap.\"\"\"\n",
|
664 |
+
" manager = pycolmap.SceneManager(str(colmap_path))\n",
|
665 |
+
" manager.load_cameras()\n",
|
666 |
+
" manager.load_images()\n",
|
667 |
+
" manager.load_points3D()\n",
|
668 |
+
" manager.filter_points3D(min_track_len=min_track_length)\n",
|
669 |
+
" sfm_cameras = _pycolmap_to_sfm_cameras(manager)\n",
|
670 |
+
" return cls(sfm_cameras, manager.get_filtered_points3D(), image_path)\n",
|
671 |
+
"\n",
|
672 |
+
" def __init__(self, cameras, points, image_path):\n",
|
673 |
+
" self.image_path = Path(image_path)\n",
|
674 |
+
" self.camera_dict = cameras\n",
|
675 |
+
" self.points = points\n",
|
676 |
+
"\n",
|
677 |
+
" logging.info('Created scene manager with %d cameras', len(self.camera_dict))\n",
|
678 |
+
"\n",
|
679 |
+
" def __len__(self):\n",
|
680 |
+
" return len(self.camera_dict)\n",
|
681 |
+
"\n",
|
682 |
+
" @property\n",
|
683 |
+
" def image_ids(self):\n",
|
684 |
+
" return sorted(self.camera_dict.keys())\n",
|
685 |
+
"\n",
|
686 |
+
" @property\n",
|
687 |
+
" def camera_list(self):\n",
|
688 |
+
" return [self.camera_dict[i] for i in self.image_ids]\n",
|
689 |
+
"\n",
|
690 |
+
" @property\n",
|
691 |
+
" def camera_positions(self):\n",
|
692 |
+
" \"\"\"Returns an array of camera positions.\"\"\"\n",
|
693 |
+
" return np.stack([camera.position for camera in self.camera_list])\n",
|
694 |
+
"\n",
|
695 |
+
" def load_image(self, image_id):\n",
|
696 |
+
" \"\"\"Loads the image with the specified image_id.\"\"\"\n",
|
697 |
+
" path = self.image_path / f'{image_id}.png'\n",
|
698 |
+
" with path.open('rb') as f:\n",
|
699 |
+
" return imageio.imread(f)\n",
|
700 |
+
"\n",
|
701 |
+
" def triangulate_pixels(self, pixels):\n",
|
702 |
+
" \"\"\"Triangulates the pixels across all cameras in the scene.\n",
|
703 |
+
"\n",
|
704 |
+
" Args:\n",
|
705 |
+
" pixels: the pixels to triangulate. There must be the same number of pixels\n",
|
706 |
+
" as cameras in the scene.\n",
|
707 |
+
"\n",
|
708 |
+
" Returns:\n",
|
709 |
+
" The 3D points triangulated from the pixels.\n",
|
710 |
+
" \"\"\"\n",
|
711 |
+
" if pixels.shape != (len(self), 2):\n",
|
712 |
+
" raise ValueError(\n",
|
713 |
+
" f'The number of pixels ({len(pixels)}) must be equal to the number '\n",
|
714 |
+
" f'of cameras ({len(self)}).')\n",
|
715 |
+
"\n",
|
716 |
+
" return triangulate_pixels(pixels, self.camera_list)\n",
|
717 |
+
"\n",
|
718 |
+
" def change_basis(self, axes, center):\n",
|
719 |
+
" \"\"\"Change the basis of the scene.\n",
|
720 |
+
"\n",
|
721 |
+
" Args:\n",
|
722 |
+
" axes: the axes of the new coordinate frame.\n",
|
723 |
+
" center: the center of the new coordinate frame.\n",
|
724 |
+
"\n",
|
725 |
+
" Returns:\n",
|
726 |
+
" A new SceneManager with transformed points and cameras.\n",
|
727 |
+
" \"\"\"\n",
|
728 |
+
" transform_mat = np.zeros((3, 4))\n",
|
729 |
+
" transform_mat[:3, :3] = axes.T\n",
|
730 |
+
" transform_mat[:, 3] = -(center @ axes)\n",
|
731 |
+
" return self.transform(transform_mat)\n",
|
732 |
+
"\n",
|
733 |
+
" def transform(self, transform_mat):\n",
|
734 |
+
" \"\"\"Transform the scene using a transformation matrix.\n",
|
735 |
+
"\n",
|
736 |
+
" Args:\n",
|
737 |
+
" transform_mat: a 3x4 transformation matrix representation a\n",
|
738 |
+
" transformation.\n",
|
739 |
+
"\n",
|
740 |
+
" Returns:\n",
|
741 |
+
" A new SceneManager with transformed points and cameras.\n",
|
742 |
+
" \"\"\"\n",
|
743 |
+
" if transform_mat.shape != (3, 4):\n",
|
744 |
+
" raise ValueError('transform_mat should be a 3x4 transformation matrix.')\n",
|
745 |
+
"\n",
|
746 |
+
" points = None\n",
|
747 |
+
" if self.points is not None:\n",
|
748 |
+
" points = self.points.copy()\n",
|
749 |
+
" points = points @ transform_mat[:, :3].T + transform_mat[:, 3]\n",
|
750 |
+
"\n",
|
751 |
+
" new_cameras = {}\n",
|
752 |
+
" for image_id, camera in self.camera_dict.items():\n",
|
753 |
+
" new_cameras[image_id] = _transform_camera(camera, transform_mat)\n",
|
754 |
+
"\n",
|
755 |
+
" return SceneManager(new_cameras, points, self.image_path)\n",
|
756 |
+
"\n",
|
757 |
+
" def filter_images(self, image_ids):\n",
|
758 |
+
" num_filtered = 0\n",
|
759 |
+
" for image_id in image_ids:\n",
|
760 |
+
" if self.camera_dict.pop(image_id, None) is not None:\n",
|
761 |
+
" num_filtered += 1\n",
|
762 |
+
"\n",
|
763 |
+
" return num_filtered\n"
|
764 |
+
]
|
765 |
+
},
|
766 |
+
{
|
767 |
+
"cell_type": "code",
|
768 |
+
"execution_count": null,
|
769 |
+
"metadata": {
|
770 |
+
"colab": {
|
771 |
+
"base_uri": "https://localhost:8080/",
|
772 |
+
"height": 560
|
773 |
+
},
|
774 |
+
"id": "HdAegiHVWdY9",
|
775 |
+
"outputId": "17e8c4d6-4809-4b70-ce08-d1ac214a93ce"
|
776 |
+
},
|
777 |
+
"outputs": [],
|
778 |
+
"source": [
|
779 |
+
"# @title Load COLMAP scene.\n",
|
780 |
+
"import plotly.graph_objs as go\n",
|
781 |
+
"\n",
|
782 |
+
"scene_manager = SceneManager.from_pycolmap(\n",
|
783 |
+
" colmap_dir / 'sparse/0', \n",
|
784 |
+
" rgb_dir / f'1x', \n",
|
785 |
+
" min_track_length=5)\n",
|
786 |
+
"\n",
|
787 |
+
"if colmap_image_scale > 1:\n",
|
788 |
+
" print(f'Scaling COLMAP cameras back to 1x from {colmap_image_scale}x.')\n",
|
789 |
+
" for item_id in scene_manager.image_ids:\n",
|
790 |
+
" camera = scene_manager.camera_dict[item_id]\n",
|
791 |
+
" scene_manager.camera_dict[item_id] = camera.scale(colmap_image_scale)\n",
|
792 |
+
"\n",
|
793 |
+
"\n",
|
794 |
+
"fig = go.Figure()\n",
|
795 |
+
"fig.add_trace(go.Scatter3d(\n",
|
796 |
+
" x=scene_manager.points[:, 0],\n",
|
797 |
+
" y=scene_manager.points[:, 1],\n",
|
798 |
+
" z=scene_manager.points[:, 2],\n",
|
799 |
+
" mode='markers',\n",
|
800 |
+
" marker=dict(size=2),\n",
|
801 |
+
"))\n",
|
802 |
+
"fig.add_trace(go.Scatter3d(\n",
|
803 |
+
" x=scene_manager.camera_positions[:, 0],\n",
|
804 |
+
" y=scene_manager.camera_positions[:, 1],\n",
|
805 |
+
" z=scene_manager.camera_positions[:, 2],\n",
|
806 |
+
" mode='markers',\n",
|
807 |
+
" marker=dict(size=2),\n",
|
808 |
+
"))\n",
|
809 |
+
"fig.update_layout(scene_dragmode='orbit')\n",
|
810 |
+
"fig.show()"
|
811 |
+
]
|
812 |
+
},
|
813 |
+
{
|
814 |
+
"cell_type": "code",
|
815 |
+
"execution_count": null,
|
816 |
+
"metadata": {
|
817 |
+
"cellView": "form",
|
818 |
+
"colab": {
|
819 |
+
"base_uri": "https://localhost:8080/",
|
820 |
+
"height": 198
|
821 |
+
},
|
822 |
+
"id": "e92Kcuoa5i9h",
|
823 |
+
"outputId": "f00d7fca-c267-4c08-a862-61636b3adde1"
|
824 |
+
},
|
825 |
+
"outputs": [],
|
826 |
+
"source": [
|
827 |
+
"# @title Filter blurry frames.\n",
|
828 |
+
"from matplotlib import pyplot as plt\n",
|
829 |
+
"import numpy as np\n",
|
830 |
+
"import cv2\n",
|
831 |
+
"\n",
|
832 |
+
"def variance_of_laplacian(image: np.ndarray) -> np.ndarray:\n",
|
833 |
+
" \"\"\"Compute the variance of the Laplacian which measure the focus.\"\"\"\n",
|
834 |
+
" gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n",
|
835 |
+
" return cv2.Laplacian(gray, cv2.CV_64F).var()\n",
|
836 |
+
"\n",
|
837 |
+
"\n",
|
838 |
+
"blur_filter_perc = 95.0 # @param {type: 'number'}\n",
|
839 |
+
"if blur_filter_perc > 0.0:\n",
|
840 |
+
" image_paths = sorted(rgb_dir.iterdir())\n",
|
841 |
+
" print('Loading images.')\n",
|
842 |
+
" images = list(map(scene_manager.load_image, scene_manager.image_ids))\n",
|
843 |
+
" print('Computing blur scores.')\n",
|
844 |
+
" blur_scores = np.array([variance_of_laplacian(im) for im in images])\n",
|
845 |
+
" blur_thres = np.percentile(blur_scores, blur_filter_perc)\n",
|
846 |
+
" blur_filter_inds = np.where(blur_scores >= blur_thres)[0]\n",
|
847 |
+
" blur_filter_scores = [blur_scores[i] for i in blur_filter_inds]\n",
|
848 |
+
" blur_filter_inds = blur_filter_inds[np.argsort(blur_filter_scores)]\n",
|
849 |
+
" blur_filter_scores = np.sort(blur_filter_scores)\n",
|
850 |
+
" blur_filter_image_ids = [scene_manager.image_ids[i] for i in blur_filter_inds]\n",
|
851 |
+
" print(f'Filtering {len(blur_filter_image_ids)} IDs: {blur_filter_image_ids}')\n",
|
852 |
+
" num_filtered = scene_manager.filter_images(blur_filter_image_ids)\n",
|
853 |
+
" print(f'Filtered {num_filtered} images')\n",
|
854 |
+
"\n",
|
855 |
+
" plt.figure(figsize=(15, 10))\n",
|
856 |
+
" plt.subplot(121)\n",
|
857 |
+
" plt.title('Least blurry')\n",
|
858 |
+
" plt.imshow(images[blur_filter_inds[-1]])\n",
|
859 |
+
" plt.subplot(122)\n",
|
860 |
+
" plt.title('Most blurry')\n",
|
861 |
+
" plt.imshow(images[blur_filter_inds[0]])"
|
862 |
+
]
|
863 |
+
},
|
864 |
+
{
|
865 |
+
"cell_type": "markdown",
|
866 |
+
"metadata": {
|
867 |
+
"id": "xtSV7C5y3Yuv"
|
868 |
+
},
|
869 |
+
"source": [
|
870 |
+
"### Face Processing.\n",
|
871 |
+
"\n",
|
872 |
+
"This section runs the optional step of computing facial landmarks for the purpose of test camera generation."
|
873 |
+
]
|
874 |
+
},
|
875 |
+
{
|
876 |
+
"cell_type": "code",
|
877 |
+
"execution_count": null,
|
878 |
+
"metadata": {
|
879 |
+
"cellView": "form",
|
880 |
+
"id": "lDOphUXt5AQ-"
|
881 |
+
},
|
882 |
+
"outputs": [],
|
883 |
+
"source": [
|
884 |
+
"import jax\n",
|
885 |
+
"from jax import numpy as jnp\n",
|
886 |
+
"from tensorflow_graphics.geometry.representation.ray import triangulate as ray_triangulate\n",
|
887 |
+
"\n",
|
888 |
+
"use_face = False # @param {type: 'boolean'}"
|
889 |
+
]
|
890 |
+
},
|
891 |
+
{
|
892 |
+
"cell_type": "code",
|
893 |
+
"execution_count": null,
|
894 |
+
"metadata": {
|
895 |
+
"cellView": "form",
|
896 |
+
"id": "hVjyA5sW3AVZ"
|
897 |
+
},
|
898 |
+
"outputs": [],
|
899 |
+
"source": [
|
900 |
+
"# @title Compute 2D landmarks.\n",
|
901 |
+
"\n",
|
902 |
+
"import imageio\n",
|
903 |
+
"import mediapipe as mp\n",
|
904 |
+
"from PIL import Image\n",
|
905 |
+
"\n",
|
906 |
+
"if use_face:\n",
|
907 |
+
" mp_face_mesh = mp.solutions.face_mesh\n",
|
908 |
+
" mp_drawing = mp.solutions.drawing_utils \n",
|
909 |
+
" drawing_spec = mp_drawing.DrawingSpec(thickness=1, circle_radius=1)\n",
|
910 |
+
" \n",
|
911 |
+
" # Initialize MediaPipe Face Mesh.\n",
|
912 |
+
" face_mesh = mp_face_mesh.FaceMesh(\n",
|
913 |
+
" static_image_mode=True,\n",
|
914 |
+
" max_num_faces=2,\n",
|
915 |
+
" min_detection_confidence=0.5)\n",
|
916 |
+
" \n",
|
917 |
+
" \n",
|
918 |
+
" def compute_landmarks(image):\n",
|
919 |
+
" height, width = image.shape[:2]\n",
|
920 |
+
" results = face_mesh.process(image)\n",
|
921 |
+
" if results.multi_face_landmarks is None:\n",
|
922 |
+
" return None\n",
|
923 |
+
" # Choose first face found.\n",
|
924 |
+
" landmarks = results.multi_face_landmarks[0].landmark\n",
|
925 |
+
" landmarks = np.array(\n",
|
926 |
+
" [(o.x * width, o.y * height) for o in landmarks],\n",
|
927 |
+
" dtype=np.uint32)\n",
|
928 |
+
" return landmarks\n",
|
929 |
+
"\n",
|
930 |
+
" landmarks_dict = {}\n",
|
931 |
+
" for item_id in scene_manager.image_ids:\n",
|
932 |
+
" image = scene_manager.load_image(item_id)\n",
|
933 |
+
" landmarks = compute_landmarks(image)\n",
|
934 |
+
" if landmarks is not None:\n",
|
935 |
+
" landmarks_dict[item_id] = landmarks\n",
|
936 |
+
" \n",
|
937 |
+
" landmark_item_ids = sorted(landmarks_dict)\n",
|
938 |
+
" landmarks_pixels = np.array([landmarks_dict[i] for i in landmark_item_ids])\n",
|
939 |
+
" landmarks_cameras = [scene_manager.camera_dict[i] for i in landmark_item_ids]\n",
|
940 |
+
" \n",
|
941 |
+
" from matplotlib import pyplot as plt\n",
|
942 |
+
" plt.imshow(image)\n",
|
943 |
+
" plt.scatter(x=landmarks[..., 0], y=landmarks[..., 1], s=1);"
|
944 |
+
]
|
945 |
+
},
|
946 |
+
{
|
947 |
+
"cell_type": "code",
|
948 |
+
"execution_count": null,
|
949 |
+
"metadata": {
|
950 |
+
"cellView": "form",
|
951 |
+
"id": "axRj1ItALAuC"
|
952 |
+
},
|
953 |
+
"outputs": [],
|
954 |
+
"source": [
|
955 |
+
"# @title Triangulate landmarks in 3D.\n",
|
956 |
+
"\n",
|
957 |
+
"if use_face:\n",
|
958 |
+
" def compute_camera_rays(points, camera):\n",
|
959 |
+
" origins = np.broadcast_to(camera.position[None, :], (points.shape[0], 3))\n",
|
960 |
+
" directions = camera.pixels_to_rays(points.astype(jnp.float32))\n",
|
961 |
+
" endpoints = origins + directions\n",
|
962 |
+
" return origins, endpoints\n",
|
963 |
+
" \n",
|
964 |
+
" \n",
|
965 |
+
" def triangulate_landmarks(landmarks, cameras):\n",
|
966 |
+
" all_origins = []\n",
|
967 |
+
" all_endpoints = []\n",
|
968 |
+
" nan_inds = []\n",
|
969 |
+
" for i, (camera_landmarks, camera) in enumerate(zip(landmarks, cameras)):\n",
|
970 |
+
" origins, endpoints = compute_camera_rays(camera_landmarks, camera)\n",
|
971 |
+
" if np.isnan(origins).sum() > 0.0 or np.isnan(endpoints).sum() > 0.0:\n",
|
972 |
+
" continue\n",
|
973 |
+
" all_origins.append(origins)\n",
|
974 |
+
" all_endpoints.append(endpoints)\n",
|
975 |
+
" all_origins = np.stack(all_origins, axis=-2).astype(np.float32)\n",
|
976 |
+
" all_endpoints = np.stack(all_endpoints, axis=-2).astype(np.float32)\n",
|
977 |
+
" weights = np.ones(all_origins.shape[:2], dtype=np.float32)\n",
|
978 |
+
" points = np.array(ray_triangulate(all_origins, all_endpoints, weights))\n",
|
979 |
+
" \n",
|
980 |
+
" return points\n",
|
981 |
+
" \n",
|
982 |
+
"\n",
|
983 |
+
" landmark_points = triangulate_landmarks(landmarks_pixels, landmarks_cameras)\n",
|
984 |
+
"else:\n",
|
985 |
+
" landmark_points = None"
|
986 |
+
]
|
987 |
+
},
|
988 |
+
{
|
989 |
+
"cell_type": "code",
|
990 |
+
"execution_count": null,
|
991 |
+
"metadata": {
|
992 |
+
"cellView": "form",
|
993 |
+
"id": "gRU-bJ8NYzR_"
|
994 |
+
},
|
995 |
+
"outputs": [],
|
996 |
+
"source": [
|
997 |
+
"# @title Normalize scene based on landmarks.\n",
|
998 |
+
"from scipy import linalg\n",
|
999 |
+
"\n",
|
1000 |
+
"DEFAULT_IPD = 0.06\n",
|
1001 |
+
"NOSE_TIP_IDX = 1\n",
|
1002 |
+
"FOREHEAD_IDX = 10\n",
|
1003 |
+
"CHIN_IDX = 152\n",
|
1004 |
+
"RIGHT_EYE_IDX = 145\n",
|
1005 |
+
"LEFT_EYE_IDX = 385\n",
|
1006 |
+
"RIGHT_TEMPLE_IDX = 162\n",
|
1007 |
+
"LEFT_TEMPLE_IDX = 389\n",
|
1008 |
+
"\n",
|
1009 |
+
"\n",
|
1010 |
+
"def _normalize(x):\n",
|
1011 |
+
" return x / linalg.norm(x)\n",
|
1012 |
+
"\n",
|
1013 |
+
"\n",
|
1014 |
+
"def fit_plane_normal(points):\n",
|
1015 |
+
" \"\"\"Fit a plane to the points and return the normal.\"\"\"\n",
|
1016 |
+
" centroid = points.sum(axis=0) / points.shape[0]\n",
|
1017 |
+
" _, _, vh = linalg.svd(points - centroid)\n",
|
1018 |
+
" return vh[2, :]\n",
|
1019 |
+
"\n",
|
1020 |
+
"\n",
|
1021 |
+
"def metric_scale_from_ipd(landmark_points, reference_ipd):\n",
|
1022 |
+
" \"\"\"Infer the scene-to-metric conversion ratio from facial landmarks.\"\"\"\n",
|
1023 |
+
" left_eye = landmark_points[LEFT_EYE_IDX]\n",
|
1024 |
+
" right_eye = landmark_points[RIGHT_EYE_IDX]\n",
|
1025 |
+
" model_ipd = linalg.norm(left_eye - right_eye)\n",
|
1026 |
+
" return reference_ipd / model_ipd\n",
|
1027 |
+
"\n",
|
1028 |
+
"\n",
|
1029 |
+
"def basis_from_landmarks(landmark_points):\n",
|
1030 |
+
" \"\"\"Computes an orthonormal basis from facial landmarks.\"\"\"\n",
|
1031 |
+
" # Estimate Z by fitting a plane\n",
|
1032 |
+
" # This works better than trusting the chin to forehead vector, especially in\n",
|
1033 |
+
" # full body captures.\n",
|
1034 |
+
" face_axis_z = _normalize(fit_plane_normal(landmark_points))\n",
|
1035 |
+
" face_axis_y = _normalize(landmark_points[FOREHEAD_IDX] -\n",
|
1036 |
+
" landmark_points[CHIN_IDX])\n",
|
1037 |
+
" face_axis_x = _normalize(landmark_points[LEFT_TEMPLE_IDX] -\n",
|
1038 |
+
" landmark_points[RIGHT_TEMPLE_IDX])\n",
|
1039 |
+
"\n",
|
1040 |
+
" # Fitted plane normal might be flipped. Check using a heuristic and flip it if\n",
|
1041 |
+
" # it's flipped.\n",
|
1042 |
+
" z_flipped = np.dot(np.cross(face_axis_x, face_axis_y), face_axis_z)\n",
|
1043 |
+
" if z_flipped < 0.0:\n",
|
1044 |
+
" face_axis_z *= -1\n",
|
1045 |
+
"\n",
|
1046 |
+
" # Ensure axes are orthogonal, with the Z axis being fixed.\n",
|
1047 |
+
" face_axis_y = np.cross(face_axis_z, face_axis_x)\n",
|
1048 |
+
" face_axis_x = np.cross(face_axis_y, face_axis_z)\n",
|
1049 |
+
"\n",
|
1050 |
+
" return np.stack([face_axis_x, face_axis_y, face_axis_z]).T\n",
|
1051 |
+
"\n",
|
1052 |
+
"\n",
|
1053 |
+
"if use_face:\n",
|
1054 |
+
" face_basis = basis_from_landmarks(landmark_points)\n",
|
1055 |
+
" new_scene_manager = scene_manager.change_basis(\n",
|
1056 |
+
" face_basis, landmark_points[NOSE_TIP_IDX])\n",
|
1057 |
+
" new_cameras = [new_scene_manager.camera_dict[i] for i in landmark_item_ids]\n",
|
1058 |
+
" new_landmark_points = triangulate_landmarks(landmarks_pixels, new_cameras)\n",
|
1059 |
+
" face_basis = basis_from_landmarks(landmark_points)\n",
|
1060 |
+
" scene_to_metric = metric_scale_from_ipd(landmark_points, DEFAULT_IPD)\n",
|
1061 |
+
" \n",
|
1062 |
+
" print(f'Computed basis: {face_basis}')\n",
|
1063 |
+
" print(f'Estimated metric scale = {scene_to_metric:.02f}')\n",
|
1064 |
+
"else:\n",
|
1065 |
+
" new_scene_manager = scene_manager"
|
1066 |
+
]
|
1067 |
+
},
|
1068 |
+
{
|
1069 |
+
"cell_type": "markdown",
|
1070 |
+
"metadata": {
|
1071 |
+
"id": "iPuR5MKk6Ubh"
|
1072 |
+
},
|
1073 |
+
"source": [
|
1074 |
+
"## Compute scene information.\n",
|
1075 |
+
"\n",
|
1076 |
+
"This section computes the scene information necessary for NeRF training."
|
1077 |
+
]
|
1078 |
+
},
|
1079 |
+
{
|
1080 |
+
"cell_type": "code",
|
1081 |
+
"execution_count": null,
|
1082 |
+
"metadata": {
|
1083 |
+
"cellView": "form",
|
1084 |
+
"colab": {
|
1085 |
+
"base_uri": "https://localhost:8080/"
|
1086 |
+
},
|
1087 |
+
"id": "klgXn8BQ8uH9",
|
1088 |
+
"outputId": "4a71e3ad-986d-4514-d080-b584543a98f2"
|
1089 |
+
},
|
1090 |
+
"outputs": [],
|
1091 |
+
"source": [
|
1092 |
+
"# @title Compute near/far planes.\n",
|
1093 |
+
"import pandas as pd\n",
|
1094 |
+
"\n",
|
1095 |
+
"\n",
|
1096 |
+
"def estimate_near_far_for_image(scene_manager, image_id):\n",
|
1097 |
+
" \"\"\"Estimate near/far plane for a single image based via point cloud.\"\"\"\n",
|
1098 |
+
" points = filter_outlier_points(scene_manager.points, 0.95)\n",
|
1099 |
+
" points = np.concatenate([\n",
|
1100 |
+
" points,\n",
|
1101 |
+
" scene_manager.camera_positions,\n",
|
1102 |
+
" ], axis=0)\n",
|
1103 |
+
" camera = scene_manager.camera_dict[image_id]\n",
|
1104 |
+
" pixels = camera.project(points)\n",
|
1105 |
+
" depths = camera.points_to_local_points(points)[..., 2]\n",
|
1106 |
+
"\n",
|
1107 |
+
" # in_frustum = camera.ArePixelsInFrustum(pixels)\n",
|
1108 |
+
" in_frustum = (\n",
|
1109 |
+
" (pixels[..., 0] >= 0.0)\n",
|
1110 |
+
" & (pixels[..., 0] <= camera.image_size_x)\n",
|
1111 |
+
" & (pixels[..., 1] >= 0.0)\n",
|
1112 |
+
" & (pixels[..., 1] <= camera.image_size_y))\n",
|
1113 |
+
" depths = depths[in_frustum]\n",
|
1114 |
+
"\n",
|
1115 |
+
" in_front_of_camera = depths > 0\n",
|
1116 |
+
" depths = depths[in_front_of_camera]\n",
|
1117 |
+
"\n",
|
1118 |
+
" near = np.quantile(depths, 0.001)\n",
|
1119 |
+
" far = np.quantile(depths, 0.999)\n",
|
1120 |
+
"\n",
|
1121 |
+
" return near, far\n",
|
1122 |
+
"\n",
|
1123 |
+
"\n",
|
1124 |
+
"def estimate_near_far(scene_manager):\n",
|
1125 |
+
" \"\"\"Estimate near/far plane for a set of randomly-chosen images.\"\"\"\n",
|
1126 |
+
" # image_ids = sorted(scene_manager.images.keys())\n",
|
1127 |
+
" image_ids = scene_manager.image_ids\n",
|
1128 |
+
" rng = np.random.RandomState(0)\n",
|
1129 |
+
" image_ids = rng.choice(\n",
|
1130 |
+
" image_ids, size=len(scene_manager.camera_list), replace=False)\n",
|
1131 |
+
" \n",
|
1132 |
+
" result = []\n",
|
1133 |
+
" for image_id in image_ids:\n",
|
1134 |
+
" near, far = estimate_near_far_for_image(scene_manager, image_id)\n",
|
1135 |
+
" result.append({'image_id': image_id, 'near': near, 'far': far})\n",
|
1136 |
+
" result = pd.DataFrame.from_records(result)\n",
|
1137 |
+
" return result\n",
|
1138 |
+
"\n",
|
1139 |
+
"\n",
|
1140 |
+
"near_far = estimate_near_far(new_scene_manager)\n",
|
1141 |
+
"print('Statistics for near/far computation:')\n",
|
1142 |
+
"print(near_far.describe())\n",
|
1143 |
+
"print()\n",
|
1144 |
+
"\n",
|
1145 |
+
"near = near_far['near'].quantile(0.001) / 0.8\n",
|
1146 |
+
"far = near_far['far'].quantile(0.999) * 1.2\n",
|
1147 |
+
"print('Selected near/far values:')\n",
|
1148 |
+
"print(f'Near = {near:.04f}')\n",
|
1149 |
+
"print(f'Far = {far:.04f}')"
|
1150 |
+
]
|
1151 |
+
},
|
1152 |
+
{
|
1153 |
+
"cell_type": "code",
|
1154 |
+
"execution_count": null,
|
1155 |
+
"metadata": {
|
1156 |
+
"cellView": "form",
|
1157 |
+
"colab": {
|
1158 |
+
"base_uri": "https://localhost:8080/"
|
1159 |
+
},
|
1160 |
+
"id": "kOgCoT62ArbD",
|
1161 |
+
"outputId": "8232f4c0-4b41-45c5-f9ab-b48151dab291"
|
1162 |
+
},
|
1163 |
+
"outputs": [],
|
1164 |
+
"source": [
|
1165 |
+
"# @title Compute scene center and scale.\n",
|
1166 |
+
"\n",
|
1167 |
+
"def get_bbox_corners(points):\n",
|
1168 |
+
" lower = points.min(axis=0)\n",
|
1169 |
+
" upper = points.max(axis=0)\n",
|
1170 |
+
" return np.stack([lower, upper])\n",
|
1171 |
+
"\n",
|
1172 |
+
"\n",
|
1173 |
+
"points = filter_outlier_points(new_scene_manager.points, 0.95)\n",
|
1174 |
+
"bbox_corners = get_bbox_corners(\n",
|
1175 |
+
" np.concatenate([points, new_scene_manager.camera_positions], axis=0))\n",
|
1176 |
+
"\n",
|
1177 |
+
"scene_center = np.mean(bbox_corners, axis=0)\n",
|
1178 |
+
"scene_scale = 1.0 / np.sqrt(np.sum((bbox_corners[1] - bbox_corners[0]) ** 2))\n",
|
1179 |
+
"\n",
|
1180 |
+
"print(f'Scene Center: {scene_center}')\n",
|
1181 |
+
"print(f'Scene Scale: {scene_scale}')\n"
|
1182 |
+
]
|
1183 |
+
},
|
1184 |
+
{
|
1185 |
+
"cell_type": "code",
|
1186 |
+
"execution_count": null,
|
1187 |
+
"metadata": {
|
1188 |
+
"cellView": "form",
|
1189 |
+
"colab": {
|
1190 |
+
"base_uri": "https://localhost:8080/",
|
1191 |
+
"height": 560
|
1192 |
+
},
|
1193 |
+
"id": "6Q1KC4xw6Til",
|
1194 |
+
"outputId": "c91cf557-dd99-4929-90c8-9c2c3cfcac73"
|
1195 |
+
},
|
1196 |
+
"outputs": [],
|
1197 |
+
"source": [
|
1198 |
+
"# @title Visualize scene.\n",
|
1199 |
+
"\n",
|
1200 |
+
"def scatter_points(points, size=2):\n",
|
1201 |
+
" return go.Scatter3d(\n",
|
1202 |
+
" x=points[:, 0],\n",
|
1203 |
+
" y=points[:, 1],\n",
|
1204 |
+
" z=points[:, 2],\n",
|
1205 |
+
" mode='markers',\n",
|
1206 |
+
" marker=dict(size=size),\n",
|
1207 |
+
" )\n",
|
1208 |
+
"\n",
|
1209 |
+
"camera = new_scene_manager.camera_list[0]\n",
|
1210 |
+
"near_points = camera.pixels_to_points(\n",
|
1211 |
+
" camera.get_pixel_centers()[::8, ::8], jnp.array(near)).reshape((-1, 3))\n",
|
1212 |
+
"far_points = camera.pixels_to_points(\n",
|
1213 |
+
" camera.get_pixel_centers()[::8, ::8], jnp.array(far)).reshape((-1, 3))\n",
|
1214 |
+
"\n",
|
1215 |
+
"data = [\n",
|
1216 |
+
" scatter_points(new_scene_manager.points),\n",
|
1217 |
+
" scatter_points(new_scene_manager.camera_positions),\n",
|
1218 |
+
" scatter_points(bbox_corners),\n",
|
1219 |
+
" scatter_points(near_points),\n",
|
1220 |
+
" scatter_points(far_points),\n",
|
1221 |
+
"]\n",
|
1222 |
+
"if use_face:\n",
|
1223 |
+
" data.append(scatter_points(new_landmark_points))\n",
|
1224 |
+
"fig = go.Figure(data=data)\n",
|
1225 |
+
"fig.update_layout(scene_dragmode='orbit')\n",
|
1226 |
+
"fig.show()"
|
1227 |
+
]
|
1228 |
+
},
|
1229 |
+
{
|
1230 |
+
"cell_type": "markdown",
|
1231 |
+
"metadata": {
|
1232 |
+
"id": "KtOTEI_Tbpt_"
|
1233 |
+
},
|
1234 |
+
"source": [
|
1235 |
+
"## Generate test cameras."
|
1236 |
+
]
|
1237 |
+
},
|
1238 |
+
{
|
1239 |
+
"cell_type": "code",
|
1240 |
+
"execution_count": null,
|
1241 |
+
"metadata": {
|
1242 |
+
"id": "WvvOLabUeJUX"
|
1243 |
+
},
|
1244 |
+
"outputs": [],
|
1245 |
+
"source": [
|
1246 |
+
"# @title Define Utilities.\n",
|
1247 |
+
"_EPSILON = 1e-5\n",
|
1248 |
+
"\n",
|
1249 |
+
"\n",
|
1250 |
+
"def points_bound(points):\n",
|
1251 |
+
" \"\"\"Computes the min and max dims of the points.\"\"\"\n",
|
1252 |
+
" min_dim = np.min(points, axis=0)\n",
|
1253 |
+
" max_dim = np.max(points, axis=0)\n",
|
1254 |
+
" return np.stack((min_dim, max_dim), axis=1)\n",
|
1255 |
+
"\n",
|
1256 |
+
"\n",
|
1257 |
+
"def points_centroid(points):\n",
|
1258 |
+
" \"\"\"Computes the centroid of the points from the bounding box.\"\"\"\n",
|
1259 |
+
" return points_bound(points).mean(axis=1)\n",
|
1260 |
+
"\n",
|
1261 |
+
"\n",
|
1262 |
+
"def points_bounding_size(points):\n",
|
1263 |
+
" \"\"\"Computes the bounding size of the points from the bounding box.\"\"\"\n",
|
1264 |
+
" bounds = points_bound(points)\n",
|
1265 |
+
" return np.linalg.norm(bounds[:, 1] - bounds[:, 0])\n",
|
1266 |
+
"\n",
|
1267 |
+
"\n",
|
1268 |
+
"def look_at(camera,\n",
|
1269 |
+
" camera_position: np.ndarray,\n",
|
1270 |
+
" look_at_position: np.ndarray,\n",
|
1271 |
+
" up_vector: np.ndarray):\n",
|
1272 |
+
" look_at_camera = camera.copy()\n",
|
1273 |
+
" optical_axis = look_at_position - camera_position\n",
|
1274 |
+
" norm = np.linalg.norm(optical_axis)\n",
|
1275 |
+
" if norm < _EPSILON:\n",
|
1276 |
+
" raise ValueError('The camera center and look at position are too close.')\n",
|
1277 |
+
" optical_axis /= norm\n",
|
1278 |
+
"\n",
|
1279 |
+
" right_vector = np.cross(optical_axis, up_vector)\n",
|
1280 |
+
" norm = np.linalg.norm(right_vector)\n",
|
1281 |
+
" if norm < _EPSILON:\n",
|
1282 |
+
" raise ValueError('The up-vector is parallel to the optical axis.')\n",
|
1283 |
+
" right_vector /= norm\n",
|
1284 |
+
"\n",
|
1285 |
+
" # The three directions here are orthogonal to each other and form a right\n",
|
1286 |
+
" # handed coordinate system.\n",
|
1287 |
+
" camera_rotation = np.identity(3)\n",
|
1288 |
+
" camera_rotation[0, :] = right_vector\n",
|
1289 |
+
" camera_rotation[1, :] = np.cross(optical_axis, right_vector)\n",
|
1290 |
+
" camera_rotation[2, :] = optical_axis\n",
|
1291 |
+
"\n",
|
1292 |
+
" look_at_camera.position = camera_position\n",
|
1293 |
+
" look_at_camera.orientation = camera_rotation\n",
|
1294 |
+
" return look_at_camera\n"
|
1295 |
+
]
|
1296 |
+
},
|
1297 |
+
{
|
1298 |
+
"cell_type": "code",
|
1299 |
+
"execution_count": null,
|
1300 |
+
"metadata": {
|
1301 |
+
"colab": {
|
1302 |
+
"base_uri": "https://localhost:8080/",
|
1303 |
+
"height": 614
|
1304 |
+
},
|
1305 |
+
"id": "e5cHTuhP9Dgp",
|
1306 |
+
"outputId": "b9792314-3e87-47f0-ad55-96d641755dc8"
|
1307 |
+
},
|
1308 |
+
"outputs": [],
|
1309 |
+
"source": [
|
1310 |
+
"# @title Generate camera trajectory.\n",
|
1311 |
+
"\n",
|
1312 |
+
"import math\n",
|
1313 |
+
"from scipy import interpolate\n",
|
1314 |
+
"from plotly.offline import iplot\n",
|
1315 |
+
"import plotly.graph_objs as go\n",
|
1316 |
+
"\n",
|
1317 |
+
"\n",
|
1318 |
+
"def compute_camera_rays(points, camera):\n",
|
1319 |
+
" origins = np.broadcast_to(camera.position[None, :], (points.shape[0], 3))\n",
|
1320 |
+
" directions = camera.pixels_to_rays(points.astype(jnp.float32))\n",
|
1321 |
+
" endpoints = origins + directions\n",
|
1322 |
+
" return origins, endpoints\n",
|
1323 |
+
"\n",
|
1324 |
+
"\n",
|
1325 |
+
"def triangulate_rays(origins, directions):\n",
|
1326 |
+
" origins = origins[np.newaxis, ...].astype('float32')\n",
|
1327 |
+
" directions = directions[np.newaxis, ...].astype('float32')\n",
|
1328 |
+
" weights = np.ones(origins.shape[:2], dtype=np.float32)\n",
|
1329 |
+
" points = np.array(ray_triangulate(origins, origins + directions, weights))\n",
|
1330 |
+
" return points.squeeze()\n",
|
1331 |
+
"\n",
|
1332 |
+
"\n",
|
1333 |
+
"ref_cameras = [c for c in new_scene_manager.camera_list]\n",
|
1334 |
+
"origins = np.array([c.position for c in ref_cameras])\n",
|
1335 |
+
"directions = np.array([c.optical_axis for c in ref_cameras])\n",
|
1336 |
+
"look_at = triangulate_rays(origins, directions)\n",
|
1337 |
+
"print('look_at', look_at)\n",
|
1338 |
+
"\n",
|
1339 |
+
"avg_position = np.mean(origins, axis=0)\n",
|
1340 |
+
"print('avg_position', avg_position)\n",
|
1341 |
+
"\n",
|
1342 |
+
"up = -np.mean([c.orientation[..., 1] for c in ref_cameras], axis=0)\n",
|
1343 |
+
"print('up', up)\n",
|
1344 |
+
"\n",
|
1345 |
+
"bounding_size = points_bounding_size(origins) / 2\n",
|
1346 |
+
"x_scale = 0.75# @param {type: 'number'}\n",
|
1347 |
+
"y_scale = 0.75 # @param {type: 'number'}\n",
|
1348 |
+
"xs = x_scale * bounding_size\n",
|
1349 |
+
"ys = y_scale * bounding_size\n",
|
1350 |
+
"radius = 0.75 # @param {type: 'number'}\n",
|
1351 |
+
"num_frames = 100 # @param {type: 'number'}\n",
|
1352 |
+
"\n",
|
1353 |
+
"\n",
|
1354 |
+
"origin = np.zeros(3)\n",
|
1355 |
+
"\n",
|
1356 |
+
"ref_camera = ref_cameras[0]\n",
|
1357 |
+
"print(ref_camera.position)\n",
|
1358 |
+
"z_offset = -0.1 * (-10)\n",
|
1359 |
+
"\n",
|
1360 |
+
"angles = np.linspace(0, 2*math.pi, num=num_frames)\n",
|
1361 |
+
"positions = []\n",
|
1362 |
+
"for angle in angles:\n",
|
1363 |
+
" x = np.cos(angle) * radius * xs\n",
|
1364 |
+
" y = np.sin(angle) * radius * ys\n",
|
1365 |
+
" # x = xs * radius * np.cos(angle) / (1 + np.sin(angle) ** 2)\n",
|
1366 |
+
" # y = ys * radius * np.sin(angle) * np.cos(angle) / (1 + np.sin(angle) ** 2)\n",
|
1367 |
+
"\n",
|
1368 |
+
" position = np.array([x, y, z_offset])\n",
|
1369 |
+
" # Make distance to reference point constant.\n",
|
1370 |
+
" position = avg_position + position\n",
|
1371 |
+
" positions.append(position)\n",
|
1372 |
+
"\n",
|
1373 |
+
"positions = np.stack(positions)\n",
|
1374 |
+
"\n",
|
1375 |
+
"orbit_cameras = []\n",
|
1376 |
+
"for position in positions:\n",
|
1377 |
+
" camera = ref_camera.look_at(position, look_at, up)\n",
|
1378 |
+
" orbit_cameras.append(camera)\n",
|
1379 |
+
"\n",
|
1380 |
+
"camera_paths = {'orbit-mild': orbit_cameras}\n",
|
1381 |
+
"\n",
|
1382 |
+
"traces = [\n",
|
1383 |
+
" scatter_points(new_scene_manager.points),\n",
|
1384 |
+
" scatter_points(new_scene_manager.camera_positions),\n",
|
1385 |
+
" scatter_points(bbox_corners),\n",
|
1386 |
+
" scatter_points(near_points),\n",
|
1387 |
+
" scatter_points(far_points),\n",
|
1388 |
+
"\n",
|
1389 |
+
" scatter_points(positions),\n",
|
1390 |
+
" scatter_points(origins),\n",
|
1391 |
+
"]\n",
|
1392 |
+
"fig = go.Figure(traces)\n",
|
1393 |
+
"fig.update_layout(scene_dragmode='orbit')\n",
|
1394 |
+
"fig.show()"
|
1395 |
+
]
|
1396 |
+
},
|
1397 |
+
{
|
1398 |
+
"cell_type": "markdown",
|
1399 |
+
"metadata": {
|
1400 |
+
"id": "UYJ6aI45IIwd"
|
1401 |
+
},
|
1402 |
+
"source": [
|
1403 |
+
"## Save data."
|
1404 |
+
]
|
1405 |
+
},
|
1406 |
+
{
|
1407 |
+
"cell_type": "code",
|
1408 |
+
"execution_count": null,
|
1409 |
+
"metadata": {
|
1410 |
+
"cellView": "form",
|
1411 |
+
"colab": {
|
1412 |
+
"base_uri": "https://localhost:8080/"
|
1413 |
+
},
|
1414 |
+
"id": "aDFYTpGB6_Gl",
|
1415 |
+
"outputId": "c20ca4ad-913a-4985-80a8-61cf182d35c9"
|
1416 |
+
},
|
1417 |
+
"outputs": [],
|
1418 |
+
"source": [
|
1419 |
+
"# @title Save scene information to `scene.json`.\n",
|
1420 |
+
"from pprint import pprint\n",
|
1421 |
+
"import json\n",
|
1422 |
+
"\n",
|
1423 |
+
"scene_json_path = root_dir / 'scene.json'\n",
|
1424 |
+
"with scene_json_path.open('w') as f:\n",
|
1425 |
+
" json.dump({\n",
|
1426 |
+
" 'scale': scene_scale,\n",
|
1427 |
+
" 'center': scene_center.tolist(),\n",
|
1428 |
+
" 'bbox': bbox_corners.tolist(),\n",
|
1429 |
+
" 'near': near * scene_scale,\n",
|
1430 |
+
" 'far': far * scene_scale,\n",
|
1431 |
+
" }, f, indent=2)\n",
|
1432 |
+
"\n",
|
1433 |
+
"print(f'Saved scene information to {scene_json_path}')"
|
1434 |
+
]
|
1435 |
+
},
|
1436 |
+
{
|
1437 |
+
"cell_type": "code",
|
1438 |
+
"execution_count": null,
|
1439 |
+
"metadata": {
|
1440 |
+
"cellView": "form",
|
1441 |
+
"colab": {
|
1442 |
+
"base_uri": "https://localhost:8080/"
|
1443 |
+
},
|
1444 |
+
"id": "k_oQ-4MTGFpz",
|
1445 |
+
"outputId": "6d4e03f2-6766-4971-e3cf-c467f84dd55a"
|
1446 |
+
},
|
1447 |
+
"outputs": [],
|
1448 |
+
"source": [
|
1449 |
+
"# @title Save dataset split to `dataset.json`.\n",
|
1450 |
+
"\n",
|
1451 |
+
"all_ids = scene_manager.image_ids\n",
|
1452 |
+
"val_ids = all_ids[::20]\n",
|
1453 |
+
"train_ids = sorted(set(all_ids) - set(val_ids))\n",
|
1454 |
+
"dataset_json = {\n",
|
1455 |
+
" 'count': len(scene_manager),\n",
|
1456 |
+
" 'num_exemplars': len(train_ids),\n",
|
1457 |
+
" 'ids': scene_manager.image_ids,\n",
|
1458 |
+
" 'train_ids': train_ids,\n",
|
1459 |
+
" 'val_ids': val_ids,\n",
|
1460 |
+
"}\n",
|
1461 |
+
"\n",
|
1462 |
+
"dataset_json_path = root_dir / 'dataset.json'\n",
|
1463 |
+
"with dataset_json_path.open('w') as f:\n",
|
1464 |
+
" json.dump(dataset_json, f, indent=2)\n",
|
1465 |
+
"\n",
|
1466 |
+
"print(f'Saved dataset information to {dataset_json_path}')"
|
1467 |
+
]
|
1468 |
+
},
|
1469 |
+
{
|
1470 |
+
"cell_type": "code",
|
1471 |
+
"execution_count": null,
|
1472 |
+
"metadata": {
|
1473 |
+
"cellView": "form",
|
1474 |
+
"colab": {
|
1475 |
+
"base_uri": "https://localhost:8080/"
|
1476 |
+
},
|
1477 |
+
"id": "3PWkPkBVGnSl",
|
1478 |
+
"outputId": "0dad5f14-1f7c-4882-f2d0-c8070efb3edf"
|
1479 |
+
},
|
1480 |
+
"outputs": [],
|
1481 |
+
"source": [
|
1482 |
+
"# @title Save metadata information to `metadata.json`.\n",
|
1483 |
+
"import bisect\n",
|
1484 |
+
"\n",
|
1485 |
+
"metadata_json = {}\n",
|
1486 |
+
"for i, image_id in enumerate(train_ids):\n",
|
1487 |
+
" metadata_json[image_id] = {\n",
|
1488 |
+
" 'warp_id': i,\n",
|
1489 |
+
" 'appearance_id': i,\n",
|
1490 |
+
" 'camera_id': 0,\n",
|
1491 |
+
" }\n",
|
1492 |
+
"for i, image_id in enumerate(val_ids):\n",
|
1493 |
+
" i = bisect.bisect_left(train_ids, image_id)\n",
|
1494 |
+
" metadata_json[image_id] = {\n",
|
1495 |
+
" 'warp_id': i,\n",
|
1496 |
+
" 'appearance_id': i,\n",
|
1497 |
+
" 'camera_id': 0,\n",
|
1498 |
+
" }\n",
|
1499 |
+
"\n",
|
1500 |
+
"metadata_json_path = root_dir / 'metadata.json'\n",
|
1501 |
+
"with metadata_json_path.open('w') as f:\n",
|
1502 |
+
" json.dump(metadata_json, f, indent=2)\n",
|
1503 |
+
"\n",
|
1504 |
+
"print(f'Saved metadata information to {metadata_json_path}')"
|
1505 |
+
]
|
1506 |
+
},
|
1507 |
+
{
|
1508 |
+
"cell_type": "code",
|
1509 |
+
"execution_count": null,
|
1510 |
+
"metadata": {
|
1511 |
+
"cellView": "form",
|
1512 |
+
"colab": {
|
1513 |
+
"base_uri": "https://localhost:8080/"
|
1514 |
+
},
|
1515 |
+
"id": "4Uxu0yKlGs3V",
|
1516 |
+
"outputId": "b4e3da57-a3a2-4b7a-f905-0f9bf5b50e8e"
|
1517 |
+
},
|
1518 |
+
"outputs": [],
|
1519 |
+
"source": [
|
1520 |
+
"# @title Save cameras.\n",
|
1521 |
+
"camera_dir = root_dir / 'camera'\n",
|
1522 |
+
"camera_dir.mkdir(exist_ok=True, parents=True)\n",
|
1523 |
+
"for item_id, camera in new_scene_manager.camera_dict.items():\n",
|
1524 |
+
" camera_path = camera_dir / f'{item_id}.json'\n",
|
1525 |
+
" print(f'Saving camera to {camera_path!s}')\n",
|
1526 |
+
" with camera_path.open('w') as f:\n",
|
1527 |
+
" json.dump(camera.to_json(), f, indent=2)"
|
1528 |
+
]
|
1529 |
+
},
|
1530 |
+
{
|
1531 |
+
"cell_type": "code",
|
1532 |
+
"execution_count": null,
|
1533 |
+
"metadata": {
|
1534 |
+
"colab": {
|
1535 |
+
"base_uri": "https://localhost:8080/"
|
1536 |
+
},
|
1537 |
+
"id": "WA_Icz5_Ia4h",
|
1538 |
+
"outputId": "e6849d82-a5c5-4da4-eff5-0336dfba468d"
|
1539 |
+
},
|
1540 |
+
"outputs": [],
|
1541 |
+
"source": [
|
1542 |
+
"# @title Save test cameras.\n",
|
1543 |
+
"\n",
|
1544 |
+
"import json\n",
|
1545 |
+
"\n",
|
1546 |
+
"test_camera_dir = root_dir / 'camera-paths'\n",
|
1547 |
+
"for test_path_name, test_cameras in camera_paths.items():\n",
|
1548 |
+
" out_dir = test_camera_dir / test_path_name\n",
|
1549 |
+
" out_dir.mkdir(exist_ok=True, parents=True)\n",
|
1550 |
+
" for i, camera in enumerate(test_cameras):\n",
|
1551 |
+
" camera_path = out_dir / f'{i:06d}.json'\n",
|
1552 |
+
" print(f'Saving camera to {camera_path!s}')\n",
|
1553 |
+
" with camera_path.open('w') as f:\n",
|
1554 |
+
" json.dump(camera.to_json(), f, indent=2)"
|
1555 |
+
]
|
1556 |
+
},
|
1557 |
+
{
|
1558 |
+
"cell_type": "markdown",
|
1559 |
+
"metadata": {
|
1560 |
+
"id": "3iV-YLB_TEMq"
|
1561 |
+
},
|
1562 |
+
"source": [
|
1563 |
+
"## Training\n",
|
1564 |
+
"\n",
|
1565 |
+
" * You are now ready to train a Nerfie!\n",
|
1566 |
+
" * Head over to the [training Colab](https://colab.sandbox.google.com/github/google/nerfies/blob/main/notebooks/Nerfies_Training.ipynb) for a basic demo."
|
1567 |
+
]
|
1568 |
+
},
|
1569 |
+
{
|
1570 |
+
"cell_type": "code",
|
1571 |
+
"execution_count": null,
|
1572 |
+
"metadata": {
|
1573 |
+
"id": "bjMZZ7I9XsVW"
|
1574 |
+
},
|
1575 |
+
"outputs": [],
|
1576 |
+
"source": []
|
1577 |
+
}
|
1578 |
+
],
|
1579 |
+
"metadata": {
|
1580 |
+
"colab": {
|
1581 |
+
"provenance": []
|
1582 |
+
},
|
1583 |
+
"gpuClass": "standard",
|
1584 |
+
"kernelspec": {
|
1585 |
+
"display_name": "Python 3 (ipykernel)",
|
1586 |
+
"language": "python",
|
1587 |
+
"name": "python3"
|
1588 |
+
},
|
1589 |
+
"language_info": {
|
1590 |
+
"codemirror_mode": {
|
1591 |
+
"name": "ipython",
|
1592 |
+
"version": 3
|
1593 |
+
},
|
1594 |
+
"file_extension": ".py",
|
1595 |
+
"mimetype": "text/x-python",
|
1596 |
+
"name": "python",
|
1597 |
+
"nbconvert_exporter": "python",
|
1598 |
+
"pygments_lexer": "ipython3",
|
1599 |
+
"version": "3.10.10"
|
1600 |
+
}
|
1601 |
+
},
|
1602 |
+
"nbformat": 4,
|
1603 |
+
"nbformat_minor": 1
|
1604 |
+
}
|