├── models ├── __init__.py ├── nerf.py └── rendering.py ├── starry_night.jpg ├── wheat_field.jpg ├── italian_futurism.jpg ├── datasets ├── __init__.py ├── depth_utils.py ├── ray_utils.py ├── blender.py └── llff.py ├── requirements.txt ├── utils ├── visualization.py ├── logger.py ├── warmup_scheduler.py └── __init__.py ├── metrics.py ├── .gitignore ├── README.md ├── demo.ipynb ├── eval.py ├── opt.py ├── losses.py ├── pipeline.py └── LICENSE /models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /starry_night.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayran/styleNeRF/HEAD/starry_night.jpg -------------------------------------------------------------------------------- /wheat_field.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayran/styleNeRF/HEAD/wheat_field.jpg -------------------------------------------------------------------------------- /italian_futurism.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhayran/styleNeRF/HEAD/italian_futurism.jpg -------------------------------------------------------------------------------- /datasets/__init__.py: -------------------------------------------------------------------------------- 1 | from .blender import BlenderDataset 2 | from .llff import LLFFDataset 3 | 4 | dataset_dict = {'blender': BlenderDataset, 5 | 'llff': LLFFDataset} -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==1.7.1 2 | torchvision==0.8.2 3 | pytorch-lightning==1.1.5 4 | einops==0.3.0 5 | test-tube==0.7.5 6 | kornia==0.4.1 7 | opencv-python==4.5.1.48 8 | matplotlib==3.3.3 9 | jupyter 10 | imageio==2.9.0 11 | imageio-ffmpeg==0.4.2 12 | torch_optimizer -------------------------------------------------------------------------------- /utils/visualization.py: -------------------------------------------------------------------------------- 1 | import torchvision.transforms as T 2 | import numpy as np 3 | import cv2 4 | from PIL import Image 5 | 6 | def visualize_depth(depth, cmap=cv2.COLORMAP_JET): 7 | """ 8 | depth: (H, W) 9 | """ 10 | x = depth.cpu().numpy() 11 | x = np.nan_to_num(x) # change nan to 0 12 | mi = np.min(x) # get minimum depth 13 | ma = np.max(x) 14 | x = (x-mi)/(ma-mi+1e-8) # normalize to 0~1 15 | x = (255*x).astype(np.uint8) 16 | x_ = Image.fromarray(cv2.applyColorMap(x, cmap)) 17 | x_ = T.ToTensor()(x_) # (3, H, W) 18 | return x_ -------------------------------------------------------------------------------- /metrics.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from kornia.losses import ssim as dssim 3 | 4 | def mse(image_pred, image_gt, valid_mask=None, reduction='mean'): 5 | value = (image_pred-image_gt)**2 6 | if valid_mask is not None: 7 | value = value[valid_mask] 8 | if reduction == 'mean': 9 | return torch.mean(value) 10 | return value 11 | 12 | def psnr(image_pred, image_gt, valid_mask=None, reduction='mean'): 13 | return -10*torch.log10(mse(image_pred, image_gt, valid_mask, reduction)) 14 | 15 | def ssim(image_pred, image_gt, reduction='mean'): 16 | """ 17 | image_pred and image_gt: (1, 3, H, W) 18 | """ 19 | dssim_ = dssim(image_pred, image_gt, 3, reduction) # dissimilarity in [0, 1] 20 | return 1-2*dssim_ # in [-1, 1] -------------------------------------------------------------------------------- /utils/logger.py: -------------------------------------------------------------------------------- 1 | from torch.utils.tensorboard import SummaryWriter 2 | import numpy as np 3 | import torch 4 | 5 | 6 | class Logger: 7 | def __init__(self): 8 | self.writer = SummaryWriter() 9 | self.keys = {} 10 | 11 | def __call__(self, key, value): 12 | if key in self.keys: 13 | self.keys[key] += 1 14 | else: 15 | self.keys[key] = 1 16 | if type(value) in [int, float]: 17 | self.writer.add_scalar(key, value, self.keys[key]) 18 | elif type(value) is np.ndarray: 19 | if len(value.shape) == 3: 20 | self.writer.add_image(key, value, self.keys[key]) 21 | else: 22 | self.writer.add_images(key, value, self.keys[key]) 23 | elif type(value) is torch.Tensor: 24 | if torch.numel(value) == 1: 25 | self.writer.add_scalar(key, float(value.item()), self.keys[key]) 26 | elif len(value.shape) == 3: 27 | self.writer.add_image(key, value, self.keys[key]) 28 | elif len(value.shape) == 4: 29 | self.writer.add_images(key, value, self.keys[key]) 30 | else: 31 | raise TypeError('Unexpected type. Options: int, float, 3d or 4d numpy arrays / torch tensors.') 32 | -------------------------------------------------------------------------------- /datasets/depth_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import re 3 | import sys 4 | 5 | def read_pfm(filename): 6 | file = open(filename, 'rb') 7 | color = None 8 | width = None 9 | height = None 10 | scale = None 11 | endian = None 12 | 13 | header = file.readline().decode('utf-8').rstrip() 14 | if header == 'PF': 15 | color = True 16 | elif header == 'Pf': 17 | color = False 18 | else: 19 | raise Exception('Not a PFM file.') 20 | 21 | dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode('utf-8')) 22 | if dim_match: 23 | width, height = map(int, dim_match.groups()) 24 | else: 25 | raise Exception('Malformed PFM header.') 26 | 27 | scale = float(file.readline().rstrip()) 28 | if scale < 0: # little-endian 29 | endian = '<' 30 | scale = -scale 31 | else: 32 | endian = '>' # big-endian 33 | 34 | data = np.fromfile(file, endian + 'f') 35 | shape = (height, width, 3) if color else (height, width) 36 | 37 | data = np.reshape(data, shape) 38 | data = np.flipud(data) 39 | file.close() 40 | return data, scale 41 | 42 | 43 | def save_pfm(filename, image, scale=1): 44 | file = open(filename, "wb") 45 | color = None 46 | 47 | image = np.flipud(image) 48 | 49 | if image.dtype.name != 'float32': 50 | raise Exception('Image dtype must be float32.') 51 | 52 | if len(image.shape) == 3 and image.shape[2] == 3: # color image 53 | color = True 54 | elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale 55 | color = False 56 | else: 57 | raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.') 58 | 59 | file.write('PF\n'.encode('utf-8') if color else 'Pf\n'.encode('utf-8')) 60 | file.write('{} {}\n'.format(image.shape[1], image.shape[0]).encode('utf-8')) 61 | 62 | endian = image.dtype.byteorder 63 | 64 | if endian == '<' or endian == '=' and sys.byteorder == 'little': 65 | scale = -scale 66 | 67 | file.write(('%f\n' % scale).encode('utf-8')) 68 | 69 | image.tofile(file) 70 | file.close() -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode/ 2 | logs/ 3 | ckpts/ 4 | results/ 5 | *.ply 6 | *.vol 7 | 8 | # Byte-compiled / optimized / DLL files 9 | __pycache__/ 10 | *.py[cod] 11 | *$py.class 12 | 13 | # C extensions 14 | *.so 15 | 16 | # Distribution / packaging 17 | .Python 18 | build/ 19 | develop-eggs/ 20 | dist/ 21 | downloads/ 22 | eggs/ 23 | .eggs/ 24 | lib/ 25 | lib64/ 26 | parts/ 27 | sdist/ 28 | var/ 29 | wheels/ 30 | pip-wheel-metadata/ 31 | share/python-wheels/ 32 | *.egg-info/ 33 | .installed.cfg 34 | *.egg 35 | MANIFEST 36 | 37 | # PyInstaller 38 | # Usually these files are written by a python script from a template 39 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 40 | *.manifest 41 | *.spec 42 | 43 | # Installer logs 44 | pip-log.txt 45 | pip-delete-this-directory.txt 46 | 47 | # Unit test / coverage reports 48 | htmlcov/ 49 | .tox/ 50 | .nox/ 51 | .coverage 52 | .coverage.* 53 | .cache 54 | nosetests.xml 55 | coverage.xml 56 | *.cover 57 | *.py,cover 58 | .hypothesis/ 59 | .pytest_cache/ 60 | 61 | # Translations 62 | *.mo 63 | *.pot 64 | 65 | # Django stuff: 66 | *.log 67 | local_settings.py 68 | db.sqlite3 69 | db.sqlite3-journal 70 | 71 | # Flask stuff: 72 | instance/ 73 | .webassets-cache 74 | 75 | # Scrapy stuff: 76 | .scrapy 77 | 78 | # Sphinx documentation 79 | docs/_build/ 80 | 81 | # PyBuilder 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | .python-version 93 | 94 | # pipenv 95 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 96 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 97 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 98 | # install all needed dependencies. 99 | #Pipfile.lock 100 | 101 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 102 | __pypackages__/ 103 | 104 | # Celery stuff 105 | celerybeat-schedule 106 | celerybeat.pid 107 | 108 | # SageMath parsed files 109 | *.sage.py 110 | 111 | # Environments 112 | .env 113 | .venv 114 | env/ 115 | venv/ 116 | ENV/ 117 | env.bak/ 118 | venv.bak/ 119 | 120 | # Spyder project settings 121 | .spyderproject 122 | .spyproject 123 | 124 | # Rope project settings 125 | .ropeproject 126 | 127 | # mkdocs documentation 128 | /site 129 | 130 | # mypy 131 | .mypy_cache/ 132 | .dmypy.json 133 | dmypy.json 134 | 135 | # Pyre type checker 136 | .pyre/ 137 | 138 | .idea 139 | datasets/nerf_synthetic 140 | runs 141 | vgg19.pt 142 | italian_futurism.jpg 143 | wheat_field.jpg 144 | 145 | *.gif -------------------------------------------------------------------------------- /utils/warmup_scheduler.py: -------------------------------------------------------------------------------- 1 | from torch.optim.lr_scheduler import _LRScheduler 2 | from torch.optim.lr_scheduler import ReduceLROnPlateau 3 | 4 | class GradualWarmupScheduler(_LRScheduler): 5 | """ Gradually warm-up(increasing) learning rate in optimizer. 6 | Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'. 7 | Args: 8 | optimizer (Optimizer): Wrapped optimizer. 9 | multiplier: target learning rate = base lr * multiplier 10 | total_epoch: target learning rate is reached at total_epoch, gradually 11 | after_scheduler: after target_epoch, use this scheduler(eg. ReduceLROnPlateau) 12 | """ 13 | 14 | def __init__(self, optimizer, multiplier, total_epoch, after_scheduler=None): 15 | self.multiplier = multiplier 16 | if self.multiplier < 1.: 17 | raise ValueError('multiplier should be greater thant or equal to 1.') 18 | self.total_epoch = total_epoch 19 | self.after_scheduler = after_scheduler 20 | self.finished = False 21 | super().__init__(optimizer) 22 | 23 | def get_lr(self): 24 | if self.last_epoch > self.total_epoch: 25 | if self.after_scheduler: 26 | if not self.finished: 27 | self.after_scheduler.base_lrs = [base_lr * self.multiplier for base_lr in self.base_lrs] 28 | self.finished = True 29 | return self.after_scheduler.get_lr() 30 | return [base_lr * self.multiplier for base_lr in self.base_lrs] 31 | 32 | return [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.) for base_lr in self.base_lrs] 33 | 34 | def step_ReduceLROnPlateau(self, metrics, epoch=None): 35 | if epoch is None: 36 | epoch = self.last_epoch + 1 37 | self.last_epoch = epoch if epoch != 0 else 1 # ReduceLROnPlateau is called at the end of epoch, whereas others are called at beginning 38 | if self.last_epoch <= self.total_epoch: 39 | warmup_lr = [base_lr * ((self.multiplier - 1.) * self.last_epoch / self.total_epoch + 1.) for base_lr in self.base_lrs] 40 | for param_group, lr in zip(self.optimizer.param_groups, warmup_lr): 41 | param_group['lr'] = lr 42 | else: 43 | if epoch is None: 44 | self.after_scheduler.step(metrics, None) 45 | else: 46 | self.after_scheduler.step(metrics, epoch - self.total_epoch) 47 | 48 | def step(self, epoch=None, metrics=None): 49 | if type(self.after_scheduler) != ReduceLROnPlateau: 50 | if self.finished and self.after_scheduler: 51 | if epoch is None: 52 | self.after_scheduler.step(None) 53 | else: 54 | self.after_scheduler.step(epoch - self.total_epoch) 55 | else: 56 | return super(GradualWarmupScheduler, self).step(epoch) 57 | else: 58 | self.step_ReduceLROnPlateau(metrics, epoch) -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | import torch 2 | # optimizer 3 | from torch.optim import SGD, Adam 4 | import torch_optimizer as optim 5 | # scheduler 6 | from torch.optim.lr_scheduler import CosineAnnealingLR, MultiStepLR 7 | from .warmup_scheduler import GradualWarmupScheduler 8 | 9 | from .visualization import * 10 | 11 | def get_parameters(models): 12 | """Get all model parameters recursively.""" 13 | parameters = [] 14 | if isinstance(models, list): 15 | for model in models: 16 | parameters += get_parameters(model) 17 | elif isinstance(models, dict): 18 | for model in models.values(): 19 | parameters += get_parameters(model) 20 | else: # models is actually a single pytorch model 21 | parameters += list(models.parameters()) 22 | return parameters 23 | 24 | def get_optimizer(hparams, models): 25 | eps = 1e-8 26 | parameters = get_parameters(models) 27 | if hparams.optimizer == 'sgd': 28 | optimizer = SGD(parameters, lr=hparams.lr, 29 | momentum=hparams.momentum, weight_decay=hparams.weight_decay) 30 | elif hparams.optimizer == 'adam': 31 | optimizer = Adam(parameters, lr=hparams.lr, eps=eps, 32 | weight_decay=hparams.weight_decay) 33 | elif hparams.optimizer == 'radam': 34 | optimizer = optim.RAdam(parameters, lr=hparams.lr, eps=eps, 35 | weight_decay=hparams.weight_decay) 36 | elif hparams.optimizer == 'ranger': 37 | optimizer = optim.Ranger(parameters, lr=hparams.lr, eps=eps, 38 | weight_decay=hparams.weight_decay) 39 | else: 40 | raise ValueError('optimizer not recognized!') 41 | 42 | return optimizer 43 | 44 | def get_scheduler(hparams, optimizer): 45 | eps = 1e-8 46 | if hparams.lr_scheduler == 'steplr': 47 | scheduler = MultiStepLR(optimizer, milestones=hparams.decay_step, 48 | gamma=hparams.decay_gamma) 49 | elif hparams.lr_scheduler == 'cosine': 50 | scheduler = CosineAnnealingLR(optimizer, T_max=hparams.num_epochs, eta_min=eps) 51 | elif hparams.lr_scheduler == 'poly': 52 | scheduler = LambdaLR(optimizer, 53 | lambda epoch: (1-epoch/hparams.num_epochs)**hparams.poly_exp) 54 | else: 55 | raise ValueError('scheduler not recognized!') 56 | 57 | if hparams.warmup_epochs > 0 and hparams.optimizer not in ['radam', 'ranger']: 58 | scheduler = GradualWarmupScheduler(optimizer, multiplier=hparams.warmup_multiplier, 59 | total_epoch=hparams.warmup_epochs, after_scheduler=scheduler) 60 | 61 | return scheduler 62 | 63 | def get_learning_rate(optimizer): 64 | for param_group in optimizer.param_groups: 65 | return param_group['lr'] 66 | 67 | def extract_model_state_dict(ckpt_path, model_name='model', prefixes_to_ignore=[]): 68 | checkpoint = torch.load(ckpt_path, map_location=torch.device('cpu')) 69 | checkpoint_ = {} 70 | if 'state_dict' in checkpoint: # if it's a pytorch-lightning checkpoint 71 | checkpoint = checkpoint['state_dict'] 72 | for k, v in checkpoint.items(): 73 | if not k.startswith(model_name): 74 | continue 75 | k = k[len(model_name)+1:] 76 | for prefix in prefixes_to_ignore: 77 | if k.startswith(prefix): 78 | print('ignore', k) 79 | break 80 | else: 81 | checkpoint_[k] = v 82 | return checkpoint_ 83 | 84 | def load_ckpt(model, ckpt_path, model_name='model', prefixes_to_ignore=[]): 85 | model_dict = model.state_dict() 86 | checkpoint_ = extract_model_state_dict(ckpt_path, model_name, prefixes_to_ignore) 87 | model_dict.update(checkpoint_) 88 | model.load_state_dict(model_dict) 89 | -------------------------------------------------------------------------------- /datasets/ray_utils.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from kornia import create_meshgrid 3 | 4 | 5 | def get_ray_directions(H, W, focal): 6 | """ 7 | Get ray directions for all pixels in camera coordinate. 8 | Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/ 9 | ray-tracing-generating-camera-rays/standard-coordinate-systems 10 | 11 | Inputs: 12 | H, W, focal: image height, width and focal length 13 | 14 | Outputs: 15 | directions: (H, W, 3), the direction of the rays in camera coordinate 16 | """ 17 | grid = create_meshgrid(H, W, normalized_coordinates=False)[0] 18 | i, j = grid.unbind(-1) 19 | # the direction here is without +0.5 pixel centering as calibration is not so accurate 20 | # see https://github.com/bmild/nerf/issues/24 21 | directions = \ 22 | torch.stack([(i-W/2)/focal, -(j-H/2)/focal, -torch.ones_like(i)], -1) # (H, W, 3) 23 | 24 | return directions 25 | 26 | 27 | def get_rays(directions, c2w): 28 | """ 29 | Get ray origin and normalized directions in world coordinate for all pixels in one image. 30 | Reference: https://www.scratchapixel.com/lessons/3d-basic-rendering/ 31 | ray-tracing-generating-camera-rays/standard-coordinate-systems 32 | 33 | Inputs: 34 | directions: (H, W, 3) precomputed ray directions in camera coordinate 35 | c2w: (3, 4) transformation matrix from camera coordinate to world coordinate 36 | 37 | Outputs: 38 | rays_o: (H*W, 3), the origin of the rays in world coordinate 39 | rays_d: (H*W, 3), the normalized direction of the rays in world coordinate 40 | """ 41 | # Rotate ray directions from camera coordinate to the world coordinate 42 | rays_d = directions @ c2w[:, :3].T # (H, W, 3) 43 | rays_d = rays_d / torch.norm(rays_d, dim=-1, keepdim=True) 44 | # The origin of all rays is the camera origin in world coordinate 45 | rays_o = c2w[:, 3].expand(rays_d.shape) # (H, W, 3) 46 | 47 | rays_d = rays_d.view(-1, 3) 48 | rays_o = rays_o.view(-1, 3) 49 | 50 | return rays_o, rays_d 51 | 52 | 53 | def get_ndc_rays(H, W, focal, near, rays_o, rays_d): 54 | """ 55 | Transform rays from world coordinate to NDC. 56 | NDC: Space such that the canvas is a cube with sides [-1, 1] in each axis. 57 | For detailed derivation, please see: 58 | http://www.songho.ca/opengl/gl_projectionmatrix.html 59 | https://github.com/bmild/nerf/files/4451808/ndc_derivation.pdf 60 | 61 | In practice, use NDC "if and only if" the scene is unbounded (has a large depth). 62 | See https://github.com/bmild/nerf/issues/18 63 | 64 | Inputs: 65 | H, W, focal: image height, width and focal length 66 | near: (N_rays) or float, the depths of the near plane 67 | rays_o: (N_rays, 3), the origin of the rays in world coordinate 68 | rays_d: (N_rays, 3), the direction of the rays in world coordinate 69 | 70 | Outputs: 71 | rays_o: (N_rays, 3), the origin of the rays in NDC 72 | rays_d: (N_rays, 3), the direction of the rays in NDC 73 | """ 74 | # Shift ray origins to near plane 75 | t = -(near + rays_o[...,2]) / rays_d[...,2] 76 | rays_o = rays_o + t[...,None] * rays_d 77 | 78 | # Store some intermediate homogeneous results 79 | ox_oz = rays_o[...,0] / rays_o[...,2] 80 | oy_oz = rays_o[...,1] / rays_o[...,2] 81 | 82 | # Projection 83 | o0 = -1./(W/(2.*focal)) * ox_oz 84 | o1 = -1./(H/(2.*focal)) * oy_oz 85 | o2 = 1. + 2. * near / rays_o[...,2] 86 | 87 | d0 = -1./(W/(2.*focal)) * (rays_d[...,0]/rays_d[...,2] - ox_oz) 88 | d1 = -1./(H/(2.*focal)) * (rays_d[...,1]/rays_d[...,2] - oy_oz) 89 | d2 = 1 - o2 90 | 91 | rays_o = torch.stack([o0, o1, o2], -1) # (B, 3) 92 | rays_d = torch.stack([d0, d1, d2], -1) # (B, 3) 93 | 94 | return rays_o, rays_d -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # styleNeRF 2 | 3 | Memory efficient 3D style transfer for neural radiance fields [1] in PyTorch. 4 | 5 | This project is built upon a [PyTorch Lightning implementation](https://github.com/kwea123/nerf_pl) [2] and [the official PyTorch tutorial for neural style transfer](https://pytorch.org/tutorials/advanced/neural_style_tutorial.html). 6 | 7 | ## Download the blender dataset 8 | 9 | Download `nerf_synthetic.zip` from [here](https://drive.google.com/drive/folders/128yBriW1IG_3NJ5Rp7APSTZsJqdJdfc1) and extract the content under `./datasets`. We work with the lego dataset which is expected to be under `./datasets/nerf_synthetic/lego`. 10 | 11 | ## Quick demonstration 12 | 13 | If you want to give this repo a quick try, you can run `demo.ipynb` which will first train a NeRF model on the synthetic lego truck scene, then transfer the style from Van Gogh's starry night image, and finally render a gif. You can monitor the training process via the command `tensorboard --logdir runs` and going to `localhost:6006` in your browser. 14 | 15 | ## Model architecture 16 | 17 | We employ a two stage training. First stage is the standard NeRF training procedure. Our primary aim is to train the "geometry MLP" which is responsible for generating the density, while "style MLP" acts as an auxilary network and will be modified later on. 18 | 19 | In the second stage, we freeze the geometry MLP and train style MLP by the style loss between rendered images and the style image. By doing so, we disentangle the geometry and appearance of the scene, hence manage to transfer the style while making sure the geometry is fixed. 20 | 21 | ![image](https://user-images.githubusercontent.com/40629249/124367192-5d43fe00-dc55-11eb-9408-6e99529007e2.png) 22 | 23 | ## Stage 1: Train the density model 24 | 25 | After downloading the dataset, run the following command for the Stage 1 where the scene geometry is learned: 26 | 27 | ``` 28 | python pipeline.py --stage geometry --prefix $PREFIX --suffix $SUFFIX --dataset_name blender --root_dir datasets/nerf_synthetic/lego --img_wh 400 400 --num_epochs_density 1 --batch_size 1024 --lr 5e-4 29 | ``` 30 | 31 | The models will be logged under `./ckpts/$PREFIX_nerf_coarse_$SUFFIX.pt` and `./ckpts/$PREFIX_nerf_fine_$SUFFIX.pt` 32 | 33 | ## Stage 2: Transfer the style 34 | 35 | Having trained the density model, we now transfer the style while freezing the geometry MLP with the following command: 36 | 37 | ``` 38 | python pipeline.py --stage style --prefix $PREFIX --suffix $SUFFIX --style_dir $STYLE_DIR --style_mode $STYLE_MODE --coarse_path $COARSE_PATH --fine_path $FINE_PATH --dataset_name blender --root_dir datasets/nerf_synthetic/lego --img_wh 400 400 --num_epochs_style 1 --lr 1e-3 39 | ``` 40 | 41 | where `$STYLE_DIR` is the path to style image, `$COARSE_PATH` is the path to previously logged coarse NeRF model and `$FINE_PATH` is the path to previously logged fine NeRF model. 42 | 43 | Style transfer stage is very heavy in terms of memory consumption, since we can't process the pixels individually due to the nature of style loss. We propose three different ways to alleviate that problem which you can specify by `$STYLE_MODE`: 44 | - `small`: This is the most straightforward approach, where you render smaller images. Limited to around a size of 50 x 50 for a GPU with 8 GB of memory, hence the fine detail is lost. Significant size mismatch between rendered images and the style image is a problem. 45 | - `patch`: Render patches and transfer the style to each patch individually. Better performance, but lacks global consistency and fails to capture higher level features since we have to process patches individually. Size mismatch problem persists. 46 | - `memory_saving`: A practical workaround for working with arbitrarily big images without using patching, which enables us to process pixels even individually. This way we mitigate both the memory limitations and the size mismatch issue. This approach consists of two substages: 47 | - Substage 1: Render image in inference mode, calculate and store gradients per pixel by the style loss 48 | - Substage 2: Render pixels while freezing the geometry MLP, then backpropagate the corresponding stored pixel gradients. Wait for every pixel to be processed before stepping the optimizer. 49 | 50 | ![image](https://user-images.githubusercontent.com/40629249/124367388-03443800-dc57-11eb-9e93-5c80d1a724f4.png) 51 | 52 | ## Testing 53 | 54 | Use [eval.py](eval.py) to create the whole sequence of moving views. 55 | E.g. 56 | ``` 57 | python eval.py --dataset_name blender --root_dir datasets/nerf_synthetic/lego --scene_name lego --img_wh 400 400 --coarse_path $COARSE_PATH --fine_path $FINE_PATH --gif_name $GIF_NAME 58 | ``` 59 | 60 | It will create folder `results/{dataset_name}/{scene_name}` and run inference on all test data, finally create a gif out of them and save to `./$GIF_NAME.gif`. 61 | 62 | - Example: A NeRF model trained first on the synthetic lego truck data with 400 x 400 images, then learned the style of the Van Gogh's starry night image using the `memory_saving` mode, using a GPU with 8GB of memory. Memory saving mode enables working with GPUs having quite low memory. 63 | 64 | ![gif](https://user-images.githubusercontent.com/40629249/124567099-f3d61200-de43-11eb-86dc-035567213182.gif) 65 | 66 | ## References 67 | [1] 68 | Ben Mildenhall, Pratul P. Srinivasan, Matthew Tancik, Jonathan T. Barron, Ravi Ramamoorthi, and Ren Ng. *Nerf: Representing scenes as neural radiance fields for view synthesis.* In European Conference on Computer Vision, pages 405–421. Springer, 2020. 69 | 70 | [2] 71 | Chen Quei-An. *Nerf_pl: A pytorch-lightning implementation of neural radiance fields*, 2020. 72 | -------------------------------------------------------------------------------- /demo.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "attachments": {}, 5 | "cell_type": "markdown", 6 | "id": "c3682d44", 7 | "metadata": {}, 8 | "source": [ 9 | "## Repo demonstration for replicating the results\n", 10 | "\n", 11 | "Please make sure that you have installed packages listed in `requirements.txt`\n", 12 | "\n", 13 | "If you want to monitor training process, run `tensorboard --logdir runs`\n", 14 | "\n", 15 | "We worked with 400 x 400 images in our experiments, using a single GPU with 8GB of memory.\n", 16 | "\n", 17 | "`pipeline.py` is the main script for training which you can call by certain arguments:\n", 18 | "- --stage: `geometry` when learning the scene geometry, `style` when transferring the style.\n", 19 | "- --prefix and --suffix: trained models will be saved under `ckpts/{prefix}_nerf_coarse_{suffix}.pt` and `ckpts/{prefix}_nerf_fine_{suffix}.pt`\n", 20 | "- --img_wh: image resolution, `400 400` in our experiments.\n", 21 | "- --num_epochs_density: number of epochs when learning scene geometry, `1` in our experiments.\n", 22 | "- --batch_size: batch size, only relevant in the `geometry` stage, `1024` in our experiments.\n", 23 | "- --num_epochs_style: number of epochs when transferring the style, `1` in our experiments.\n", 24 | "- --style_dir: path to the styling image, one of the following options: `starry_night.jpg`, `wheat_field.jpg`, `italian_futurism.jpg`\n", 25 | "- --style_mode: the approach to take in style transfer stage, one of the following options: `small` (refers to simple method, takes around 5 mins), `patch` (refers to patched method, takes around 30 mins), `memory_saving` (refers to no patch method, takes around 50 mins)\n", 26 | "- --coarse_path and --fine_path: when transferring the style, path to coarse and fine density models learned in Stage 1\n", 27 | "- --lr: learning rate, in our experiments `5e-4` for `geometry` stage, `1e-3` for `style` stage with `small` or `memory_saving` mode, `1e-4` for `patch` mode" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "id": "f379b7f6", 34 | "metadata": {}, 35 | "outputs": [ 36 | { 37 | "name": "stdout", 38 | "output_type": "stream", 39 | "text": [ 40 | "Starting epoch 1 to learn density...\n" 41 | ] 42 | } 43 | ], 44 | "source": [ 45 | "# Stage 1: Train the geometry MLP.\n", 46 | "# Estimated runtime: 1 hour\n", 47 | "# You can increase the batch size if you have access to more memory to speed up training.\n", 48 | "\n", 49 | "!python pipeline.py --stage geometry --prefix test --suffix density --dataset_name blender --root_dir datasets/nerf_synthetic/lego --img_wh 400 400 --num_epochs_density 1 --batch_size 1024 --lr 5e-4" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 3, 55 | "id": "e005da8a", 56 | "metadata": {}, 57 | "outputs": [ 58 | { 59 | "name": "stdout", 60 | "output_type": "stream", 61 | "text": [ 62 | "Mode: Memory saving (No patch), Starting epoch 1 to learn style...\n" 63 | ] 64 | } 65 | ], 66 | "source": [ 67 | "# Stage 2: Train the style MLP with the starry night image and in memory saving mode. \n", 68 | "# Estimated runtime: 50 mins\n", 69 | "\n", 70 | "!python pipeline.py --stage style --prefix test --suffix style --style_dir starry_night.jpg --style_mode memory_saving --coarse_path ckpts/test_nerf_coarse_density.pt --fine_path ckpts/test_nerf_fine_density.pt --dataset_name blender --root_dir datasets/nerf_synthetic/lego --img_wh 400 400 --num_epochs_style 1 --lr 1e-3" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 8, 76 | "id": "a5050f18", 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "%%capture\n", 81 | "\n", 82 | "# Create and save a gif out of the rendered images from 200 camera poses in test dataset under ./starry_night_memory_saving.gif\n", 83 | "# Estimated runtime: 1 hour\n", 84 | "\n", 85 | "!python eval.py --dataset_name blender --root_dir datasets/nerf_synthetic/lego --scene_name lego --img_wh 400 400 --coarse_path ckpts/test_nerf_coarse_style.pt --fine_path ckpts/test_nerf_fine_style.pt --gif_name starry_night_memory_saving" 86 | ] 87 | }, 88 | { 89 | "cell_type": "code", 90 | "execution_count": 9, 91 | "id": "a776849e", 92 | "metadata": {}, 93 | "outputs": [ 94 | { 95 | "data": { 96 | "text/html": [ 97 | "

" 98 | ], 99 | "text/plain": [ 100 | "" 101 | ] 102 | }, 103 | "metadata": {}, 104 | "output_type": "display_data" 105 | } 106 | ], 107 | "source": [ 108 | "# Display the saved gif\n", 109 | "\n", 110 | "from IPython.core.display import display, HTML\n", 111 | "display(HTML('

'))" 112 | ] 113 | } 114 | ], 115 | "metadata": { 116 | "kernelspec": { 117 | "display_name": "Python 3", 118 | "language": "python", 119 | "name": "python3" 120 | }, 121 | "language_info": { 122 | "codemirror_mode": { 123 | "name": "ipython", 124 | "version": 3 125 | }, 126 | "file_extension": ".py", 127 | "mimetype": "text/x-python", 128 | "name": "python", 129 | "nbconvert_exporter": "python", 130 | "pygments_lexer": "ipython3", 131 | "version": "3.9.2" 132 | } 133 | }, 134 | "nbformat": 4, 135 | "nbformat_minor": 5 136 | } 137 | -------------------------------------------------------------------------------- /eval.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import os 3 | import numpy as np 4 | from collections import defaultdict 5 | from tqdm import tqdm 6 | import imageio 7 | from argparse import ArgumentParser 8 | 9 | from models.rendering import render_rays 10 | from models.nerf import * 11 | 12 | from utils import load_ckpt 13 | import metrics 14 | 15 | from datasets import dataset_dict 16 | from datasets.depth_utils import * 17 | 18 | torch.backends.cudnn.benchmark = True 19 | 20 | 21 | def get_opts(): 22 | parser = ArgumentParser() 23 | parser.add_argument('--root_dir', type=str, 24 | default='/home/ubuntu/data/nerf_example_data/nerf_synthetic/lego', 25 | help='root directory of dataset') 26 | parser.add_argument('--dataset_name', type=str, default='blender', 27 | choices=['blender'], 28 | help='which dataset to validate') 29 | parser.add_argument('--scene_name', type=str, default='test', 30 | help='scene name, used as output folder name') 31 | parser.add_argument('--split', type=str, default='test', 32 | choices=['val', 'test', 'test_train']) 33 | parser.add_argument('--img_wh', nargs="+", type=int, default=[800, 800], 34 | help='resolution (img_w, img_h) of the image') 35 | 36 | parser.add_argument('--coarse_path', type=str, help='path to the coarse NeRF model') 37 | parser.add_argument('--fine_path', type=str, help='path to the fine NeRF model') 38 | parser.add_argument('--gif_name', type=str, help='name for the gif to be saved') 39 | 40 | # original NeRF parameters 41 | parser.add_argument('--N_emb_xyz', type=int, default=10, 42 | help='number of xyz embedding frequencies') 43 | parser.add_argument('--N_emb_dir', type=int, default=4, 44 | help='number of direction embedding frequencies') 45 | parser.add_argument('--N_samples', type=int, default=64, 46 | help='number of coarse samples') 47 | parser.add_argument('--N_importance', type=int, default=128, 48 | help='number of additional fine samples') 49 | parser.add_argument('--use_disp', default=False, action="store_true", 50 | help='use disparity depth sampling') 51 | 52 | # NeRF-W parameters 53 | parser.add_argument('--N_vocab', type=int, default=100, 54 | help='''number of vocabulary (number of images) 55 | in the dataset for nn.Embedding''') 56 | parser.add_argument('--encode_a', default=False, action="store_true", 57 | help='whether to encode appearance (NeRF-A)') 58 | parser.add_argument('--N_a', type=int, default=48, 59 | help='number of embeddings for appearance') 60 | parser.add_argument('--encode_t', default=False, action="store_true", 61 | help='whether to encode transient object (NeRF-U)') 62 | parser.add_argument('--N_tau', type=int, default=16, 63 | help='number of embeddings for transient objects') 64 | parser.add_argument('--beta_min', type=float, default=0.1, 65 | help='minimum color variance for each ray') 66 | 67 | parser.add_argument('--chunk', type=int, default=32 * 1024 * 4, 68 | help='chunk size to split the input to avoid OOM') 69 | 70 | return parser.parse_args() 71 | 72 | 73 | @torch.no_grad() 74 | def batched_inference(models, embeddings, 75 | rays, ts, N_samples, N_importance, use_disp, 76 | chunk, 77 | white_back): 78 | """Do batched inference on rays using chunk.""" 79 | B = rays.shape[0] 80 | results = defaultdict(list) 81 | for i in range(0, B, chunk): 82 | rendered_ray_chunks = \ 83 | render_rays(models, 84 | embeddings, 85 | rays[i:i + chunk], 86 | ts[i:i + chunk], 87 | N_samples, 88 | use_disp, 89 | 0, 90 | 0, 91 | N_importance, 92 | chunk, 93 | dataset.white_back, 94 | test_time=True) 95 | 96 | for k, v in rendered_ray_chunks.items(): 97 | results[k] += [v] 98 | 99 | for k, v in results.items(): 100 | results[k] = torch.cat(v, 0) 101 | return results 102 | 103 | 104 | if __name__ == "__main__": 105 | args = get_opts() 106 | w, h = args.img_wh 107 | 108 | kwargs = {'root_dir': args.root_dir, 109 | 'split': args.split, 110 | 'img_wh': tuple(args.img_wh)} 111 | dataset = dataset_dict[args.dataset_name](**kwargs) 112 | 113 | embedding_xyz = PosEmbedding(args.N_emb_xyz - 1, args.N_emb_xyz) 114 | embedding_dir = PosEmbedding(args.N_emb_dir - 1, args.N_emb_dir) 115 | embeddings = {'xyz': embedding_xyz, 'dir': embedding_dir} 116 | 117 | nerf_coarse = NeRF('coarse').cuda() 118 | nerf_fine = NeRF('fine', beta_min=args.beta_min).cuda() 119 | 120 | nerf_coarse.load_state_dict(torch.load(args.coarse_path)) 121 | nerf_coarse.eval() 122 | nerf_fine.load_state_dict(torch.load(args.fine_path)) 123 | nerf_fine.eval() 124 | 125 | models = {'coarse': nerf_coarse, 'fine': nerf_fine} 126 | 127 | imgs, psnrs = [], [] 128 | dir_name = f'results/{args.dataset_name}/{args.scene_name}' 129 | os.makedirs(dir_name, exist_ok=True) 130 | 131 | for i in tqdm(range(len(dataset))): 132 | sample = dataset[i] 133 | rays = sample['rays'].cuda() 134 | ts = sample['ts'].cuda() 135 | results = batched_inference(models, embeddings, rays, ts, 136 | args.N_samples, args.N_importance, args.use_disp, 137 | args.chunk, 138 | dataset.white_back) 139 | 140 | img_pred = results['rgb_fine'].view(h, w, 3).cpu().numpy() 141 | 142 | img_pred_ = (img_pred * 255).astype(np.uint8) 143 | imgs += [img_pred_] 144 | imageio.imwrite(os.path.join(dir_name, f'{i:03d}.png'), img_pred_) 145 | 146 | if 'rgbs' in sample: 147 | rgbs = sample['rgbs'] 148 | img_gt = rgbs.view(h, w, 3) 149 | psnrs += [metrics.psnr(img_gt, img_pred).item()] 150 | 151 | imageio.mimsave(f'{args.gif_name}.gif', imgs, fps=30) 152 | 153 | if psnrs: 154 | mean_psnr = np.mean(psnrs) 155 | print(f'Mean PSNR : {mean_psnr:.2f}') 156 | -------------------------------------------------------------------------------- /opt.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | def get_opts(): 4 | parser = argparse.ArgumentParser() 5 | 6 | parser.add_argument('--stage', type=str, default='style', 7 | help='''training stage. options: 8 | 'geometry', 'style' 9 | ''') 10 | parser.add_argument('--style_dir', type=str, default=None, help='path to style image') 11 | parser.add_argument('--style_mode', type=str, default='memory_saving', 12 | help='''style transfer method. options: 13 | 'memory_saving', 'patch', 'small' 14 | ''') 15 | 16 | parser.add_argument('--prefix', type=str, default='', help='prefix for the model name') 17 | parser.add_argument('--suffix', type=str, default='', help='suffix for the model name') 18 | 19 | parser.add_argument('--coarse_path', type=str, default=None, help='path to coarse model when transferring style') 20 | parser.add_argument('--fine_path', type=str, default=None, help='path to fine model when transferring style') 21 | 22 | parser.add_argument('--root_dir', type=str, 23 | default='/home/ubuntu/data/nerf_example_data/nerf_synthetic/lego', 24 | help='root directory of dataset') 25 | parser.add_argument('--dataset_name', type=str, default='blender', 26 | choices=['blender', 'llff'], 27 | help='which dataset to train/val') 28 | parser.add_argument('--data_perturb', nargs="+", type=str, default=[], 29 | help='''what perturbation to add to data. 30 | Available choices: [], ["color"], ["occ"] or ["color", "occ"] 31 | ''') 32 | parser.add_argument('--img_wh', nargs="+", type=int, default=[400, 400], 33 | help='resolution (img_w, img_h) of the image') 34 | parser.add_argument('--spheric_poses', default=False, action="store_true", 35 | help='whether images are taken in spheric poses (for llff)') 36 | parser.add_argument('--use_gpu', default=True, help='whether to use GPU') 37 | 38 | # original NeRF parameters 39 | parser.add_argument('--N_emb_xyz', type=int, default=10, 40 | help='number of xyz embedding frequencies') 41 | parser.add_argument('--N_emb_dir', type=int, default=4, 42 | help='number of direction embedding frequencies') 43 | parser.add_argument('--N_samples', type=int, default=64, 44 | help='number of coarse samples') 45 | parser.add_argument('--N_importance', type=int, default=64, 46 | help='number of additional fine samples') 47 | parser.add_argument('--use_disp', default=False, action="store_true", 48 | help='use disparity depth sampling') 49 | parser.add_argument('--perturb', type=float, default=1.0, 50 | help='factor to perturb depth sampling points') 51 | parser.add_argument('--noise_std', type=float, default=0.0, 52 | help='std dev of noise added to regularize sigma') 53 | 54 | # NeRF-W parameters 55 | parser.add_argument('--N_vocab', type=int, default=100, 56 | help='''number of vocabulary (number of images) 57 | in the dataset for nn.Embedding''') 58 | parser.add_argument('--encode_a', default=False, action="store_true", 59 | help='whether to encode appearance (NeRF-A)') 60 | parser.add_argument('--N_a', type=int, default=48, 61 | help='dimensionality of appearance embeddings') 62 | parser.add_argument('--encode_t', default=False, action="store_true", 63 | help='whether to encode transient object (NeRF-U)') 64 | parser.add_argument('--N_tau', type=int, default=16, 65 | help='number of embeddings for transient objects') 66 | parser.add_argument('--beta_min', type=float, default=0.1, 67 | help='minimum color variance for each ray') 68 | 69 | parser.add_argument('--batch_size', type=int, default=1024, 70 | help='batch size') 71 | parser.add_argument('--chunk', type=int, default=32*1024, 72 | help='chunk size to split the input to avoid OOM') 73 | parser.add_argument('--num_epochs_density', type=int, default=1, 74 | help='number of training epochs for density learning stage') 75 | parser.add_argument('--num_epochs_style', type=int, default=1, 76 | help='number of training epochs for style learning stage') 77 | parser.add_argument('--num_gpus', type=int, default=1, 78 | help='number of gpus') 79 | 80 | parser.add_argument('--ckpt_path', type=str, default=None, 81 | help='pretrained checkpoint path to load') 82 | parser.add_argument('--prefixes_to_ignore', nargs='+', type=str, default=['loss'], 83 | help='the prefixes to ignore in the checkpoint state dict') 84 | 85 | parser.add_argument('--optimizer', type=str, default='adam', 86 | help='optimizer type', 87 | choices=['sgd', 'adam', 'radam', 'ranger']) 88 | parser.add_argument('--lr', type=float, default=5e-4, 89 | help='learning rate') 90 | parser.add_argument('--momentum', type=float, default=0.9, 91 | help='learning rate momentum') 92 | parser.add_argument('--weight_decay', type=float, default=0, 93 | help='weight decay') 94 | parser.add_argument('--lr_scheduler', type=str, default='steplr', 95 | help='scheduler type', 96 | choices=['steplr', 'cosine', 'poly']) 97 | #### params for warmup, only applied when optimizer == 'sgd' or 'adam' 98 | parser.add_argument('--warmup_multiplier', type=float, default=1.0, 99 | help='lr is multiplied by this factor after --warmup_epochs') 100 | parser.add_argument('--warmup_epochs', type=int, default=0, 101 | help='Gradually warm-up(increasing) learning rate in optimizer') 102 | ########################### 103 | #### params for steplr #### 104 | parser.add_argument('--decay_step', nargs='+', type=int, default=[20], 105 | help='scheduler decay step') 106 | parser.add_argument('--decay_gamma', type=float, default=0.1, 107 | help='learning rate decay amount') 108 | ########################### 109 | #### params for poly #### 110 | parser.add_argument('--poly_exp', type=float, default=0.9, 111 | help='exponent for polynomial learning rate decay') 112 | ########################### 113 | 114 | parser.add_argument('--exp_name', type=str, default='exp', 115 | help='experiment name') 116 | 117 | return parser.parse_args() 118 | -------------------------------------------------------------------------------- /models/nerf.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from collections import OrderedDict 4 | 5 | 6 | class PosEmbedding(nn.Module): 7 | def __init__(self, max_logscale, N_freqs, logscale=True): 8 | """ 9 | Defines a function that embeds x to (sin(2^k x), cos(2^k x), ...) 10 | """ 11 | super().__init__() 12 | self.funcs = [torch.sin, torch.cos] 13 | 14 | if logscale: 15 | self.freqs = 2**torch.linspace(0, max_logscale, N_freqs) 16 | else: 17 | self.freqs = torch.linspace(1, 2**max_logscale, N_freqs) 18 | 19 | def forward(self, x): 20 | """ 21 | Inputs: 22 | x: (B, 3) 23 | 24 | Outputs: 25 | out: (B, 6*N_freqs+3) 26 | """ 27 | out = [x] 28 | for freq in self.freqs: 29 | for func in self.funcs: 30 | out += [func(freq*x)] 31 | 32 | return torch.cat(out, -1) 33 | 34 | 35 | class NeRF(nn.Module): 36 | def __init__(self, typ, 37 | D=8, W=256, 38 | in_channels_xyz=63, in_channels_dir=27, 39 | skips=[4], 40 | encode_appearance=False, in_channels_a=48, 41 | encode_transient=False, in_channels_t=16, 42 | beta_min=0.03): 43 | """ 44 | ---Parameters for the original NeRF--- 45 | typ: if 'coarse', refers to coarse model. else, refers to fine model. 46 | D: number of layers for density (sigma) encoder 47 | W: number of hidden units in each layer 48 | in_channels_xyz: number of input channels for xyz (3 + 3*10*2=63 by default) 49 | in_channels_dir: number of input channels for direction (3 + 3*4*2=27 by default) 50 | in_channels_t: number of input channels for t 51 | skips: add skip connection in the Dth layer 52 | 53 | ---Parameters for NeRF-W (used in fine model only as per section 4.3)--- 54 | encode_appearance: whether to add appearance encoding as input (NeRF-A) 55 | in_channels_a: appearance embedding dimension. n^(a) in the paper 56 | encode_transient: whether to add transient encoding as input (NeRF-U) 57 | in_channels_t: transient embedding dimension. n^(tau) in the paper 58 | beta_min: minimum pixel color variance 59 | """ 60 | super().__init__() 61 | self.typ = typ 62 | self.D = D 63 | self.W = W 64 | self.in_channels_xyz = in_channels_xyz 65 | self.in_channels_dir = in_channels_dir 66 | self.in_channels_t = in_channels_t 67 | self.skips = skips 68 | 69 | """ 70 | don't use any embeddings if the network is coarse, since the primary aim for coarse network is to guide the 71 | sampling process by the generated density 72 | """ 73 | self.encode_appearance = False if typ == 'coarse' else encode_appearance 74 | self.in_channels_a = in_channels_a if encode_appearance else 0 75 | self.encode_transient = False if typ == 'coarse' else encode_transient 76 | self.in_channels_t = in_channels_t 77 | self.beta_min = beta_min 78 | 79 | # xyz encoding layers, refers to the orange block in Figure 3 (NeRF-W) 80 | for i in range(D): 81 | if i == 0: 82 | layer = nn.Linear(in_channels_xyz, W) 83 | elif i in skips: 84 | layer = nn.Linear(W+in_channels_xyz, W) 85 | else: 86 | layer = nn.Linear(W, W) 87 | # layer = nn.Sequential(layer, nn.ReLU(True)) 88 | 89 | layer = nn.Sequential(OrderedDict([ 90 | (f'density', layer), 91 | (f'activation', nn.ReLU(True)) 92 | ])) 93 | setattr(self, f"xyz_encoding_{i+1}", layer) 94 | 95 | self.xyz_encoding_final = nn.Linear(W, W) 96 | 97 | # direction encoding layers, refers to the green block in Figure 3 (NeRF-W) 98 | self.dir_encoding = nn.Sequential( 99 | nn.Linear(W+in_channels_dir+self.in_channels_a, W//2), 100 | nn.ReLU(True), 101 | nn.Linear(W // 2, W // 2), 102 | nn.ReLU(True), 103 | nn.Linear(W // 2, W // 2), 104 | nn.ReLU(True), 105 | nn.Linear(W // 2, W // 2), 106 | nn.ReLU(True), 107 | nn.Linear(W // 2, W // 2), 108 | nn.ReLU(True), 109 | nn.Linear(W // 2, W // 2), 110 | nn.ReLU(True) 111 | ) 112 | 113 | # static output layers 114 | self.static_sigma = nn.Sequential(OrderedDict([ # outputs the density from the orange block 115 | (f'density', nn.Linear(W, 1)), 116 | (f'activation', nn.Softplus()) 117 | ])) 118 | 119 | # self.static_sigma = nn.Sequential(nn.Linear(W, 1), nn.Softplus()) 120 | self.static_rgb = nn.Sequential(nn.Linear(W//2, 3), nn.Sigmoid()) # outputs the RGB color from the green block 121 | 122 | if self.encode_transient: 123 | # transient encoding layers 124 | self.transient_encoding = nn.Sequential( 125 | nn.Linear(W+in_channels_t, W//2), nn.ReLU(True), 126 | nn.Linear(W//2, W//2), nn.ReLU(True), 127 | nn.Linear(W//2, W//2), nn.ReLU(True), 128 | nn.Linear(W//2, W//2), nn.ReLU(True)) 129 | # transient output layers 130 | self.transient_sigma = nn.Sequential(nn.Linear(W//2, 1), nn.Softplus()) 131 | self.transient_rgb = nn.Sequential(nn.Linear(W//2, 3), nn.Sigmoid()) 132 | self.transient_beta = nn.Sequential(nn.Linear(W//2, 1), nn.Softplus()) 133 | 134 | def forward(self, x, sigma_only=False, output_transient=True): 135 | """ 136 | Encodes input (xyz+dir) to rgb+sigma (not ready to render yet). 137 | For rendering this ray, please see rendering.py 138 | 139 | Inputs: 140 | x: the embedded vector of position (+ direction + appearance + transient) 141 | sigma_only: whether to infer sigma only. 142 | output_transient: whether to infer the transient component. 143 | 144 | Outputs: 145 | if sigma_only: 146 | static_sigma 147 | elif output_transient: 148 | static_rgb, static_sigma, transient_rgb, transient_sigma, transient_beta 149 | else: 150 | static_sigma, static_rgb 151 | """ 152 | if sigma_only: 153 | input_xyz = x 154 | elif output_transient: 155 | input_xyz, input_dir_a, input_t = \ 156 | torch.split(x, [self.in_channels_xyz, 157 | self.in_channels_dir+self.in_channels_a, 158 | self.in_channels_t], dim=-1) 159 | else: 160 | input_xyz, input_dir_a = \ 161 | torch.split(x, [self.in_channels_xyz, 162 | self.in_channels_dir+self.in_channels_a], dim=-1) 163 | 164 | 165 | xyz_ = input_xyz 166 | for i in range(self.D): 167 | if i in self.skips: 168 | xyz_ = torch.cat([input_xyz, xyz_], 1) 169 | xyz_ = getattr(self, f"xyz_encoding_{i+1}")(xyz_) 170 | 171 | static_sigma = self.static_sigma(xyz_) # (B, 1) 172 | if sigma_only: 173 | return static_sigma 174 | 175 | xyz_encoding_final = self.xyz_encoding_final(xyz_) 176 | dir_encoding_input = torch.cat([xyz_encoding_final, input_dir_a], 1) 177 | dir_encoding = self.dir_encoding(dir_encoding_input) 178 | static_rgb = self.static_rgb(dir_encoding) # (B, 3) 179 | static = torch.cat([static_rgb, static_sigma], 1) # (B, 4) 180 | 181 | if not output_transient: 182 | return static 183 | 184 | transient_encoding_input = torch.cat([xyz_encoding_final, input_t], 1) 185 | transient_encoding = self.transient_encoding(transient_encoding_input) 186 | transient_sigma = self.transient_sigma(transient_encoding) # (B, 1) 187 | transient_rgb = self.transient_rgb(transient_encoding) # (B, 3) 188 | transient_beta = self.transient_beta(transient_encoding) # (B, 1) 189 | 190 | transient = torch.cat([transient_rgb, transient_sigma, 191 | transient_beta], 1) # (B, 5) 192 | 193 | return torch.cat([static, transient], 1) # (B, 9) 194 | -------------------------------------------------------------------------------- /losses.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | import math 4 | from torchvision import models 5 | import copy 6 | import torch.nn.functional as F 7 | 8 | 9 | class MSELoss(nn.Module): 10 | def __init__(self): 11 | super(MSELoss, self).__init__() 12 | self.loss = nn.MSELoss(reduction='mean') 13 | 14 | def forward(self, inputs, targets): 15 | loss = self.loss(inputs['rgb_coarse'], targets) 16 | if 'rgb_fine' in inputs: 17 | loss += self.loss(inputs['rgb_fine'], targets) 18 | 19 | return loss 20 | 21 | 22 | class FeatureLoss(torch.nn.Module): 23 | '''Given a content style reference images will find the style and content loss''' 24 | 25 | def __init__(self, 26 | style_img, 27 | style_weight, 28 | content_weight 29 | ) -> None: 30 | super(FeatureLoss, self).__init__() 31 | 32 | self.device = style_img.device 33 | 34 | self.style_weight = style_weight 35 | self.content_weight = content_weight 36 | 37 | content_layers_default = ['conv_4'] 38 | style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5'] 39 | normalization_mean_default = torch.tensor([0.485, 0.456, 0.406], device=self.device) 40 | normalization_std_default = torch.tensor([0.229, 0.224, 0.225], device=self.device) 41 | 42 | # Load the VGG 43 | # model_file = 'vgg19.pt' 44 | # if Path(model_file).is_file(): 45 | # print(f'Loading model {model_file}') 46 | # cnn = torch.load(model_file) 47 | # else: 48 | cnn = models.vgg19(pretrained=True).to(self.device) 49 | # torch.save(cnn, model_file) 50 | 51 | self.cnn = cnn.features.eval() 52 | 53 | self.style_model, self.style_losses, self.content_features = self.get_style_model_and_losses( 54 | self.cnn, 55 | style_img, 56 | normalization_mean=normalization_mean_default, 57 | normalization_std=normalization_std_default, 58 | content_layers=content_layers_default, 59 | style_layers=style_layers_default 60 | ) 61 | 62 | def forward(self, input_img, content_img): 63 | # numel_input = torch.numel(input_img) 64 | # numel_content = torch.numel(content_img) 65 | # assert numel_input == numel_content, 'Input image and content image must be in equal sizes!' 66 | # dim = int(math.sqrt(numel_input / 3)) 67 | # 68 | # input_img = input_img.view(dim, dim, 3).permute(2, 0, 1).unsqueeze(dim=0) 69 | # content_img = content_img.view(dim, dim, 3).permute(2, 0, 1).unsqueeze(dim=0) 70 | 71 | # collect feature loss tensors for the target/content image 72 | self.style_model(content_img) 73 | target_content_features = [cf.content_feature for cf in self.content_features] 74 | 75 | # another forward pass for the input image 76 | self.style_model(input_img) 77 | 78 | style_score = 0 79 | content_score = 0 80 | 81 | # style loss 82 | for sl in self.style_losses: 83 | style_score += sl.loss 84 | 85 | # content loss 86 | input_content_features = [cf.content_feature for cf in self.content_features] 87 | for in_cl_feat, target_cl_feat in zip(input_content_features, target_content_features): 88 | content_score += F.mse_loss(in_cl_feat, target_cl_feat) 89 | 90 | # weight the loss and combine 91 | style_score *= self.style_weight 92 | content_score *= self.content_weight 93 | 94 | loss = style_score + content_score 95 | 96 | return loss 97 | 98 | def get_style_model_and_losses(self, 99 | cnn, 100 | style_img, 101 | normalization_mean, 102 | normalization_std, 103 | content_layers, 104 | style_layers 105 | ): 106 | '''Build model to be used for style/content loss''' 107 | 108 | cnn = copy.deepcopy(cnn) 109 | 110 | # normalization module 111 | normalization = Normalization( 112 | normalization_mean, 113 | normalization_std 114 | ) 115 | 116 | # to have iterable access to a list of content features and style losses 117 | content_features = [] 118 | style_losses = [] 119 | 120 | # assuming that cnn is a nn.Sequential, we make a new nn.Sequential 121 | # to put in modules that are supposed to be activated sequentially 122 | model = nn.Sequential(normalization) 123 | 124 | i = 0 # increment every time we see a conv 125 | for layer in cnn.children(): 126 | if isinstance(layer, nn.Conv2d): 127 | i += 1 128 | name = 'conv_{}'.format(i) 129 | elif isinstance(layer, nn.ReLU): 130 | name = 'relu_{}'.format(i) 131 | # The in-place version doesn't play very nicely with the ContentLoss 132 | # and StyleLoss we insert below. So we replace with out-of-place 133 | # ones here. 134 | layer = nn.ReLU(inplace=False) 135 | elif isinstance(layer, nn.MaxPool2d): 136 | name = 'pool_{}'.format(i) 137 | elif isinstance(layer, nn.BatchNorm2d): 138 | name = 'bn_{}'.format(i) 139 | else: 140 | raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__)) 141 | 142 | model.add_module(name, layer) 143 | 144 | # add content loss to the model: 145 | if name in content_layers: 146 | # Get the feature map of the content image using the half built model 147 | content_feature = ContentFeature() 148 | model.add_module("content_feat_{}".format(i), content_feature) 149 | content_features.append(content_feature) 150 | 151 | # add style loss to the model: 152 | if name in style_layers: 153 | # add style loss: 154 | target_feature = model(style_img).detach() 155 | style_loss = StyleLoss(target_feature) 156 | model.add_module("style_loss_{}".format(i), style_loss) 157 | style_losses.append(style_loss) 158 | 159 | # now we trim off the layers after the last content and style losses 160 | for i in range(len(model) - 1, -1, -1): 161 | if isinstance(model[i], ContentFeature) or isinstance(model[i], StyleLoss): 162 | break 163 | 164 | model = model[:(i + 1)] 165 | 166 | return model, style_losses, content_features 167 | 168 | 169 | class ContentFeature(torch.nn.Module): 170 | '''Extract the feature map''' 171 | 172 | def __init__(self): 173 | super(ContentFeature, self).__init__() 174 | 175 | def forward(self, input): 176 | # Save the content feature 177 | self.content_feature = input 178 | return input 179 | 180 | 181 | class StyleLoss(torch.nn.Module): 182 | '''Compute the style loss using Gram matrices''' 183 | 184 | def __init__(self, target_feature): 185 | super(StyleLoss, self).__init__() 186 | self.target = self._gram_matrix(target_feature).detach() 187 | 188 | def forward(self, input): 189 | if self.target.device.type == 'cpu': 190 | # TODO avoid doing this 191 | self.target = self.target.to(self.device) 192 | 193 | G = self._gram_matrix(input) 194 | self.loss = F.mse_loss(G, self.target) 195 | return input 196 | 197 | def _gram_matrix(self, input): 198 | # a=batch size(=1) 199 | # b=number of feature maps 200 | # (c,d)=dimensions of a f. map (N=c*d) 201 | a, b, c, d = input.size() 202 | 203 | features = input.view(a * b, c * d) # resise F_XL into \hat F_XL 204 | 205 | G = torch.mm(features, features.t()) # compute the gram product 206 | 207 | # 'normalize' the gram matrix by dividing by size of the feature map 208 | return G.div(a * b * c * d) 209 | 210 | 211 | class Normalization(torch.nn.Module): 212 | '''VGG Normalisation (pretrained models expect this)''' 213 | 214 | def __init__(self, mean, std): 215 | super(Normalization, self).__init__() 216 | # .view the mean and std to make them [C x 1 x 1] so that they can 217 | # directly work with image Tensor of shape [B x C x H x W]. 218 | # B is batch size. C is number of channels. H is height and W is width. 219 | 220 | self.device = torch.device('cuda') 221 | 222 | self.mean = mean.view(-1, 1, 1).to(self.device) 223 | self.std = std.view(-1, 1, 1).to(self.device) 224 | 225 | def forward(self, img): 226 | # normalize img 227 | if self.mean.device.type == 'cpu': 228 | # TODO avoid doing this 229 | self.mean = self.mean.to(self.device) 230 | self.std = self.std.to(self.device) 231 | 232 | return (img - self.mean) / self.std 233 | 234 | 235 | loss_dict = {'nerfw': MSELoss, 236 | 'style': FeatureLoss} 237 | -------------------------------------------------------------------------------- /datasets/blender.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import Dataset 2 | import json 3 | import numpy as np 4 | import os 5 | from PIL import Image, ImageDraw 6 | from torchvision import transforms as T 7 | 8 | from .ray_utils import * 9 | 10 | 11 | def add_perturbation(img, perturbation, seed): 12 | if 'color' in perturbation: 13 | np.random.seed(seed) 14 | img_np = np.array(img)/255.0 15 | s = np.random.uniform(0.8, 1.2, size=3) 16 | b = np.random.uniform(-0.2, 0.2, size=3) 17 | img_np[..., :3] = np.clip(s*img_np[..., :3]+b, 0, 1) 18 | img = Image.fromarray((255*img_np).astype(np.uint8)) 19 | if 'occ' in perturbation: 20 | draw = ImageDraw.Draw(img) 21 | np.random.seed(seed) 22 | left = np.random.randint(200, 400) 23 | top = np.random.randint(200, 400) 24 | for i in range(10): 25 | np.random.seed(10*seed+i) 26 | random_color = tuple(np.random.choice(range(256), 3)) 27 | draw.rectangle(((left+20*i, top), (left+20*(i+1), top+200)), 28 | fill=random_color) 29 | return img 30 | 31 | 32 | class BlenderDataset(Dataset): 33 | def __init__(self, root_dir, split='train', img_wh=(400, 400), perturbation=[], is_learning_density=True, render_patches=False): 34 | self.root_dir = root_dir 35 | self.split = split 36 | assert img_wh[0] == img_wh[1], 'image width must equal image height!' 37 | self.img_wh = img_wh 38 | self.define_transforms() 39 | 40 | self.is_learning_density = is_learning_density 41 | self.render_patches = render_patches 42 | 43 | assert set(perturbation).issubset({"color", "occ"}), \ 44 | 'Only "color" and "occ" perturbations are supported!' 45 | self.perturbation = perturbation 46 | self.read_meta() 47 | self.white_back = True 48 | 49 | def set_params(self, is_learning_density, render_patches): 50 | self.is_learning_density = is_learning_density 51 | self.render_patches = render_patches 52 | 53 | def read_meta(self): 54 | with open(os.path.join(self.root_dir, 55 | f"transforms_{self.split.split('_')[-1]}.json"), 'r') as f: 56 | self.meta = json.load(f) 57 | 58 | w, h = self.img_wh 59 | self.focal = 0.5*800/np.tan(0.5*self.meta['camera_angle_x']) # original focal length 60 | # when W=800 61 | 62 | self.focal *= self.img_wh[0]/800 # modify focal length to match size self.img_wh 63 | 64 | # bounds, common for all scenes 65 | self.near = 2.0 66 | self.far = 6.0 67 | self.bounds = np.array([self.near, self.far]) 68 | 69 | # ray directions for all pixels, same for all images (same H, W, focal) 70 | self.directions = \ 71 | get_ray_directions(h, w, self.focal) # (h, w, 3) 72 | 73 | if self.split == 'train': # create buffer of all rays and rgb data 74 | self.image_paths = [] 75 | self.poses = [] 76 | self.all_rays = [] 77 | self.all_rgbs = [] 78 | for t, frame in enumerate(self.meta['frames']): 79 | pose = np.array(frame['transform_matrix'])[:3, :4] 80 | self.poses += [pose] 81 | c2w = torch.FloatTensor(pose) 82 | 83 | image_path = os.path.join(self.root_dir, f"{frame['file_path']}.png") 84 | self.image_paths += [image_path] 85 | img = Image.open(image_path) 86 | if t != 0: # perturb everything except the first image. 87 | # cf. Section D in the supplementary material 88 | img = add_perturbation(img, self.perturbation, t) 89 | 90 | img = img.resize(self.img_wh, Image.LANCZOS) 91 | img = self.transform(img) # (4, h, w) 92 | img = img.view(4, -1).permute(1, 0) # (h*w, 4) RGBA 93 | img = img[:, :3]*img[:, -1:] + (1-img[:, -1:]) # blend A to RGB 94 | self.all_rgbs += [img] 95 | 96 | rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3) 97 | rays_t = t * torch.ones(len(rays_o), 1) 98 | 99 | self.all_rays += [torch.cat([rays_o, rays_d, 100 | self.near*torch.ones_like(rays_o[:, :1]), 101 | self.far*torch.ones_like(rays_o[:, :1]), 102 | rays_t], 103 | 1)] # (h*w, 8) 104 | 105 | self.all_rays = torch.cat(self.all_rays, 0) # (len(self.meta['frames])*h*w, 3) 106 | self.all_rgbs = torch.cat(self.all_rgbs, 0) # (len(self.meta['frames])*h*w, 3) 107 | 108 | def define_transforms(self): 109 | self.transform = T.ToTensor() 110 | 111 | def __len__(self): 112 | if self.split == 'train': 113 | if self.is_learning_density: 114 | return len(self.all_rays) 115 | else: 116 | return len(self.all_rays) // 2500 if self.render_patches else 100 117 | if self.split == 'val': 118 | return 8 # only validate 8 images (to support <=8 gpus) 119 | return len(self.meta['frames']) 120 | 121 | def __getitem__(self, idx): 122 | if self.split == 'train': # use data in the buffers 123 | if self.is_learning_density: 124 | sample = {'rays': self.all_rays[idx, :8], 125 | 'ts': self.all_rays[idx, 8].long(), 126 | 'rgbs': self.all_rgbs[idx]} 127 | else: 128 | if self.render_patches: 129 | img_wh = self.img_wh[0] 130 | sqrt_n_of_patches = (img_wh // 50) 131 | n_of_patches = sqrt_n_of_patches ** 2 132 | 133 | img_idx = idx // n_of_patches 134 | rays = self.all_rays[img_idx * (img_wh ** 2):(img_idx + 1) * (img_wh ** 2), :8] 135 | rays = rays.view(img_wh, img_wh, 8) 136 | ts = self.all_rays[img_idx * (img_wh ** 2):(img_idx + 1) * (img_wh ** 2), 8] 137 | ts = ts.view(img_wh, img_wh) 138 | rgbs = self.all_rgbs[img_idx * (img_wh ** 2):(img_idx + 1) * (img_wh ** 2)] 139 | rgbs = rgbs.view(img_wh, img_wh, 3) 140 | 141 | patch_idx = idx % n_of_patches 142 | i, j = patch_idx // sqrt_n_of_patches, patch_idx % sqrt_n_of_patches # patch row and column 143 | sample = {'rays': rays[i * 50:(i + 1) * 50, j * 50:(j + 1) * 50, :].reshape(2500, 8), 144 | 'ts': ts[i * 50:(i + 1) * 50, j * 50:(j + 1) * 50].flatten().long(), 145 | 'rgbs': rgbs[i * 50:(i + 1) * 50, j * 50:(j + 1) * 50, :].reshape(2500, 3)} 146 | else: 147 | img_size = self.img_wh[0] ** 2 148 | 149 | sample = {'rays': self.all_rays[img_size * idx: img_size * (idx + 1), :8], 150 | 'ts': self.all_rays[img_size * idx: img_size * (idx + 1), 8].long(), 151 | 'rgbs': self.all_rgbs[img_size * idx: img_size * (idx + 1)]} 152 | 153 | else: # create data for each image separately 154 | frame = self.meta['frames'][idx] 155 | c2w = torch.FloatTensor(frame['transform_matrix'])[:3, :4] 156 | t = idx # transient embedding index, 0 for val and test (no perturbation) 157 | 158 | img = Image.open(os.path.join(self.root_dir, f"{frame['file_path']}.png")) 159 | if self.split == 'test_train' and idx != 0: 160 | t = idx 161 | img = add_perturbation(img, self.perturbation, idx) 162 | img = img.resize(self.img_wh, Image.LANCZOS) 163 | img = self.transform(img) # (4, H, W) 164 | valid_mask = (img[-1]>0).flatten() # (H*W) valid color area 165 | img = img.view(4, -1).permute(1, 0) # (H*W, 4) RGBA 166 | img = img[:, :3]*img[:, -1:] + (1-img[:, -1:]) # blend A to RGB 167 | 168 | rays_o, rays_d = get_rays(self.directions, c2w) 169 | 170 | rays = torch.cat([rays_o, rays_d, 171 | self.near*torch.ones_like(rays_o[:, :1]), 172 | self.far*torch.ones_like(rays_o[:, :1])], 173 | 1) # (H*W, 8) 174 | 175 | sample = {'rays': rays, 176 | 'ts': t * torch.ones(len(rays), dtype=torch.long), 177 | 'rgbs': img, 178 | 'c2w': c2w, 179 | 'valid_mask': valid_mask} 180 | 181 | if self.split == 'test_train' and self.perturbation: 182 | # append the original (unperturbed) image 183 | img = Image.open(os.path.join(self.root_dir, f"{frame['file_path']}.png")) 184 | img = img.resize(self.img_wh, Image.LANCZOS) 185 | img = self.transform(img) # (4, H, W) 186 | valid_mask = (img[-1]>0).flatten() # (H*W) valid color area 187 | img = img.view(4, -1).permute(1, 0) # (H*W, 4) RGBA 188 | img = img[:, :3]*img[:, -1:] + (1-img[:, -1:]) # blend A to RGB 189 | sample['original_rgbs'] = img 190 | sample['original_valid_mask'] = valid_mask 191 | 192 | return sample -------------------------------------------------------------------------------- /models/rendering.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from einops import rearrange, reduce, repeat 3 | 4 | __all__ = ['render_rays'] 5 | 6 | 7 | def sample_pdf(bins, weights, N_importance, det=False, eps=1e-5): 8 | """ 9 | Sample @N_importance samples from @bins with distribution defined by @weights. 10 | Inputs: 11 | bins: (N_rays, N_samples_+1) where N_samples_ is "the number of coarse samples per ray - 2" 12 | weights: (N_rays, N_samples_) 13 | N_importance: the number of samples to draw from the distribution 14 | det: deterministic or not 15 | eps: a small number to prevent division by zero 16 | Outputs: 17 | samples: the sampled samples 18 | """ 19 | N_rays, N_samples_ = weights.shape 20 | weights = weights + eps # prevent division by zero (don't do inplace op!) 21 | pdf = weights / reduce(weights, 'n1 n2 -> n1 1', 'sum') # (N_rays, N_samples_) 22 | cdf = torch.cumsum(pdf, -1) # (N_rays, N_samples), cumulative distribution function 23 | cdf = torch.cat([torch.zeros_like(cdf[: ,:1]), cdf], -1) # (N_rays, N_samples_+1) 24 | # padded to 0~1 inclusive 25 | 26 | if det: 27 | u = torch.linspace(0, 1, N_importance, device=bins.device) 28 | u = u.expand(N_rays, N_importance) 29 | else: 30 | u = torch.rand(N_rays, N_importance, device=bins.device) 31 | u = u.contiguous() 32 | 33 | inds = torch.searchsorted(cdf, u, right=True) 34 | below = torch.clamp_min(inds-1, 0) 35 | above = torch.clamp_max(inds, N_samples_) 36 | 37 | inds_sampled = rearrange(torch.stack([below, above], -1), 'n1 n2 c -> n1 (n2 c)', c=2) 38 | cdf_g = rearrange(torch.gather(cdf, 1, inds_sampled), 'n1 (n2 c) -> n1 n2 c', c=2) 39 | bins_g = rearrange(torch.gather(bins, 1, inds_sampled), 'n1 (n2 c) -> n1 n2 c', c=2) 40 | 41 | denom = cdf_g[...,1]-cdf_g[...,0] 42 | denom[denom (n1 n2) c', c=3) 99 | 100 | # Perform model inference to get rgb and raw sigma 101 | B = xyz_.shape[0] 102 | out_chunks = [] 103 | if typ=='coarse' and test_time: 104 | for i in range(0, B, chunk): 105 | xyz_embedded = embedding_xyz(xyz_[i:i+chunk]) 106 | out_chunks += [model(xyz_embedded, sigma_only=True)] 107 | out = torch.cat(out_chunks, 0) 108 | static_sigmas = rearrange(out, '(n1 n2) 1 -> n1 n2', n1=N_rays, n2=N_samples_) 109 | else: # infer rgb and sigma and others 110 | dir_embedded_ = repeat(dir_embedded, 'n1 c -> (n1 n2) c', n2=N_samples_) 111 | # create other necessary inputs 112 | if model.encode_appearance: 113 | a_embedded_ = repeat(a_embedded, 'n1 c -> (n1 n2) c', n2=N_samples_) 114 | if model.encode_transient: 115 | t_embedded_ = repeat(t_embedded, 'n1 c -> (n1 n2) c', n2=N_samples_) 116 | for i in range(0, B, chunk): 117 | # inputs for original NeRF 118 | inputs = [embedding_xyz(xyz_[i:i+chunk]), dir_embedded_[i:i+chunk]] 119 | # additional inputs for NeRF-W 120 | if model.encode_appearance: 121 | inputs += [a_embedded_[i:i+chunk]] 122 | if model.encode_transient: 123 | inputs += [t_embedded_[i:i+chunk]] 124 | # TODO: add output_transient option in the kwargs 125 | out_chunks += [model(torch.cat(inputs, 1), 126 | output_transient=(typ=='fine' and model.encode_transient))] 127 | 128 | out = torch.cat(out_chunks, 0) 129 | out = rearrange(out, '(n1 n2) c -> n1 n2 c', n1=N_rays, n2=N_samples_) 130 | static_rgbs = out[..., :3] # (N_rays, N_samples_, 3) 131 | static_sigmas = out[..., 3] # (N_rays, N_samples_) 132 | if typ == 'fine' and model.encode_transient: 133 | transient_rgbs = out[..., 4:7] 134 | transient_sigmas = out[..., 7] 135 | transient_betas = out[..., 8] 136 | 137 | # Convert these values using volume rendering 138 | deltas = z_vals[:, 1:] - z_vals[:, :-1] # (N_rays, N_samples_-1) 139 | delta_inf = 1e2 * torch.ones_like(deltas[:, :1]) # (N_rays, 1) the last delta is infinity 140 | deltas = torch.cat([deltas, delta_inf], -1) # (N_rays, N_samples_) 141 | 142 | if model.encode_transient: 143 | static_alphas = 1-torch.exp(-deltas*static_sigmas) 144 | transient_alphas = 1-torch.exp(-deltas*transient_sigmas) 145 | alphas = 1-torch.exp(-deltas*(static_sigmas+transient_sigmas)) 146 | else: 147 | noise = torch.randn_like(static_sigmas) * noise_std 148 | alphas = 1-torch.exp(-deltas*torch.relu(static_sigmas+noise)) 149 | 150 | alphas_shifted = \ 151 | torch.cat([torch.ones_like(alphas[:, :1]), 1-alphas], -1) # [1, 1-a1, 1-a2, ...] 152 | transmittance = torch.cumprod(alphas_shifted[:, :-1], -1) # [1, 1-a1, (1-a1)(1-a2), ...] 153 | 154 | if model.encode_transient: 155 | static_weights = static_alphas * transmittance 156 | transient_weights = transient_alphas * transmittance 157 | 158 | weights = alphas * transmittance 159 | weights_sum = reduce(weights, 'n1 n2 -> n1', 'sum') 160 | 161 | results[f'weights_{typ}'] = weights 162 | results[f'opacity_{typ}'] = weights_sum 163 | if model.encode_transient: 164 | results['transient_sigmas'] = transient_sigmas 165 | if test_time and typ == 'coarse': 166 | return 167 | 168 | 169 | if model.encode_transient: 170 | static_rgb_map = reduce(rearrange(static_weights, 'n1 n2 -> n1 n2 1')*static_rgbs, 171 | 'n1 n2 c -> n1 c', 'sum') 172 | if white_back: 173 | static_rgb_map += 1-rearrange(weights_sum, 'n -> n 1') 174 | 175 | transient_rgb_map = \ 176 | reduce(rearrange(transient_weights, 'n1 n2 -> n1 n2 1')*transient_rgbs, 177 | 'n1 n2 c -> n1 c', 'sum') 178 | results['beta'] = model.beta_min + \ 179 | reduce(transient_weights*transient_betas, 'n1 n2 -> n1', 'sum') 180 | results[f'rgb_{typ}'] = static_rgb_map + transient_rgb_map 181 | 182 | if test_time: 183 | # Compute also static and transient rgbs when only one field exists. 184 | # The result is different from when both fields exist, since the transimttance 185 | # will change. 186 | static_alphas_shifted = \ 187 | torch.cat([torch.ones_like(static_alphas[:, :1]), 1-static_alphas], -1) 188 | static_transmittance = torch.cumprod(static_alphas_shifted[:, :-1], -1) 189 | static_weights_ = static_alphas * static_transmittance 190 | static_rgb_map_ = \ 191 | reduce(rearrange(static_weights_, 'n1 n2 -> n1 n2 1')*static_rgbs, 192 | 'n1 n2 c -> n1 c', 'sum') 193 | if white_back: 194 | static_rgb_map_ += 1-rearrange(weights_sum, 'n -> n 1') 195 | results['rgb_fine_static'] = static_rgb_map_ 196 | results['depth_fine_static'] = \ 197 | reduce(static_weights_*z_vals, 'n1 n2 -> n1', 'sum') 198 | 199 | transient_alphas_shifted = \ 200 | torch.cat([torch.ones_like(transient_alphas[:, :1]), 1-transient_alphas], -1) 201 | transient_transmittance = torch.cumprod(transient_alphas_shifted[:, :-1], -1) 202 | transient_weights_ = transient_alphas * transient_transmittance 203 | results['rgb_fine_transient'] = \ 204 | reduce(rearrange(transient_weights_, 'n1 n2 -> n1 n2 1')*transient_rgbs, 205 | 'n1 n2 c -> n1 c', 'sum') 206 | results['depth_fine_transient'] = \ 207 | reduce(transient_weights_*z_vals, 'n1 n2 -> n1', 'sum') 208 | else: # no transient field 209 | rgb_map = reduce(rearrange(weights, 'n1 n2 -> n1 n2 1')*static_rgbs, 210 | 'n1 n2 c -> n1 c', 'sum') 211 | if white_back: 212 | rgb_map += 1-rearrange(weights_sum, 'n -> n 1') 213 | results[f'rgb_{typ}'] = rgb_map 214 | 215 | results[f'depth_{typ}'] = reduce(weights*z_vals, 'n1 n2 -> n1', 'sum') 216 | return 217 | 218 | embedding_xyz, embedding_dir = embeddings['xyz'], embeddings['dir'] 219 | 220 | # Decompose the inputs 221 | N_rays = rays.shape[0] 222 | rays_o, rays_d = rays[:, 0:3], rays[:, 3:6] # both (N_rays, 3) 223 | near, far = rays[:, 6:7], rays[:, 7:8] # both (N_rays, 1) 224 | # Embed direction 225 | dir_embedded = embedding_dir(kwargs.get('view_dir', rays_d)) 226 | 227 | rays_o = rearrange(rays_o, 'n1 c -> n1 1 c') 228 | rays_d = rearrange(rays_d, 'n1 c -> n1 1 c') 229 | 230 | # Sample depth points 231 | z_steps = torch.linspace(0, 1, N_samples, device=rays.device) 232 | if not use_disp: # use linear sampling in depth space 233 | z_vals = near * (1-z_steps) + far * z_steps 234 | else: # use linear sampling in disparity space 235 | z_vals = 1/(1/near * (1-z_steps) + 1/far * z_steps) 236 | 237 | z_vals = z_vals.expand(N_rays, N_samples) 238 | 239 | if perturb > 0: # perturb sampling depths (z_vals) 240 | z_vals_mid = 0.5 * (z_vals[: ,:-1] + z_vals[: ,1:]) # (N_rays, N_samples-1) interval mid points 241 | # get intervals between samples 242 | upper = torch.cat([z_vals_mid, z_vals[: ,-1:]], -1) 243 | lower = torch.cat([z_vals[: ,:1], z_vals_mid], -1) 244 | 245 | perturb_rand = perturb * torch.rand_like(z_vals) 246 | z_vals = lower + (upper - lower) * perturb_rand 247 | 248 | xyz_coarse = rays_o + rays_d * rearrange(z_vals, 'n1 n2 -> n1 n2 1') 249 | 250 | results = {} 251 | inference(results, models['coarse'], xyz_coarse, z_vals, test_time, **kwargs) 252 | 253 | if N_importance > 0: # sample points for fine model 254 | z_vals_mid = 0.5 * (z_vals[: ,:-1] + z_vals[: ,1:]) # (N_rays, N_samples-1) interval mid points 255 | z_vals_ = sample_pdf(z_vals_mid, results['weights_coarse'][:, 1:-1].detach(), 256 | N_importance, det=(perturb==0)) 257 | # detach so that grad doesn't propogate to weights_coarse from here 258 | z_vals = torch.sort(torch.cat([z_vals, z_vals_], -1), -1)[0] 259 | xyz_fine = rays_o + rays_d * rearrange(z_vals, 'n1 n2 -> n1 n2 1') 260 | 261 | model = models['fine'] 262 | if model.encode_appearance: 263 | a_embedded = embeddings['a'](ts) 264 | if model.encode_transient: 265 | t_embedded = embeddings['t'](ts) 266 | inference(results, model, xyz_fine, z_vals, test_time, **kwargs) 267 | 268 | return results -------------------------------------------------------------------------------- /datasets/llff.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.utils.data import Dataset 3 | import glob 4 | import numpy as np 5 | import os 6 | from PIL import Image 7 | from torchvision import transforms as T 8 | 9 | from .ray_utils import * 10 | 11 | 12 | def normalize(v): 13 | """Normalize a vector.""" 14 | return v/np.linalg.norm(v) 15 | 16 | 17 | def average_poses(poses): 18 | """ 19 | Calculate the average pose, which is then used to center all poses 20 | using @center_poses. Its computation is as follows: 21 | 1. Compute the center: the average of pose centers. 22 | 2. Compute the z axis: the normalized average z axis. 23 | 3. Compute axis y': the average y axis. 24 | 4. Compute x' = y' cross product z, then normalize it as the x axis. 25 | 5. Compute the y axis: z cross product x. 26 | 27 | Note that at step 3, we cannot directly use y' as y axis since it's 28 | not necessarily orthogonal to z axis. We need to pass from x to y. 29 | 30 | Inputs: 31 | poses: (N_images, 3, 4) 32 | 33 | Outputs: 34 | pose_avg: (3, 4) the average pose 35 | """ 36 | # 1. Compute the center 37 | center = poses[..., 3].mean(0) # (3) 38 | 39 | # 2. Compute the z axis 40 | z = normalize(poses[..., 2].mean(0)) # (3) 41 | 42 | # 3. Compute axis y' (no need to normalize as it's not the final output) 43 | y_ = poses[..., 1].mean(0) # (3) 44 | 45 | # 4. Compute the x axis 46 | x = normalize(np.cross(y_, z)) # (3) 47 | 48 | # 5. Compute the y axis (as z and x are normalized, y is already of norm 1) 49 | y = np.cross(z, x) # (3) 50 | 51 | pose_avg = np.stack([x, y, z, center], 1) # (3, 4) 52 | 53 | return pose_avg 54 | 55 | 56 | def center_poses(poses): 57 | """ 58 | Center the poses so that we can use NDC. 59 | See https://github.com/bmild/nerf/issues/34 60 | 61 | Inputs: 62 | poses: (N_images, 3, 4) 63 | 64 | Outputs: 65 | poses_centered: (N_images, 3, 4) the centered poses 66 | pose_avg: (3, 4) the average pose 67 | """ 68 | 69 | pose_avg = average_poses(poses) # (3, 4) 70 | pose_avg_homo = np.eye(4) 71 | pose_avg_homo[:3] = pose_avg # convert to homogeneous coordinate for faster computation 72 | # by simply adding 0, 0, 0, 1 as the last row 73 | last_row = np.tile(np.array([0, 0, 0, 1]), (len(poses), 1, 1)) # (N_images, 1, 4) 74 | poses_homo = \ 75 | np.concatenate([poses, last_row], 1) # (N_images, 4, 4) homogeneous coordinate 76 | 77 | poses_centered = np.linalg.inv(pose_avg_homo) @ poses_homo # (N_images, 4, 4) 78 | poses_centered = poses_centered[:, :3] # (N_images, 3, 4) 79 | 80 | return poses_centered, pose_avg 81 | 82 | 83 | def create_spiral_poses(radii, focus_depth, n_poses=120): 84 | """ 85 | Computes poses that follow a spiral path for rendering purpose. 86 | See https://github.com/Fyusion/LLFF/issues/19 87 | In particular, the path looks like: 88 | https://tinyurl.com/ybgtfns3 89 | 90 | Inputs: 91 | radii: (3) radii of the spiral for each axis 92 | focus_depth: float, the depth that the spiral poses look at 93 | n_poses: int, number of poses to create along the path 94 | 95 | Outputs: 96 | poses_spiral: (n_poses, 3, 4) the poses in the spiral path 97 | """ 98 | 99 | poses_spiral = [] 100 | for t in np.linspace(0, 4*np.pi, n_poses+1)[:-1]: # rotate 4pi (2 rounds) 101 | # the parametric function of the spiral (see the interactive web) 102 | center = np.array([np.cos(t), -np.sin(t), -np.sin(0.5*t)]) * radii 103 | 104 | # the viewing z axis is the vector pointing from the @focus_depth plane 105 | # to @center 106 | z = normalize(center - np.array([0, 0, -focus_depth])) 107 | 108 | # compute other axes as in @average_poses 109 | y_ = np.array([0, 1, 0]) # (3) 110 | x = normalize(np.cross(y_, z)) # (3) 111 | y = np.cross(z, x) # (3) 112 | 113 | poses_spiral += [np.stack([x, y, z, center], 1)] # (3, 4) 114 | 115 | return np.stack(poses_spiral, 0) # (n_poses, 3, 4) 116 | 117 | 118 | def create_spheric_poses(radius, n_poses=120): 119 | """ 120 | Create circular poses around z axis. 121 | Inputs: 122 | radius: the (negative) height and the radius of the circle. 123 | 124 | Outputs: 125 | spheric_poses: (n_poses, 3, 4) the poses in the circular path 126 | """ 127 | def spheric_pose(theta, phi, radius): 128 | trans_t = lambda t : np.array([ 129 | [1,0,0,0], 130 | [0,1,0,-0.9*t], 131 | [0,0,1,t], 132 | [0,0,0,1], 133 | ]) 134 | 135 | rot_phi = lambda phi : np.array([ 136 | [1,0,0,0], 137 | [0,np.cos(phi),-np.sin(phi),0], 138 | [0,np.sin(phi), np.cos(phi),0], 139 | [0,0,0,1], 140 | ]) 141 | 142 | rot_theta = lambda th : np.array([ 143 | [np.cos(th),0,-np.sin(th),0], 144 | [0,1,0,0], 145 | [np.sin(th),0, np.cos(th),0], 146 | [0,0,0,1], 147 | ]) 148 | 149 | c2w = rot_theta(theta) @ rot_phi(phi) @ trans_t(radius) 150 | c2w = np.array([[-1,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,0,1]]) @ c2w 151 | return c2w[:3] 152 | 153 | spheric_poses = [] 154 | for th in np.linspace(0, 2*np.pi, n_poses+1)[:-1]: 155 | spheric_poses += [spheric_pose(th, -np.pi/5, radius)] # 36 degree view downwards 156 | return np.stack(spheric_poses, 0) 157 | 158 | 159 | class LLFFDataset(Dataset): 160 | def __init__(self, root_dir, split='train', img_wh=(504, 378), spheric_poses=False, val_num=1): 161 | """ 162 | spheric_poses: whether the images are taken in a spheric inward-facing manner 163 | default: False (forward-facing) 164 | val_num: number of val images (used for multigpu training, validate same image for all gpus) 165 | """ 166 | self.root_dir = root_dir 167 | self.split = split 168 | self.img_wh = img_wh 169 | self.spheric_poses = spheric_poses 170 | self.val_num = max(1, val_num) # at least 1 171 | self.define_transforms() 172 | 173 | self.read_meta() 174 | self.white_back = False 175 | 176 | def read_meta(self): 177 | poses_bounds = np.load(os.path.join(self.root_dir, 178 | 'poses_bounds.npy')) # (N_images, 17) 179 | self.image_paths = sorted(glob.glob(os.path.join(self.root_dir, 'images/*'))) 180 | # load full resolution image then resize 181 | if self.split in ['train', 'val']: 182 | assert len(poses_bounds) == len(self.image_paths), \ 183 | 'Mismatch between number of images and number of poses! Please rerun COLMAP!' 184 | 185 | poses = poses_bounds[:, :15].reshape(-1, 3, 5) # (N_images, 3, 5) 186 | self.bounds = poses_bounds[:, -2:] # (N_images, 2) 187 | 188 | # Step 1: rescale focal length according to training resolution 189 | H, W, self.focal = poses[0, :, -1] # original intrinsics, same for all images 190 | # assert H*self.img_wh[0] == W*self.img_wh[1], \ 191 | # f'You must set @img_wh to have the same aspect ratio as ({W}, {H}) !' 192 | 193 | self.focal *= self.img_wh[0]/W 194 | 195 | # Step 2: correct poses 196 | # Original poses has rotation in form "down right back", change to "right up back" 197 | # See https://github.com/bmild/nerf/issues/34 198 | poses = np.concatenate([poses[..., 1:2], -poses[..., :1], poses[..., 2:4]], -1) 199 | # (N_images, 3, 4) exclude H, W, focal 200 | self.poses, self.pose_avg = center_poses(poses) 201 | distances_from_center = np.linalg.norm(self.poses[..., 3], axis=1) 202 | val_idx = np.argmin(distances_from_center) # choose val image as the closest to 203 | # center image 204 | 205 | # Step 3: correct scale so that the nearest depth is at a little more than 1.0 206 | # See https://github.com/bmild/nerf/issues/34 207 | near_original = self.bounds.min() 208 | scale_factor = near_original*0.75 # 0.75 is the default parameter 209 | # the nearest depth is at 1/0.75=1.33 210 | self.bounds /= scale_factor 211 | self.poses[..., 3] /= scale_factor 212 | 213 | # ray directions for all pixels, same for all images (same H, W, focal) 214 | self.directions = \ 215 | get_ray_directions(self.img_wh[1], self.img_wh[0], self.focal) # (H, W, 3) 216 | 217 | if self.split == 'train': # create buffer of all rays and rgb data 218 | # use first N_images-1 to train, the LAST is val 219 | self.all_rays = [] 220 | self.all_rgbs = [] 221 | for i, image_path in enumerate(self.image_paths): 222 | if i == val_idx: # exclude the val image 223 | continue 224 | c2w = torch.FloatTensor(self.poses[i]) 225 | 226 | img = Image.open(image_path).convert('RGB') 227 | assert img.size[1]*self.img_wh[0] == img.size[0]*self.img_wh[1], \ 228 | f'''{image_path} has different aspect ratio than img_wh, 229 | please check your data!''' 230 | img = img.resize(self.img_wh, Image.LANCZOS) 231 | img = self.transform(img) # (3, h, w) 232 | img = img.view(3, -1).permute(1, 0) # (h*w, 3) RGB 233 | self.all_rgbs += [img] 234 | 235 | rays_o, rays_d = get_rays(self.directions, c2w) # both (h*w, 3) 236 | if not self.spheric_poses: 237 | near, far = 0, 1 238 | rays_o, rays_d = get_ndc_rays(self.img_wh[1], self.img_wh[0], 239 | self.focal, 1.0, rays_o, rays_d) 240 | # near plane is always at 1.0 241 | # near and far in NDC are always 0 and 1 242 | # See https://github.com/bmild/nerf/issues/34 243 | else: 244 | near = self.bounds.min() 245 | far = min(8 * near, self.bounds.max()) # focus on central object only 246 | 247 | self.all_rays += [torch.cat([rays_o, rays_d, 248 | near*torch.ones_like(rays_o[:, :1]), 249 | far*torch.ones_like(rays_o[:, :1])], 250 | 1)] # (h*w, 8) 251 | 252 | self.all_rays = torch.cat(self.all_rays, 0) # ((N_images-1)*h*w, 8) 253 | self.all_rgbs = torch.cat(self.all_rgbs, 0) # ((N_images-1)*h*w, 3) 254 | 255 | elif self.split == 'val': 256 | print('val image is', self.image_paths[val_idx]) 257 | self.c2w_val = self.poses[val_idx] 258 | self.image_path_val = self.image_paths[val_idx] 259 | 260 | else: # for testing, create a parametric rendering path 261 | if self.split.endswith('train'): # test on training set 262 | self.poses_test = self.poses 263 | elif not self.spheric_poses: 264 | focus_depth = 3.5 # hardcoded, this is numerically close to the formula 265 | # given in the original repo. Mathematically if near=1 266 | # and far=infinity, then this number will converge to 4 267 | radii = np.percentile(np.abs(self.poses[..., 3]), 90, axis=0) 268 | self.poses_test = create_spiral_poses(radii, focus_depth) 269 | else: 270 | radius = 1.1 * self.bounds.min() 271 | self.poses_test = create_spheric_poses(radius) 272 | 273 | def define_transforms(self): 274 | self.transform = T.ToTensor() 275 | 276 | def __len__(self): 277 | if self.split == 'train': 278 | return len(self.all_rays) 279 | if self.split == 'val': 280 | return self.val_num 281 | return len(self.poses_test) 282 | 283 | def __getitem__(self, idx): 284 | if self.split == 'train': # use data in the buffers 285 | sample = {'rays': self.all_rays[idx], 286 | 'rgbs': self.all_rgbs[idx]} 287 | 288 | else: 289 | if self.split == 'val': 290 | c2w = torch.FloatTensor(self.c2w_val) 291 | else: 292 | c2w = torch.FloatTensor(self.poses_test[idx]) 293 | 294 | rays_o, rays_d = get_rays(self.directions, c2w) 295 | if not self.spheric_poses: 296 | near, far = 0, 1 297 | rays_o, rays_d = get_ndc_rays(self.img_wh[1], self.img_wh[0], 298 | self.focal, 1.0, rays_o, rays_d) 299 | else: 300 | near = self.bounds.min() 301 | far = min(8 * near, self.bounds.max()) 302 | 303 | rays = torch.cat([rays_o, rays_d, 304 | near*torch.ones_like(rays_o[:, :1]), 305 | far*torch.ones_like(rays_o[:, :1])], 306 | 1) # (h*w, 8) 307 | 308 | sample = {'rays': rays, 309 | 'c2w': c2w} 310 | 311 | if self.split == 'val': 312 | img = Image.open(self.image_path_val).convert('RGB') 313 | img = img.resize(self.img_wh, Image.LANCZOS) 314 | img = self.transform(img) # (3, h, w) 315 | img = img.view(3, -1).permute(1, 0) # (h*w, 3) 316 | sample['rgbs'] = img 317 | 318 | return sample 319 | -------------------------------------------------------------------------------- /pipeline.py: -------------------------------------------------------------------------------- 1 | from opt import get_opts 2 | from collections import defaultdict 3 | from torch.utils.data import DataLoader 4 | from datasets import dataset_dict 5 | from models.nerf import * 6 | from models.rendering import * 7 | from utils import * 8 | from losses import loss_dict 9 | from metrics import * 10 | from utils.logger import Logger 11 | import math 12 | import matplotlib.pyplot as plt 13 | import os 14 | import torchvision.transforms as transforms 15 | 16 | 17 | def show(img): 18 | plt.imshow(img.detach().cpu().numpy()) 19 | plt.show() 20 | 21 | 22 | def image_loader(image_name, imsize): 23 | image = Image.open(image_name) 24 | loader = transforms.Compose([ 25 | transforms.Resize(imsize), # scale imported image 26 | transforms.ToTensor()] # transform it into a torch tensor 27 | ) 28 | 29 | # fake batch dimension required to fit network's input dimensions 30 | image = loader(image).unsqueeze(0) 31 | return image.to(torch.float) 32 | 33 | 34 | class Pipeline: 35 | def __init__(self, hparams, **kwargs): 36 | super().__init__() 37 | 38 | self.logger = Logger() 39 | torch.manual_seed(1337) 40 | 41 | self.hparams = hparams 42 | self.device = torch.device('cuda') if hparams.use_gpu else torch.device('cpu') 43 | 44 | self.embeddings = { 45 | 'xyz': PosEmbedding(hparams.N_emb_xyz - 1, hparams.N_emb_xyz).to(self.device), 46 | 'dir': PosEmbedding(hparams.N_emb_dir - 1, hparams.N_emb_dir).to(self.device) 47 | } 48 | self.models = { 49 | 'coarse': NeRF('coarse').to(self.device), 50 | 'fine': NeRF('fine', beta_min=hparams.beta_min).to(self.device) 51 | } 52 | 53 | self.dataset = dataset_dict[hparams.dataset_name] 54 | self.kwargs = {'root_dir': hparams.root_dir, 55 | 'img_wh': tuple(hparams.img_wh), 56 | 'perturbation': hparams.data_perturb} 57 | if hparams.dataset_name == 'llff': 58 | self.kwargs['spheric_poses'] = hparams.spheric_poses 59 | self.kwargs['val_num'] = hparams.num_gpus 60 | 61 | if 'coarse_path' in kwargs and 'fine_path' in kwargs: 62 | self.models['coarse'].load_state_dict(torch.load(kwargs['coarse_path'])) 63 | self.models['fine'].load_state_dict(torch.load(kwargs['fine_path'])) 64 | self.train_dataset = self.dataset(split='train', is_learning_density=False, render_patches=False, 65 | **self.kwargs) 66 | else: 67 | self.train_dataset = self.dataset(split='train', is_learning_density=True, **self.kwargs) 68 | 69 | self.val_dataset = self.dataset(split='val', **self.kwargs) 70 | self.val_dataloader = DataLoader(self.val_dataset, shuffle=False, num_workers=4, batch_size=1, pin_memory=True) 71 | 72 | self.create_checkpoint_data() 73 | 74 | def create_checkpoint_data(self): 75 | dataset = self.dataset(split='train', is_learning_density=True, 76 | root_dir=self.kwargs['root_dir'], img_wh=(400, 400), perturbation=self.kwargs['perturbation']) 77 | img_idx = 4 78 | img_wh = 400 79 | self.checkpoint_rays = dataset.all_rays[img_idx * (img_wh ** 2):(img_idx + 1) * (img_wh ** 2), :8] 80 | self.checkpoint_ts = dataset.all_rays[img_idx * (img_wh ** 2):(img_idx + 1) * (img_wh ** 2), 8] 81 | 82 | def set_requires_grad(self, requires_grad=True): # set requires grad for the density layers 83 | for child in self.models['coarse'].children(): 84 | if hasattr(child, 'density'): 85 | for param in child.parameters(): 86 | param.requires_grad = requires_grad 87 | for child in self.models['fine'].children(): 88 | if hasattr(child, 'density'): 89 | for param in child.parameters(): 90 | param.requires_grad = requires_grad 91 | 92 | def __call__(self, rays, ts, white_back): # forward pass through NeRF 93 | results = defaultdict(list) 94 | for i in range(0, rays.shape[0], self.hparams.chunk): 95 | rendered_ray_chunks = render_rays(self.models, 96 | self.embeddings, 97 | rays[i:i + self.hparams.chunk], 98 | ts[i:i + self.hparams.chunk], 99 | self.hparams.N_samples, 100 | self.hparams.use_disp, 101 | self.hparams.perturb, 102 | self.hparams.noise_std, 103 | self.hparams.N_importance, 104 | self.hparams.chunk, 105 | white_back) 106 | for k, v in rendered_ray_chunks.items(): 107 | results[k] += [v] 108 | for k, v in results.items(): 109 | results[k] = torch.cat(v, 0) 110 | return results 111 | 112 | def log_checkpoint_image(self, string): 113 | with torch.no_grad(): 114 | rays, ts = self.checkpoint_rays.to(self.device), self.checkpoint_ts.to(self.device) 115 | rays = rays.squeeze() 116 | ts = ts.squeeze() 117 | results = self(rays, ts, self.val_dataloader.dataset.white_back) 118 | log_image = results['rgb_fine'] 119 | dim = int(math.sqrt(len(log_image))) 120 | log_image = log_image.squeeze().permute(1, 0).view(3, dim, dim) 121 | self.logger(f'checkpoint_image_{string}', log_image) 122 | 123 | def learn_density(self, **kwargs): # train geometry MLP 124 | loss_func = loss_dict['nerfw']() 125 | num_epochs = self.hparams.num_epochs_density 126 | device = self.device 127 | 128 | optimizer = get_optimizer(self.hparams, self.models) 129 | 130 | self.models['coarse'].train() 131 | self.models['fine'].train() 132 | 133 | self.train_dataset.set_params(is_learning_density=True, render_patches=False) 134 | data_loader = DataLoader(self.train_dataset, shuffle=True, num_workers=4, batch_size=self.hparams.batch_size, 135 | pin_memory=True) 136 | 137 | for epoch in range(num_epochs): 138 | print(f'Starting epoch {epoch+1} to learn density...') 139 | for idx, batch in enumerate(data_loader): 140 | if idx % 1000 == 0: 141 | self.log_checkpoint_image(str(idx)) 142 | 143 | rays, rgbs, ts = batch['rays'].to(device), batch['rgbs'].to(device), batch['ts'].to(device) 144 | 145 | optimizer.zero_grad() 146 | results = self(rays, ts, self.train_dataset.white_back) 147 | loss = loss_func(results, rgbs) 148 | self.logger('Loss/train', loss) 149 | loss.backward() 150 | optimizer.step() 151 | 152 | typ = 'fine' if 'rgb_fine' in results else 'coarse' 153 | with torch.no_grad(): 154 | self.logger('PSNR/train', psnr(results[f'rgb_{typ}'], rgbs)) 155 | 156 | def _prepare_for_feature_loss(self, img: torch.tensor, **kwargs): # preprocessing 157 | '''img of shape (H*W, 3) -> (1, 3, w, h)''' 158 | img_wh = kwargs.get('img_wh', None) 159 | if img_wh is None: 160 | img_wh = self.hparams.img_wh[0] 161 | img = img.permute(1, 0) # (3, H*W) 162 | img = img.view(3, img_wh, img_wh) # (3,W,H) 163 | img = img.unsqueeze(0) # (1,3,W,H) 164 | return img 165 | 166 | def reset_style_mlp(self): # reset the parameters of style mlp 167 | for child in self.models['fine'].children(): 168 | if not hasattr(child, 'density'): 169 | # layer.reset_parameters() 170 | for param in child.parameters(): 171 | if len(param.data.shape) == 2: 172 | torch.nn.init.xavier_uniform_(param.data) 173 | else: 174 | param.data = torch.zeros_like(param.data) 175 | 176 | def learn_style(self, style_path, style_mode='memory_saving', **kwargs): 177 | self.reset_style_mlp() 178 | 179 | self.style_image = image_loader( 180 | image_name=style_path, 181 | imsize=self.hparams.img_wh[0] 182 | ) 183 | self.style_image = self.style_image.to(self.device) 184 | 185 | img_wh = self.kwargs['img_wh'][0] 186 | 187 | num_epochs = self.hparams.num_epochs_style 188 | device = self.device 189 | optimizer = get_optimizer(self.hparams, self.models) 190 | loss_func = loss_dict['style'](self.style_image, style_weight=1000000, content_weight=1) 191 | 192 | num_patches = (img_wh // 50) ** 2 193 | 194 | if style_mode == 'patch': # transfer style using patches 195 | # image logging 196 | self.log_checkpoint_image('start') 197 | 198 | self.train_dataset.set_params(is_learning_density=False, render_patches=True) 199 | data_loader = DataLoader(self.train_dataset, batch_size=1, shuffle=False) 200 | 201 | for epoch in range(num_epochs): 202 | print(f'Mode: Patch, Starting epoch {epoch + 1} to learn style...') 203 | for idx, data in enumerate(data_loader): 204 | 205 | rays, rgbs, ts = data['rays'].to(device), data['rgbs'].to(device), data['ts'].to(device) 206 | rays = rays.squeeze() 207 | rgbs = rgbs.squeeze() 208 | ts = ts.squeeze() 209 | 210 | rgbs = self._prepare_for_feature_loss(rgbs, img_wh=50) 211 | optimizer.zero_grad() 212 | rendered_image = self(rays, ts, self.train_dataset.white_back)['rgb_fine'] 213 | rendered_image = self._prepare_for_feature_loss(rendered_image, img_wh=50) 214 | if torch.mean(rendered_image) > 0.99: # empty image 215 | continue 216 | loss = loss_func(rendered_image, rgbs) 217 | self.logger('Loss/train', loss) 218 | loss.backward() 219 | optimizer.step() 220 | 221 | # image logging 222 | self.log_checkpoint_image('end') 223 | 224 | elif style_mode == 'memory_saving': # render whole images to transfer the style 225 | # image logging 226 | self.log_checkpoint_image('start') 227 | 228 | for epoch in range(num_epochs): 229 | print(f'Mode: Memory saving (No patch), Starting epoch {epoch + 1} to learn style...') 230 | for i in range(100): 231 | # Substage 1: store gradients 232 | self.train_dataset.set_params(is_learning_density=False, render_patches=False) 233 | with torch.no_grad(): 234 | sample = self.train_dataset[i] 235 | rays, rgbs, ts = sample['rays'].to(device), sample['rgbs'].to(device), sample['ts'].to(device) 236 | rays = rays.squeeze() 237 | rgbs = rgbs.squeeze() 238 | ts = ts.squeeze() 239 | 240 | rgbs = self._prepare_for_feature_loss(rgbs) 241 | 242 | rendered_image = self(rays, ts, self.train_dataset.white_back)['rgb_fine'] 243 | rendered_image = self._prepare_for_feature_loss(rendered_image) 244 | 245 | rendered_image.requires_grad_() 246 | loss = loss_func(rendered_image, rgbs) 247 | self.logger('Loss/train', loss) 248 | loss.backward() 249 | 250 | gradient = rendered_image.grad.clone().detach() 251 | 252 | # Substage 2: backprop gradients through NeRF 253 | self.train_dataset.set_params(is_learning_density=False, render_patches=True) 254 | optimizer.zero_grad() 255 | for j in range(num_patches): # iterate over patches 256 | sample = self.train_dataset[i*num_patches + j] 257 | rays, rgbs, ts = sample['rays'].to(device), sample['rgbs'].to(device), sample['ts'].to(device) 258 | rays = rays.squeeze() 259 | ts = ts.squeeze() 260 | 261 | rendered_image = self(rays, ts, self.train_dataset.white_back)['rgb_fine'] 262 | rendered_image = self._prepare_for_feature_loss(rendered_image, img_wh=50) 263 | 264 | if torch.mean(rendered_image) > 0.99: # empty image 265 | continue 266 | r, c = j // (img_wh // 50), j % (img_wh // 50) 267 | rendered_image.backward(gradient[:, :, r * 50: (r + 1) * 50, c * 50: (c + 1) * 50]) 268 | optimizer.step() 269 | 270 | # image logging 271 | self.log_checkpoint_image('end') 272 | 273 | elif style_mode == 'small': 274 | self.train_dataset.set_params(is_learning_density=False, render_patches=False) 275 | data_loader = DataLoader(self.train_dataset, shuffle=True, batch_size=1) 276 | 277 | # image logging 278 | self.log_checkpoint_image('start') 279 | 280 | for epoch in range(num_epochs): 281 | print(f'Mode: Small, Starting epoch {epoch + 1} to learn style...') 282 | for idx, data in enumerate(data_loader): 283 | rays, rgbs, ts = data['rays'].to(device), data['rgbs'].to(device), data['ts'].to(device) 284 | rays = rays.squeeze() 285 | rgbs = rgbs.squeeze() 286 | ts = ts.squeeze() 287 | 288 | rgbs = self._prepare_for_feature_loss(rgbs) 289 | 290 | optimizer.zero_grad() 291 | rendered_image = self(rays, ts, self.train_dataset.white_back)['rgb_fine'] 292 | rendered_image = self._prepare_for_feature_loss(rendered_image) 293 | loss = loss_func(rendered_image, rgbs) 294 | self.logger('Loss/train', loss) 295 | loss.backward() 296 | optimizer.step() 297 | 298 | # image logging 299 | self.log_checkpoint_image('end') 300 | 301 | else: 302 | raise ValueError('Please enter a valid mode for style transfer.') 303 | 304 | def log_model(self, prefix, suffix): 305 | try: 306 | os.mkdir('./ckpts') 307 | except FileExistsError: 308 | pass 309 | torch.save(self.models['coarse'].state_dict(), f'ckpts/{prefix}_nerf_coarse_{suffix}.pt') 310 | torch.save(self.models['fine'].state_dict(), f'ckpts/{prefix}_nerf_fine_{suffix}.pt') 311 | 312 | 313 | if __name__ == '__main__': 314 | hparams = get_opts() # parse args 315 | 316 | if hparams.stage == 'geometry': # stage 1 317 | pl = Pipeline(hparams) 318 | pl.learn_density() # learn the scene geometry 319 | pl.log_model(prefix=hparams.prefix, suffix=hparams.suffix) # log the model 320 | 321 | elif hparams.stage == 'style': # stage 2 322 | pl = Pipeline(hparams, 323 | coarse_path=hparams.coarse_path, # coarse NeRF 324 | fine_path=hparams.fine_path # fine NeRF 325 | ) 326 | pl.set_requires_grad(requires_grad=False) # freeze density layer 327 | pl.learn_style(style_path=hparams.style_dir, style_mode=hparams.style_mode) # transfer the style 328 | pl.log_model(prefix=hparams.prefix, suffix=hparams.suffix) # log the model 329 | 330 | else: 331 | raise ValueError('Please enter a valid stage.') 332 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------