├── requirements.txt ├── docker ├── Dockerfile └── launch.sh ├── cuda ├── include │ └── anytime_kernels.cuh ├── setup.py └── csrc │ ├── cost_volume.cu │ └── kernels │ └── anytime_kernels.cu ├── utils ├── dataloaders │ ├── readpfm.py │ ├── sceneflow.py │ ├── kitti.py │ └── listflowfile.py ├── metrics │ └── metrics.py ├── torch_timer.py ├── cli │ └── base.py ├── submodules.py └── pl │ └── pl_base.py ├── .gitignore ├── README.md ├── cli.py ├── model ├── unet_parts.py └── default.py ├── pl_template.py └── LICENSE /requirements.txt: -------------------------------------------------------------------------------- 1 | click==6.7 2 | pytorch_lightning==0.5.3.2 3 | adabound==0.0.5 4 | numpy==1.13.3 5 | torch>=1.3.1 6 | torchsummary==1.5.1 7 | Pillow==8.3.2 8 | torchvision==0.7.0 9 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM pytorch/pytorch:1.5-cuda10.1-cudnn7-devel 2 | 3 | RUN conda install -y click opencv 4 | RUN conda install -y scipy 5 | RUN conda install -y scikit-image 6 | RUN python3 -m pip install pytorch-lightning==0.7.6 adabound 7 | RUN python3 -m pip install torchsummary==1.5.1 8 | 9 | RUN mkdir -p /root/datasets 10 | -------------------------------------------------------------------------------- /docker/launch.sh: -------------------------------------------------------------------------------- 1 | docker rm -f $(docker ps -a -q) 2 | docker build --tag=stereodock ./docker/ 3 | docker run -it --ipc=host --gpus all -v $PWD:/workspace -v $HOME/datasets:/root/datasets --env COMET_KEY=$COMET_KEY --env COMET_WORKSPACE=$COMET_WORKSPACE --env COMET_REST_KEY=$COMET_REST_KEY --env COMET_DISABLE_AUTO_LOGGING=$COMET_DISABLE_AUTO_LOGGING --name stereodock stereodock 4 | -------------------------------------------------------------------------------- /cuda/include/anytime_kernels.cuh: -------------------------------------------------------------------------------- 1 | #ifndef ANYTIME_KERNELS 2 | #define ANYTIME_KERNELS 3 | 4 | 5 | void k_100(torch::Tensor left, 6 | torch::Tensor right, 7 | torch::Tensor cost_volume, 8 | const int height, 9 | const int width, 10 | const int max_disparity, 11 | const int feature_size); 12 | 13 | #endif 14 | 15 | 16 | -------------------------------------------------------------------------------- /cuda/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | from torch.utils.cpp_extension import BuildExtension, CUDAExtension 3 | 4 | sources = ['csrc/cost_volume.cu', 5 | 'csrc/kernels/anytime_kernels.cu'] 6 | include_dirs = ['include/'] 7 | nvcc = [ 8 | '-gencode', 'arch=compute_53,code=sm_53', 9 | '-gencode', 'arch=compute_60,code=sm_60', 10 | '-gencode', 'arch=compute_61,code=sm_61', 11 | '-gencode', 'arch=compute_62,code=sm_62', 12 | '-gencode', 'arch=compute_70,code=sm_70', 13 | '-gencode', 'arch=compute_72,code=sm_72', 14 | '-gencode', 'arch=compute_70,code=compute_70', 15 | '-lineinfo', 16 | '-Xptxas', 17 | '-dlcm=ca'] 18 | extra_compile_args = {'cxx': [], 'nvcc': nvcc} 19 | 20 | setup(name='cost_volume', 21 | version='0.0.1', 22 | ext_modules=[CUDAExtension('cost_volume', 23 | sources, 24 | extra_compile_args=extra_compile_args, 25 | include_dirs=include_dirs)], 26 | cmdclass={'build_ext': BuildExtension}) 27 | -------------------------------------------------------------------------------- /cuda/csrc/cost_volume.cu: -------------------------------------------------------------------------------- 1 | #include 2 | #include "anytime_kernels.cuh" 3 | 4 | #define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x " must be a CUDA tensor") 5 | #define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x " must be contiguous") 6 | #define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) 7 | 8 | 9 | torch::Tensor cost_volume(torch::Tensor left, 10 | torch::Tensor right, 11 | int max_disparity){ 12 | CHECK_INPUT(left); 13 | CHECK_INPUT(right); 14 | 15 | int height = left.size(1); 16 | int width = left.size(2); 17 | int feat_size = left.size(0); 18 | 19 | torch::Tensor out; 20 | out = torch::zeros({max_disparity, height, width}, 21 | torch::dtype(left.dtype()). 22 | device(torch::kCUDA). 23 | requires_grad(false)); 24 | 25 | k_100(left, right, out, height, width, max_disparity, feat_size); 26 | 27 | return out; 28 | } 29 | 30 | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { 31 | m.def("cost_volume", &cost_volume, "Cost Volume (CUDA)"); 32 | } 33 | 34 | -------------------------------------------------------------------------------- /utils/dataloaders/readpfm.py: -------------------------------------------------------------------------------- 1 | import re 2 | import numpy as np 3 | import sys 4 | 5 | 6 | def readPFM(file): 7 | file = open(file, 'rb') 8 | 9 | color = None 10 | width = None 11 | height = None 12 | scale = None 13 | endian = None 14 | 15 | header = file.readline().rstrip() 16 | if header == b'PF': 17 | color = True 18 | elif header == b'Pf': 19 | color = False 20 | else: 21 | raise Exception('Not a PFM file.') 22 | 23 | dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline().decode('utf-8')) 24 | if dim_match: 25 | width, height = map(int, dim_match.groups()) 26 | else: 27 | raise Exception('Malformed PFM header.') 28 | 29 | scale = float(file.readline().rstrip()) 30 | if scale < 0: # little-endian 31 | endian = '<' 32 | scale = -scale 33 | else: 34 | endian = '>' # big-endian 35 | 36 | data = np.fromfile(file, endian + 'f') 37 | shape = (height, width, 3) if color else (height, width) 38 | 39 | data = np.reshape(data, shape) 40 | data = np.flipud(data) 41 | file.close() 42 | return data, scale 43 | -------------------------------------------------------------------------------- /utils/metrics/metrics.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | def compute_epe(d_gt, d_est, max_disp=192): 5 | """Computes end-point-error EPE 6 | 7 | Parameters 8 | ---------- 9 | d_gt : torch.Tensor 10 | disparity groundtruth 11 | d_est : torch.Tensor 12 | disparity prediction 13 | max_disp: int 14 | Maximum allowed disparity 15 | Returns 16 | ------- 17 | torch.Tensor 18 | """ 19 | mask = (d_gt < max_disp) & (d_gt > 0) 20 | 21 | if mask.sum() != 0: 22 | epe = (d_est[mask] - d_gt[mask]).abs().mean() 23 | else: 24 | epe = torch.tensor(100.0).float().to(d_gt.device) 25 | 26 | return epe 27 | 28 | 29 | def compute_err(d_gt, d_est, tau, max_disp=192): 30 | """Compute the disparity error belowe tau threshold 31 | 32 | Parameters 33 | ---------- 34 | d_gt : torch.Tensor 35 | disparity groundtruth 36 | d_est : torch.Tensor 37 | disparity prediction 38 | tau : int 39 | Allowed error in pixels 40 | max_disp: int 41 | Maximum allowed disparity 42 | 43 | Returns 44 | ------- 45 | torch.Tensor 46 | 47 | """ 48 | mask = (d_gt < max_disp) & (d_gt > 0) 49 | if mask.sum() != 0: 50 | errmap = (d_gt - d_est).abs() 51 | err = ((errmap[mask] > tau) & (errmap[mask] / d_gt[mask] > 0.05)).sum() 52 | else: 53 | err = torch.tensor(1.0).float().to(d_gt.device) 54 | return err 55 | return err.float() / mask.sum().float() 56 | -------------------------------------------------------------------------------- /utils/torch_timer.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import time 3 | 4 | 5 | class TorchTimer(object): 6 | 7 | """Compute elapsed time for a given method """ 8 | 9 | def __init__(self, times=100, warmup=5): 10 | """ Init torch timer 11 | 12 | Parameters: 13 | ---------- 14 | times: int 15 | How many times will be run the method 16 | warmup: int 17 | How many the method will run before recording its time 18 | """ 19 | super().__init__() 20 | self.times = times 21 | self.warmup = warmup 22 | self.reset() 23 | 24 | def reset(self): 25 | """ Reset variables 26 | Returns 27 | ------- 28 | None 29 | """ 30 | self.elapsed = torch.zeros(self.times) 31 | 32 | def run(self, method, *args): 33 | """ Benchmark a given method with its arguments 34 | 35 | Parameters 36 | ---------- 37 | method : Object 38 | Method to benchmark 39 | args: list 40 | List of arguments of the method 41 | 42 | Returns 43 | ------- 44 | elapsed time : [mean, std, network_output] in seconds 45 | """ 46 | self.reset() 47 | for i in range(self.times + self.warmup): 48 | torch.cuda.synchronize() 49 | start = time.perf_counter() 50 | net_output = method(*args) 51 | torch.cuda.synchronize() 52 | end = time.perf_counter() 53 | if i > (self.warmup - 1): 54 | self.elapsed[i - self.warmup] = end - start 55 | return self.elapsed.mean().cpu(), self.elapsed.std().cpu(), net_output 56 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | output/ 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | pip-wheel-metadata/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | local_settings.py 62 | db.sqlite3 63 | db.sqlite3-journal 64 | 65 | # Flask stuff: 66 | instance/ 67 | .webassets-cache 68 | 69 | # Scrapy stuff: 70 | .scrapy 71 | 72 | # Sphinx documentation 73 | docs/_build/ 74 | 75 | # PyBuilder 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | .python-version 87 | 88 | # pipenv 89 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 90 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 91 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 92 | # install all needed dependencies. 93 | #Pipfile.lock 94 | 95 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 96 | __pypackages__/ 97 | 98 | # Celery stuff 99 | celerybeat-schedule 100 | celerybeat.pid 101 | 102 | # SageMath parsed files 103 | *.sage.py 104 | 105 | # Environments 106 | .env 107 | .venv 108 | env/ 109 | venv/ 110 | ENV/ 111 | env.bak/ 112 | venv.bak/ 113 | 114 | # Spyder project settings 115 | .spyderproject 116 | .spyproject 117 | 118 | # Rope project settings 119 | .ropeproject 120 | 121 | # mkdocs documentation 122 | /site 123 | 124 | # mypy 125 | .mypy_cache/ 126 | .dmypy.json 127 | dmypy.json 128 | 129 | # Pyre type checker 130 | .pyre/ 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Fast CNN Stereo Depth Estimation through Embedded GPU Device 2 | 3 | This is the implementation of our paper"[Fast CNN Stereo Depth Estimation through Embedded GPU Device](https://www.mdpi.com/1424-8220/20/11/3249)" 4 | 5 | --- 6 | 7 | ## Results 8 | 9 | | Model | Dataset | EPE | Err > 3 | 10 | |:-----:|:-------:|:---:|:-------:| 11 | | Default| Kitti2012| 1.80 | 0.11 | 12 | 13 | --- 14 | 15 | ## Reproduce results (Training in Desktop) 16 | 17 | ##### Docker (training on x64 arch) 18 | 19 | ```bash 20 | ./docker/launch.sh 21 | 22 | # Sceneflow training 23 | python cli.py festereo-train --num_workers 16 --max_epochs 20 --min_epochs 1 --patience 100 --lr 5e-3 --save_top_k 20 24 | 25 | # Kitti2012 (using sceneflow pretrained) 26 | python cli.py festereo-train --num_workers 16 --max_epochs 300 --min_epochs 200 --patience 100 --lr 5e-3 --dataset kitti2012 --pretrained [path]/sceneflow_ckpt_epoch_19.ckpt --scheduler plateau 27 | ``` 28 | 29 | ### Pretrained networks 30 | 31 | - [Sceneflow checkpoint epoch 19](https://www.dropbox.com/s/a3ry4lqouw7nkhc/sceneflow.ckpt?dl=0) 32 | - [Kitti2012](https://www.dropbox.com/s/ckdixxrp7kb67b4/kitti2012.ckpt?dl=0) 33 | 34 | --- 35 | 36 | ## Reproduce results (Inference in Jetson Jetpack 4.3) 37 | 38 | #### Install Pytorch 1.3 39 | 40 | Follow instructions from [link](https://forums.developer.nvidia.com/t/pytorch-for-jetson-version-1-6-0-now-available/72048) 41 | 42 | #### Install Python requirements 43 | 44 | ``` 45 | pip3 install -r requirements.txt 46 | ``` 47 | 48 | 49 | #### Install tensorrt 50 | 51 | ```bash 52 | sudo apt-get install libprotobuf* protobuf-compiler ninja-build 53 | git clone https://github.com/ngunsu/torch2trt.git 54 | cd torch2trt 55 | sudo python3 setup.py install --plugins 56 | ``` 57 | 58 | #### Install cuda kernel 59 | 60 | ```bash 61 | cd cuda && python3 setup.py install --user 62 | ``` 63 | 64 | #### Benchmark speed 65 | 66 | ```bash 67 | sudo nvpmodel -m 0 && sudo jetson_clocks 68 | python3 model/default.py --benchmark --tensorrt 69 | ``` 70 | 71 | For more options python3 model/default.py --help 72 | 73 | --- 74 | 75 | ## Citation 76 | ``` 77 | @article{Aguilera_2020, 78 | doi = {10.3390/s20113249}, 79 | url = {https://doi.org/10.3390%2Fs20113249}, 80 | year = 2020, 81 | month = {jun}, 82 | publisher = {{MDPI} {AG}}, 83 | volume = {20}, 84 | number = {11}, 85 | pages = {3249}, 86 | author = {Cristhian A. Aguilera and Cristhian Aguilera and Crist{\'{o}}bal A. Navarro and Angel D. Sappa}, 87 | title = {Fast {CNN} Stereo Depth Estimation through Embedded {GPU} Devices}, 88 | journal = {Sensors} 89 | } 90 | ``` 91 | -------------------------------------------------------------------------------- /cli.py: -------------------------------------------------------------------------------- 1 | from utils.cli.base import CLIBase 2 | from argparse import Namespace 3 | from pl_template import FEStereo 4 | import click 5 | import os 6 | 7 | def_dataset_path = os.environ['HOME'] + '/datasets/' 8 | 9 | 10 | class TrainTestManager(CLIBase): 11 | 12 | """TrainTestManager deals with the training and testing process of the network""" 13 | 14 | model_name = 'festero' 15 | 16 | def __init__(self, hparams): 17 | model = FEStereo(hparams) 18 | super().__init__(model, self.model_name, hparams) 19 | 20 | 21 | @click.group() 22 | def cli(): 23 | pass 24 | 25 | 26 | @cli.command() 27 | @click.option('--num_workers', default=16, type=int, help="Number of CPUs to use") 28 | @click.option('--shuffle/--no-shuffle', default=True, help="Shuffle while training") 29 | @click.option('--drop_last/--no-drop_last', default=True, help="Drop last batch during training") 30 | @click.option('--dataset', type=click.Choice(['sceneflow', 'kitti2012', 'kitti2015']), 31 | default='sceneflow') 32 | @click.option('--model_type', type=click.Choice(['default']), default='default') 33 | @click.option('--datasets_path', default=def_dataset_path) 34 | @click.option('--exp_id', default=1, help='Experiment ID') 35 | @click.option('--min_epochs', default=10, help='Minimum number of epochs during training') 36 | @click.option('--max_epochs', default=20, help='Maximun number of epochs during training') 37 | @click.option('--epochs_per_val', default=1, help='Check validation every epochs_per_val') 38 | @click.option('--max_disp', default=192, help='Maximum disparity') 39 | @click.option('--batch_size', default=6, help='Batch size') 40 | @click.option('--seed', default=1, help='Seed') 41 | @click.option('--optimizer', type=click.Choice(['adam', 'adabound']), default='adam') 42 | @click.option('--scheduler', type=click.Choice(['steplr', 'multisteplr', 'plateau']), default='steplr') 43 | @click.option('--lr', default=5e-3, help='Learning rate') 44 | @click.option('--gamma', default=0.1, help='Learning rate step gamma') 45 | @click.option('--gamma_step', default=10, help='Learning rate step') 46 | @click.option('--auto_lr_find/--no-auto_lr_find', default=False, help='Auto find initial lr') 47 | @click.option('--debug/--no-debug', default=False, help='Number of stages') 48 | @click.option('--justtest/--no-justtest', default=False, help='just run test') 49 | @click.option('--resume', default=None, required=False, type=str, help='Checkpoint to resume training') 50 | @click.option('--patience', default=5, help='Early stopping') 51 | @click.option('--save_top_k', default=1, help='Save best k models') 52 | @click.option('--pretrained', default='', help='Pretrained weights path') 53 | def festereo_train(**args): 54 | hparams = Namespace(**args) 55 | 56 | ttmanager = TrainTestManager(hparams=hparams) 57 | 58 | ttmanager.train() 59 | 60 | 61 | if __name__ == "__main__": 62 | cli() 63 | -------------------------------------------------------------------------------- /cuda/csrc/kernels/anytime_kernels.cu: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | constexpr int K_100_THREADS = 64; 5 | 6 | //----------------------------------------------------------------------- 7 | // K_100 8 | //----------------------------------------------------------------------- 9 | template 10 | __global__ void 11 | __launch_bounds__(1024) k_100_cuda(const scalar_t* __restrict__ left, 12 | const scalar_t* __restrict__ right, 13 | scalar_t* __restrict__ cost_volume, 14 | const int height, 15 | const int width, 16 | const int max_disparity, 17 | const int feature_size){ 18 | 19 | const int pos_t = (blockIdx.x*blockDim.x) + threadIdx.x; 20 | const int h = pos_t/width; 21 | const int w = pos_t-h*width; 22 | int i = 0; 23 | int j = 0; 24 | 25 | if (h < height && w < width){ 26 | const int offset = h*width+w; 27 | 28 | for(i=0; i<<>>(left.data(), 59 | right.data(), 60 | cost_volume.data(), 61 | height, 62 | width, 63 | max_disparity, 64 | feature_size); 65 | 66 | })); 67 | cudaDeviceSynchronize(); 68 | 69 | // check for errors 70 | cudaError_t error = cudaGetLastError(); 71 | if (error != cudaSuccess) { 72 | fprintf(stderr, "ERROR: %s \n", cudaGetErrorString(error)); 73 | } 74 | 75 | } 76 | 77 | -------------------------------------------------------------------------------- /utils/cli/base.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import time 3 | from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping 4 | from pytorch_lightning import Trainer 5 | from pytorch_lightning import loggers 6 | 7 | 8 | class CLIBase(): 9 | 10 | """Base for command line interfaces of implemented models""" 11 | 12 | def __init__(self, model, model_name, hparams): 13 | """Constructor 14 | 15 | Parameters 16 | ---------- 17 | model (class): Pytorch Lighting template model 18 | model_name (str): Name of the model 19 | hparams (Namespace): Parameters list 20 | 21 | Returns 22 | ------- 23 | None 24 | 25 | """ 26 | # Set arguments 27 | self.model = model 28 | self.model_name = model_name 29 | self.model_type = hparams.model_type 30 | self.hparams = hparams 31 | 32 | def train(self): 33 | """Train the network""" 34 | 35 | hparams = self.hparams 36 | dataset = hparams.dataset 37 | 38 | exp_id = time.time() 39 | # Checkpoint callback 40 | filepath = f'./output/{self.model_name}_{self.model_type}/{dataset}/checkpoints/{exp_id}/' 41 | checkpoint_callback = ModelCheckpoint(filepath=filepath, 42 | save_top_k=hparams.save_top_k, 43 | verbose=True, 44 | monitor='val_loss', 45 | mode='min', 46 | prefix=f'{hparams.dataset}') 47 | 48 | logger = False 49 | if not hparams.justtest: 50 | logger = loggers.TensorBoardLogger(f'/output/{self.model_name}_{self.model_type}/{dataset}/log/') 51 | 52 | early_stop_callback = EarlyStopping(monitor='val_loss', 53 | min_delta=0.00, 54 | patience=hparams.patience, 55 | verbose=True, 56 | mode='min') 57 | # Set trainer 58 | trainer = Trainer(gpus=1, 59 | train_percent_check=1.0, 60 | val_percent_check=1.0, 61 | test_percent_check=1.0, 62 | overfit_pct=0.01 if hparams.debug else 0.0, 63 | check_val_every_n_epoch=hparams.epochs_per_val, 64 | min_epochs=hparams.min_epochs, 65 | max_epochs=hparams.max_epochs, 66 | resume_from_checkpoint=hparams.resume, 67 | auto_lr_find=hparams.auto_lr_find, 68 | logger=logger, 69 | checkpoint_callback=checkpoint_callback, 70 | early_stop_callback=early_stop_callback) 71 | 72 | if hparams.pretrained != '': 73 | checkpoint = torch.load(hparams.pretrained) 74 | self.model.load_state_dict(checkpoint['state_dict']) 75 | 76 | if not hparams.justtest: 77 | trainer.fit(self.model) 78 | trainer.test(self.model) 79 | else: 80 | trainer.test(self.model) 81 | -------------------------------------------------------------------------------- /utils/dataloaders/sceneflow.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import Dataset 2 | from PIL import Image 3 | from . import listflowfile as lt 4 | import numpy as np 5 | import random 6 | 7 | 8 | class SceneflowLoader(Dataset): 9 | 10 | """Sceneflow stereo dataset manager""" 11 | 12 | def __init__(self, dataset, dataset_path, training, validation, transform=None, downsample_training=False): 13 | """ 14 | Parameters 15 | ---------- 16 | dataset: str 17 | Kitti2012 or kitti2015 18 | dataset_path: str 19 | Kitti dataset path 20 | training: bool 21 | Loads training images 22 | validation: bool 23 | Loads validation data 24 | transform: torchvision.transforms 25 | Transform to be applied to all pair 26 | downsample_training: bool 27 | Downsample during training. Some networks dont't need big images to converge faster 28 | 29 | Returns 30 | ------- 31 | None 32 | """ 33 | Dataset.__init__(self) 34 | 35 | self.dataset = dataset 36 | self.dataset_path = dataset_path 37 | self.training = training 38 | self.validation = validation 39 | self.transform = transform 40 | self.downsample_training = downsample_training 41 | 42 | # Load list of images 43 | tr_l, tr_r, tr_l_disp, test_l, test_r, test_l_disp = lt.dataloader(dataset_path) 44 | 45 | self.l_im_paths = [] 46 | self.r_im_paths = [] 47 | self.l_disp_paths = [] 48 | 49 | if self.training: 50 | self.l_im_paths = self.l_im_paths + tr_l 51 | self.r_im_paths = self.r_im_paths + tr_r 52 | self.l_disp_paths = self.l_disp_paths + tr_l_disp 53 | if self.validation: 54 | self.l_im_paths = self.l_im_paths + test_l 55 | self.r_im_paths = self.r_im_paths + test_r 56 | self.l_disp_paths = self.l_disp_paths + test_l_disp 57 | 58 | def disparity_loader(self, path): 59 | path_prefix = path.split('.')[0] 60 | # print(path_prefix) 61 | path1 = path_prefix + '_exception_assign_minus_1.npy' 62 | path2 = path_prefix + '.npy' 63 | path3 = path_prefix + '.pfm' 64 | import os.path as ospath 65 | if ospath.exists(path1): 66 | return np.load(path1) 67 | else: 68 | 69 | # from readpfm import readPFMreadPFM 70 | from .readpfm import readPFM 71 | data, _ = readPFM(path3) 72 | np.save(path2, data) 73 | for i in range(data.shape[0]): 74 | for j in range(data.shape[1]): 75 | if j - data[i][j] < 0: 76 | data[i][j] = -1 77 | np.save(path1, data) 78 | return data 79 | 80 | def load_pair(self, idx): 81 | l_im = Image.open(self.l_im_paths[idx]) 82 | r_im = Image.open(self.r_im_paths[idx]) 83 | l_disp = self.disparity_loader(self.l_disp_paths[idx]) 84 | l_disp = np.ascontiguousarray(l_disp, dtype=np.float32) 85 | l_disp = np.expand_dims(l_disp, axis=0) 86 | 87 | if self.downsample_training: 88 | w, h = l_im.size 89 | th, tw = 256, 512 90 | 91 | x1 = random.randint(0, w - tw) 92 | y1 = random.randint(0, h - th) 93 | 94 | l_im = l_im.crop((x1, y1, x1 + tw, y1 + th)) 95 | r_im = r_im.crop((x1, y1, x1 + tw, y1 + th)) 96 | 97 | l_disp = l_disp[:, y1:y1 + th, x1:x1 + tw] 98 | return l_im, r_im, l_disp 99 | 100 | def __len__(self): 101 | return len(self.l_im_paths) 102 | 103 | def __getitem__(self, index): 104 | l_im, r_im, l_disp = self.load_pair(index) 105 | 106 | if self.transform is not None: 107 | l_im = self.transform(l_im) 108 | r_im = self.transform(r_im) 109 | 110 | return l_im, r_im, l_disp 111 | -------------------------------------------------------------------------------- /model/unet_parts.py: -------------------------------------------------------------------------------- 1 | """ Parts of the U-Net model 2 | Based on: https://github.com/milesial/Pytorch-UNet 3 | """ 4 | 5 | import torch 6 | import torch.nn as nn 7 | 8 | 9 | class NConv(nn.Module): 10 | """(convolution => [BN] => ReLU) * n times""" 11 | 12 | def __init__(self, in_channels, out_channels, ks, stride=1, pad=1, 13 | dilation=1, bn=True, bias=False, n=1, relu=True, groups=1): 14 | super().__init__() 15 | modules = [] 16 | for x in range(n): 17 | if bn: 18 | modules.append(nn.BatchNorm2d(in_channels)) 19 | if relu: 20 | modules.append(nn.ReLU(inplace=True)) 21 | modules.append(nn.Conv2d(in_channels, 22 | out_channels, 23 | kernel_size=ks, 24 | padding=pad, 25 | stride=stride, 26 | dilation=dilation, 27 | groups=groups, 28 | bias=bias)) 29 | in_channels = out_channels 30 | self.single_conv = nn.Sequential(*modules) 31 | 32 | def forward(self, x): 33 | return self.single_conv(x) 34 | 35 | 36 | class NConv3D(nn.Module): 37 | """(convolution3D => [BN] => ReLU) * n times""" 38 | 39 | def __init__(self, in_channels, out_channels, ks, stride=1, pad=1, 40 | dilation=1, bn=True, bias=False, n=1, relu=True): 41 | super().__init__() 42 | modules = [] 43 | for x in range(n): 44 | if bn: 45 | modules.append(nn.BatchNorm3d(in_channels)) 46 | if relu: 47 | modules.append(nn.ReLU(inplace=True)) 48 | modules.append(nn.Conv3d(in_channels, 49 | out_channels, 50 | kernel_size=ks, 51 | padding=pad, 52 | stride=stride, 53 | dilation=dilation, 54 | bias=bias)) 55 | in_channels = out_channels 56 | self.single_conv = nn.Sequential(*modules) 57 | 58 | def forward(self, x): 59 | return self.single_conv(x) 60 | 61 | 62 | class Down(nn.Module): 63 | """Downscaling with maxpool then double conv""" 64 | 65 | def __init__(self, in_channels, out_channels, bn=True, bias=False, n=1): 66 | super().__init__() 67 | modules = [] 68 | modules.append(nn.MaxPool2d(2)) 69 | modules.append(NConv(in_channels, out_channels, ks=3, bn=bn, bias=bias, n=n)) 70 | self.maxpool_conv = nn.Sequential(*modules) 71 | 72 | def forward(self, x): 73 | return self.maxpool_conv(x) 74 | 75 | 76 | class Up(nn.Module): 77 | """Upscaling then double conv""" 78 | 79 | def __init__(self, in_channels, out_channels, bn=True, bias=False, bilinear=True, n=2): 80 | super().__init__() 81 | 82 | # if bilinear, use the normal convolutions to reduce the number of channels 83 | if bilinear: 84 | self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) 85 | else: 86 | self.up = nn.ConvTranspose2d(in_channels // 2, in_channels // 2, kernel_size=2, stride=2) 87 | self.conv = NConv(in_channels, out_channels, ks=3, bn=bn, bias=bias, n=n) 88 | 89 | def forward(self, x1, x2): 90 | x1 = self.up(x1) 91 | ''' 92 | buttom, right = x1.size(2) % 2, x1.size(3) % 2 93 | x2 = nn.functional.pad(x2, (0, -right, 0, -buttom)) 94 | ''' 95 | diffY = x2.size()[2] - x1.size()[2] 96 | diffX = x2.size()[3] - x1.size()[3] 97 | 98 | x1 = nn.functional.pad(x1, [int(diffX / 2), diffX - int(diffX / 2), 99 | int(diffY / 2), diffY - int(diffY / 2)]) 100 | return self.conv(torch.cat([x1, x2], 1)) 101 | -------------------------------------------------------------------------------- /utils/submodules.py: -------------------------------------------------------------------------------- 1 | """ Convolution submodules 2 | Partially based on: https://github.com/milesial/Pytorch-UNet 3 | """ 4 | 5 | import torch 6 | import torch.nn as nn 7 | 8 | 9 | class NConv(nn.Module): 10 | """(convolution => [BN] => ReLU) * n times""" 11 | 12 | def __init__(self, in_channels, out_channels, ks=3, stride=1, pad=1, 13 | dilation=1, bn=True, bias=False, n=1, activation='relu', 14 | groups=1, c3D=False): 15 | """ 16 | Constructor 17 | 18 | Parameters: 19 | ---------- 20 | in_channels: int 21 | Number of input channels 22 | out_channel: int 23 | Number of output channels 24 | ks: int 25 | Convolution kernel size 26 | stride: int 27 | Convolution stride 28 | pad: int 29 | Convolution padding 30 | dilation: int 31 | Convolution dilation 32 | bn: bool 33 | True adds batchnormm 34 | bias: bool 35 | True use bias, False don't use bias 36 | n: int 37 | Number of convolutions 38 | activation: str 39 | Type of activation, if None, no activation is used 40 | groups: int 41 | Convolutions groups 42 | c3D: bool 43 | If True 3D convolutions are used. On the contrary, 2D convolutions 44 | """ 45 | 46 | super().__init__() 47 | modules = [] 48 | 49 | # Select 2D or 3D convolutions 50 | conv = nn.Conv2d 51 | batchnorm = nn.BatchNorm2d 52 | if c3D is True: 53 | conv = nn.Conv3d 54 | batchnorm = nn.BatchNorm3d 55 | 56 | for x in range(n): 57 | # Batchnorm 58 | if bn: 59 | modules.append(batchnorm(in_channels)) 60 | # Activation 61 | if activation is not None: 62 | if activation == 'relu': 63 | modules.append(nn.ReLU(inplace=True)) 64 | modules.append(conv(in_channels, 65 | out_channels, 66 | kernel_size=ks, 67 | padding=pad, 68 | stride=stride, 69 | dilation=dilation, 70 | groups=groups, 71 | bias=bias)) 72 | in_channels = out_channels 73 | self.single_conv = nn.Sequential(*modules) 74 | 75 | def forward(self, x): 76 | return self.single_conv(x) 77 | 78 | 79 | class Down(nn.Module): 80 | """Downscaling with maxpool then double conv""" 81 | 82 | def __init__(self, in_channels, out_channels, bn=True, bias=False, n=1): 83 | super().__init__() 84 | modules = [] 85 | modules.append(nn.MaxPool2d(2)) 86 | modules.append(NConv(in_channels, out_channels, ks=3, bn=bn, bias=bias, n=n)) 87 | self.maxpool_conv = nn.Sequential(*modules) 88 | 89 | def forward(self, x): 90 | return self.maxpool_conv(x) 91 | 92 | 93 | class Up(nn.Module): 94 | """Upscaling then double conv""" 95 | 96 | def __init__(self, in_channels, out_channels, bn=True, bias=False, n=1): 97 | super().__init__() 98 | 99 | self.up = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=True) 100 | self.conv = NConv(in_channels, out_channels, ks=3, bn=bn, bias=bias, n=n) 101 | 102 | def forward(self, x1, x2): 103 | x1 = self.up(x1) 104 | ''' 105 | buttom, right = x1.size(2) % 2, x1.size(3) % 2 106 | x2 = nn.functional.pad(x2, (0, -right, 0, -buttom)) 107 | ''' 108 | diffY = x2.size()[2] - x1.size()[2] 109 | diffX = x2.size()[3] - x1.size()[3] 110 | 111 | x1 = nn.functional.pad(x1, [int(diffX / 2), diffX - int(diffX / 2), 112 | int(diffY / 2), diffY - int(diffY / 2)]) 113 | return self.conv(torch.cat([x1, x2], 1)) 114 | -------------------------------------------------------------------------------- /utils/dataloaders/kitti.py: -------------------------------------------------------------------------------- 1 | from torch.utils.data import Dataset 2 | from os.path import join 3 | from PIL import Image 4 | import cv2 5 | import numpy as np 6 | from PIL import ImageFile 7 | ImageFile.LOAD_TRUNCATED_IMAGES = True 8 | 9 | 10 | class KittiLoader(Dataset): 11 | 12 | """Kitti 2012 and 2015 stereo dataset manager""" 13 | 14 | def __init__(self, dataset, dataset_path, training, validation, transform=None, all_in_ram=True, downsample_training=False): 15 | """ 16 | Parameters 17 | ---------- 18 | dataset: str 19 | Kitti2012 or kitti2015 20 | dataset_path: str 21 | Kitti dataset path 22 | training: bool 23 | Loads training images 24 | validation: bool 25 | Loads validation data 26 | transform: torchvision.transforms 27 | Transform to be applied to all pair 28 | all_in_ram: bool 29 | If true all images are stored in the ram 30 | 31 | Returns 32 | ------- 33 | None 34 | """ 35 | # Store dataset info 36 | self.dataset = dataset 37 | self.dataset_path = dataset_path 38 | self.transform = transform 39 | self.all_in_ram = all_in_ram 40 | 41 | # Set proper range 42 | lower_limit = 0 43 | upper_limit = 194 44 | if self.dataset == 'kitti2015': 45 | upper_limit = 200 46 | if validation and not training: 47 | lower_limit = 160 48 | if training and not validation: 49 | upper_limit = 160 50 | 51 | self.images_path = [] 52 | if self.dataset == 'kitti2015': 53 | 54 | # Generate names 55 | for idx in range(lower_limit, upper_limit): 56 | l_im_path = join(self.dataset_path, 'training', 'image_2', f'{idx:06d}_10.png') 57 | r_im_path = join(self.dataset_path, 'training', 'image_3', f'{idx:06d}_10.png') 58 | d_gt_noc_path = join(self.dataset_path, 'training', 'disp_noc_0', f'{idx:06d}_10.png') 59 | pair = dict(l_im_path=l_im_path, r_im_path=r_im_path, d_gt_noc_path=d_gt_noc_path) 60 | self.images_path.append(pair) 61 | 62 | elif self.dataset == 'kitti2012': 63 | 64 | # Generate names 65 | for idx in range(lower_limit, upper_limit): 66 | l_im_path = join(self.dataset_path, 'training', 'colored_0', f'{idx:06d}_10.png') 67 | r_im_path = join(self.dataset_path, 'training', 'colored_1', f'{idx:06d}_10.png') 68 | d_gt_noc_path = join(self.dataset_path, 'training', 'disp_noc', f'{idx:06d}_10.png') 69 | pair = dict(l_im_path=l_im_path, r_im_path=r_im_path, d_gt_noc_path=d_gt_noc_path) 70 | self.images_path.append(pair) 71 | 72 | # Load all images in the RAM 73 | if self.all_in_ram: 74 | self.pairs = [] 75 | for p in self.images_path: 76 | l_im, r_im, d_gt_noc = self.load_pair(p) 77 | pair = dict() 78 | pair['l_im'] = l_im 79 | pair['r_im'] = r_im 80 | pair['d_gt_noc'] = d_gt_noc 81 | self.pairs.append(pair) 82 | 83 | def load_pair(self, paths): 84 | l_im = Image.open(paths['l_im_path']) 85 | r_im = Image.open(paths['r_im_path']) 86 | d_gt_noc = cv2.imread(paths['d_gt_noc_path'], cv2.IMREAD_ANYDEPTH + cv2.IMREAD_GRAYSCALE) 87 | d_gt_noc = d_gt_noc.astype(np.float32) / 256 88 | 89 | crop_width = 1216 90 | crop_height = 368 91 | 92 | d_gt_noc = d_gt_noc[d_gt_noc.shape[0] - crop_height:d_gt_noc.shape[0], d_gt_noc.shape[1] - crop_width: d_gt_noc.shape[1]] 93 | d_gt_noc = np.expand_dims(d_gt_noc, axis=0) 94 | 95 | w, h = l_im.size 96 | l_im = l_im.crop((w - crop_width, h - crop_height, w, h)) 97 | r_im = r_im.crop((w - crop_width, h - crop_height, w, h)) 98 | 99 | return l_im, r_im, d_gt_noc 100 | 101 | def __len__(self): 102 | return len(self.images_path) 103 | 104 | def __getitem__(self, idx): 105 | if not self.all_in_ram: 106 | l_im, r_im, d_gt_noc = self.load_pair(self.images_path[idx]) 107 | else: 108 | l_im = self.pairs[idx]['l_im'] 109 | r_im = self.pairs[idx]['r_im'] 110 | d_gt_noc = self.pairs[idx]['d_gt_noc'] 111 | 112 | if self.transform is not None: 113 | l_im = self.transform(l_im) 114 | r_im = self.transform(r_im) 115 | 116 | return l_im, r_im, d_gt_noc 117 | -------------------------------------------------------------------------------- /utils/pl/pl_base.py: -------------------------------------------------------------------------------- 1 | from os.path import join 2 | from abc import abstractmethod 3 | from utils.dataloaders.kitti import KittiLoader 4 | from utils.dataloaders.sceneflow import SceneflowLoader 5 | from torch.utils.data import random_split 6 | import pytorch_lightning as pl 7 | from pytorch_lightning.trainer.seed import seed_everything 8 | import torch 9 | from utils.metrics import metrics 10 | 11 | 12 | class PLBase(pl.LightningModule): 13 | 14 | """Pytorch Lighting base template""" 15 | 16 | # ------------------------------------------------------------------- 17 | # Constructor 18 | # ------------------------------------------------------------------- 19 | def __init__(self, hparams): 20 | super().__init__() 21 | seed_everything(hparams.seed) 22 | self.hparams = hparams 23 | self.prepare_datasets() 24 | 25 | # ------------------------------------------------------------------- 26 | # Get torchvision transform for the dataset 27 | # ------------------------------------------------------------------- 28 | @abstractmethod 29 | def get_transform(self): 30 | pass 31 | 32 | # ------------------------------------------------------------------- 33 | # Compute EPE 34 | # ------------------------------------------------------------------- 35 | def compute_epe(self, d_gt, d_est, max_disp=192): 36 | return metrics.compute_epe(d_gt, d_est, max_disp) 37 | 38 | # ------------------------------------------------------------------- 39 | # Compute Err3 40 | # ------------------------------------------------------------------- 41 | def compute_err(self, d_gt, d_est, tau, max_disp=192): 42 | return metrics.compute_err(d_gt, d_est, tau, max_disp) 43 | 44 | # ------------------------------------------------------------------- 45 | # Prepare stereo dataset 46 | # ------------------------------------------------------------------- 47 | def prepare_datasets(self): 48 | transform = self.get_transform() 49 | loader = KittiLoader 50 | if self.hparams.dataset == 'sceneflow': 51 | loader = SceneflowLoader 52 | 53 | dataset_path = join(self.hparams.datasets_path, self.hparams.dataset) 54 | 55 | self.full_train_loader = loader(dataset=self.hparams.dataset, 56 | dataset_path=dataset_path, 57 | training=True, 58 | validation=False, 59 | transform=transform, 60 | downsample_training=True) 61 | self.test_dataset = loader(dataset=self.hparams.dataset, 62 | dataset_path=dataset_path, 63 | training=False, 64 | validation=True, 65 | transform=transform) 66 | 67 | train_size = int(len(self.full_train_loader) * 0.9) 68 | lengths = [train_size, len(self.full_train_loader) - train_size] 69 | self.train_dataset, self.val_dataset = random_split(self.full_train_loader, lengths) 70 | 71 | # ------------------------------------------------------------------- 72 | # PL dataloaders 73 | # ------------------------------------------------------------------- 74 | @pl.data_loader # Decorator used only when data doesn't change 75 | def train_dataloader(self): 76 | loader = torch.utils.data.DataLoader(self.train_dataset, 77 | batch_size=self.hparams.batch_size, 78 | shuffle=self.hparams.shuffle, 79 | num_workers=self.hparams.num_workers, 80 | drop_last=self.hparams.drop_last) 81 | return loader 82 | 83 | @pl.data_loader # Decorator used only when data doesn't change 84 | def val_dataloader(self): 85 | loader = torch.utils.data.DataLoader(self.val_dataset, 86 | batch_size=self.hparams.batch_size, 87 | shuffle=False, 88 | num_workers=self.hparams.num_workers, 89 | drop_last=False) 90 | return loader 91 | 92 | @pl.data_loader # Decorator used only when data doesn't change 93 | def test_dataloader(self): 94 | loader = torch.utils.data.DataLoader(self.test_dataset, 95 | batch_size=1, 96 | shuffle=False, 97 | num_workers=self.hparams.num_workers, 98 | drop_last=False) 99 | return loader 100 | -------------------------------------------------------------------------------- /utils/dataloaders/listflowfile.py: -------------------------------------------------------------------------------- 1 | import os 2 | import os.path 3 | 4 | IMG_EXTENSIONS = [ 5 | '.jpg', '.JPG', '.jpeg', '.JPEG', 6 | '.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP', 7 | ] 8 | 9 | 10 | def is_image_file(filename): 11 | return any(filename.endswith(extension) for extension in IMG_EXTENSIONS) 12 | 13 | 14 | def dataloader(filepath): 15 | filepath += '/' 16 | 17 | ''' 18 | classes = [d for d in os.listdir(filepath) if os.path.isdir(os.path.join(filepath, d))] 19 | image = [img for img in classes if img.find('frames_cleanpass') > -1] 20 | disp = [dsp for dsp in classes if dsp.find('disparity') > -1] 21 | 22 | monkaa_path = filepath + [x for x in image if 'monkaa' in x][0] 23 | monkaa_disp = filepath + [x for x in disp if 'monkaa' in x][0] 24 | ''' 25 | monkaa_path = os.path.join(filepath, 'monkaa', 'frames_cleanpass') 26 | monkaa_disp = os.path.join(filepath, 'monkaa', 'disparity') 27 | 28 | monkaa_dir = os.listdir(monkaa_path) 29 | 30 | all_left_img = [] 31 | all_right_img = [] 32 | all_left_disp = [] 33 | test_left_img = [] 34 | test_right_img = [] 35 | test_left_disp = [] 36 | 37 | for dd in monkaa_dir: 38 | for im in os.listdir(monkaa_path + '/' + dd + '/left/'): 39 | if is_image_file(monkaa_path + '/' + dd + '/left/' + im): 40 | all_left_img.append(monkaa_path + '/' + dd + '/left/' + im) 41 | all_left_disp.append(monkaa_disp + '/' + dd + '/left/' + im.split(".")[0] + '.pfm') 42 | 43 | for im in os.listdir(monkaa_path + '/' + dd + '/right/'): 44 | if is_image_file(monkaa_path + '/' + dd + '/right/' + im): 45 | all_right_img.append(monkaa_path + '/' + dd + '/right/' + im) 46 | ''' 47 | flying_path = filepath + [x for x in image if x == 'frames_cleanpass'][0] 48 | flying_disp = filepath + [x for x in disp if x == 'frames_disparity'][0] 49 | ''' 50 | flying_path = os.path.join(filepath, 'flyingthings3d', 'frames_cleanpass') 51 | flying_disp = os.path.join(filepath, 'flyingthings3d', 'disparity') 52 | flying_dir = flying_path + '/TRAIN/' 53 | subdir = ['A', 'B', 'C'] 54 | 55 | for ss in subdir: 56 | flying = os.listdir(flying_dir + ss) 57 | 58 | for ff in flying: 59 | imm_l = os.listdir(flying_dir + ss + '/' + ff + '/left/') 60 | for im in imm_l: 61 | if is_image_file(flying_dir + ss + '/' + ff + '/left/' + im): 62 | all_left_img.append(flying_dir + ss + '/' + ff + '/left/' + im) 63 | 64 | all_left_disp.append(flying_disp + '/TRAIN/' + ss + '/' + ff + '/left/' + im.split(".")[0] + '.pfm') 65 | 66 | if is_image_file(flying_dir + ss + '/' + ff + '/right/' + im): 67 | all_right_img.append(flying_dir + ss + '/' + ff + '/right/' + im) 68 | 69 | flying_dir = flying_path + '/TEST/' 70 | 71 | subdir = ['A', 'B', 'C'] 72 | 73 | for ss in subdir: 74 | flying = os.listdir(flying_dir + ss) 75 | 76 | for ff in flying: 77 | imm_l = os.listdir(os.path.join(flying_dir, ss, ff, 'left')) 78 | for im in imm_l: 79 | if is_image_file(os.path.join(flying_dir, ss, ff, 'left', im)): 80 | test_left_img.append(os.path.join(flying_dir, ss, ff, 'left', im)) 81 | 82 | test_left_disp.append(os.path.join(flying_disp, 'TEST', ss, ff, 'left', im.split(".")[0] + '.pfm')) 83 | 84 | if is_image_file(os.path.join(flying_dir, ss, ff, 'right', im)): 85 | test_right_img.append(os.path.join(flying_dir, ss, ff, 'right', im)) 86 | ''' 87 | driving_dir = filepath + [x for x in image if 'driving' in x][0] + '/' 88 | driving_disp = filepath + [x for x in disp if 'driving' in x][0] 89 | ''' 90 | driving_dir = os.path.join(filepath, 'driving', 'frames_cleanpass') 91 | driving_disp = os.path.join(filepath, 'driving', 'disparity') 92 | 93 | subdir1 = ['15mm_focallength', '15mm_focallength'] 94 | subdir2 = ['scene_backwards', 'scene_forwards'] 95 | subdir3 = ['fast', 'slow'] 96 | 97 | for i in subdir1: 98 | for j in subdir2: 99 | for k in subdir3: 100 | imm_l = os.listdir(os.path.join(driving_dir, i, j, k, 'left')) 101 | for im in imm_l: 102 | if is_image_file(os.path.join(driving_dir, i, j, k, 'left', im)): 103 | all_left_img.append(os.path.join(driving_dir, i, j, k, 'left', im)) 104 | all_left_disp.append( 105 | os.path.join(driving_disp, i, j, k, 'left', im.split(".")[0] + '.pfm')) 106 | 107 | if is_image_file(os.path.join(driving_dir, i, j, k, 'right', im)): 108 | all_right_img.append(os.path.join(driving_dir, i, j, k, 'right', im)) 109 | 110 | return all_left_img, all_right_img, all_left_disp, test_left_img, test_right_img, test_left_disp 111 | -------------------------------------------------------------------------------- /pl_template.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from utils.pl.pl_base import PLBase 3 | from torchvision import transforms 4 | from model.default import DefaultModel 5 | from adabound import AdaBound 6 | 7 | 8 | class FEStereo(PLBase): 9 | 10 | # ------------------------------------------------------------------- 11 | # Training details - Network definition 12 | # ------------------------------------------------------------------- 13 | def __init__(self, hparams): 14 | """ Constructor 15 | 16 | Params 17 | ------ 18 | hparams: 19 | Contains the training configuration details 20 | """ 21 | super().__init__(hparams) 22 | 23 | # Prepare network 24 | if self.hparams.model_type == 'default': 25 | self.net = DefaultModel(self.hparams.max_disp) 26 | 27 | # Additional log 28 | self.avg_train_loss = None 29 | 30 | # ------------------------------------------------------------------- 31 | # Get image transform 32 | # ------------------------------------------------------------------- 33 | def get_transform(self): 34 | # Prepare transform 35 | mean = [0.0, 0.0, 0.0] 36 | std = [1.0, 1.0, 1.0] 37 | transform = transforms.Compose([transforms.ToTensor(), 38 | transforms.Normalize(mean, std)]) 39 | return transform 40 | 41 | # ------------------------------------------------------------------- 42 | # Training details - Forward 43 | # ------------------------------------------------------------------- 44 | def forward(self, left, right): 45 | return self.net.forward(left, right) 46 | 47 | # ------------------------------------------------------------------- 48 | # Training details - Train step 49 | # ------------------------------------------------------------------- 50 | def training_step(self, batch, batch_nb): 51 | im_left, im_right, disp_l = batch 52 | output = self.forward(im_left, im_right) 53 | 54 | if self.hparams.dataset == 'sceneflow': 55 | mask = disp_l < self.hparams.max_disp 56 | else: 57 | mask = disp_l > 0 58 | mask.detach_() 59 | 60 | loss = torch.nn.functional.smooth_l1_loss(output[mask], disp_l[mask], size_average=True) 61 | 62 | if batch_nb == 0: 63 | self.avg_train_loss = 0 64 | 65 | self.avg_train_loss += loss.item() 66 | 67 | # Loss per stage to print in progresss bar 68 | pb_dict = dict() 69 | pb_dict[f'avg_train_loss'] = f'({self.avg_train_loss/(batch_nb+1):4f})' 70 | 71 | return {'loss': loss, 72 | 'progress_bar': pb_dict, 73 | 'log': {'loss': loss}} 74 | 75 | # ------------------------------------------------------------------- 76 | # Training details - Validation step 77 | # ------------------------------------------------------------------- 78 | def validation_step(self, batch, batch_nb): 79 | im_left, im_right, disp_l = batch 80 | output = self.forward(im_left, im_right) 81 | 82 | epe = self.compute_epe(disp_l, output, max_disp=self.hparams.max_disp) 83 | err3 = self.compute_err(disp_l, output, max_disp=self.hparams.max_disp, tau=3) 84 | 85 | return {'epe': epe, 'err3': err3} 86 | 87 | # ------------------------------------------------------------------- 88 | # Training details - Validation ends 89 | # ------------------------------------------------------------------- 90 | def validation_epoch_end(self, outputs): 91 | avg_epe = torch.stack([x['epe'] for x in outputs]).mean() 92 | avg_err3 = torch.stack([x['err3'] for x in outputs]).mean() 93 | return {'val_loss': avg_epe, 94 | 'progress_bar': {'val_loss': avg_epe}, 95 | 'log': {'val_epe': avg_epe, 'val_err3': avg_err3}} 96 | 97 | # ------------------------------------------------------------------- 98 | # Training details - Optimizer 99 | # ------------------------------------------------------------------- 100 | def configure_optimizers(self): 101 | lr = self.hparams.lr 102 | gamma_step = self.hparams.gamma_step 103 | gamma = self.hparams.gamma 104 | if self.hparams.optimizer == 'adam': 105 | optimizer = torch.optim.Adam(self.parameters(), lr=lr, betas=(0.9, 0.999)) 106 | if self.hparams.scheduler == 'steplr': 107 | scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=gamma_step, gamma=gamma) 108 | elif self.hparams.scheduler == 'multisteplr': 109 | scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=list(range(200, 300)), gamma=gamma) 110 | elif self.hparams.scheduler == 'plateau': 111 | return [optimizer], [torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, 'min', verbose=True, patience=25)] 112 | return [optimizer], [scheduler] 113 | elif self.hparams.optimizer == 'adabound': 114 | optimizer = AdaBound(self.parameters(), lr=lr, final_lr=0.1) 115 | return optimizer 116 | 117 | # ------------------------------------------------------------------- 118 | # Test details - Test step 119 | # ------------------------------------------------------------------- 120 | def test_step(self, batch, batch_nb): 121 | im_left, im_right, disp_l = batch 122 | output = self.forward(im_left, im_right) 123 | 124 | epe = self.compute_epe(disp_l, output, max_disp=self.hparams.max_disp) 125 | err2 = self.compute_err(disp_l, output, tau=2) 126 | err3 = self.compute_err(disp_l, output, tau=3) 127 | err4 = self.compute_err(disp_l, output, tau=4) 128 | err5 = self.compute_err(disp_l, output, tau=5) 129 | 130 | return {'epe': epe, 'err2': err2, 'err3': err3, 'err4': err4, 'err5': err5} 131 | 132 | # ------------------------------------------------------------------- 133 | # Test details - Test ends 134 | # ------------------------------------------------------------------- 135 | def test_epoch_end(self, outputs): 136 | avg_epe = torch.stack([x['epe'] for x in outputs]).mean() 137 | avg_err2 = torch.stack([x['err2'] for x in outputs]).mean() 138 | avg_err3 = torch.stack([x['err3'] for x in outputs]).mean() 139 | avg_err4 = torch.stack([x['err4'] for x in outputs]).mean() 140 | avg_err5 = torch.stack([x['err5'] for x in outputs]).mean() 141 | 142 | return {'test_err': avg_epe, 143 | 'progress_bar': {'test_err': avg_epe}, 144 | 'log': {'test_err2': avg_err2, 'test_err3': avg_err3, 'test_err4': avg_err4, 145 | 'test_err5': avg_err5, 'test_epe': avg_epe}} 146 | -------------------------------------------------------------------------------- /model/default.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | sys.path.append(os.getcwd()) 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from model.unet_parts import NConv, Down, Up 8 | import math 9 | from torchsummary import summary 10 | import click 11 | from utils.torch_timer import TorchTimer 12 | try: 13 | from cost_volume import cost_volume 14 | except e: 15 | pass 16 | 17 | 18 | class disparityregression(nn.Module): 19 | def __init__(self, start, end, stride=1, dtype=torch.float32): 20 | super(disparityregression, self).__init__() 21 | self.disp = torch.arange(start * stride, end * stride, stride, out=torch.FloatTensor()).view(1, -1, 1, 1).cuda() 22 | if dtype == torch.half: 23 | self.disp = self.disp.half() 24 | 25 | def forward(self, x): 26 | disp = self.disp.repeat(x.size()[0], 1, x.size()[2], x.size()[3]) 27 | out = torch.sum(x * disp, 1, keepdim=True) 28 | return out 29 | 30 | 31 | class FeatureNetwork(nn.Module): 32 | def __init__(self, init_channels, levels, block_size): 33 | super(FeatureNetwork, self).__init__() 34 | self.init_channels = init_channels 35 | self.levels = levels 36 | self.block_size = block_size 37 | modules = [] 38 | modules.append(nn.Conv2d(3, self.init_channels, 3, 1, 1)) 39 | modules.append(NConv(self.init_channels, self.init_channels, ks=3, stride=2, pad=1, bn=True, bias=False, relu=True, n=1)) 40 | 41 | for i in range(self.levels): 42 | in_channels = (2**i) * self.init_channels 43 | out_channels = (2**(i + 1)) * self.init_channels 44 | modules.append(Down(in_channels, out_channels, n=self.block_size)) 45 | self.down_network = nn.ModuleList(modules) 46 | self.upsample = Up(12, 8, n=self.block_size) 47 | 48 | def forward(self, x): 49 | out = [] 50 | out.append(self.down_network[0](x)) 51 | for i in range(1, len(self.down_network)): 52 | out.append(self.down_network[i].forward(out[-1])) 53 | return self.upsample(out[-1], out[-2]) 54 | 55 | 56 | class PostFeatureNetwork(nn.Module): 57 | def __init__(self, channels_3d, layers_3d, growth_rate, max_disp): 58 | super(PostFeatureNetwork, self).__init__() 59 | self.channels_3d = channels_3d 60 | self.layers_3d = layers_3d 61 | self.growth_rate = growth_rate 62 | self.max_disp = max_disp 63 | 64 | # Left processing 65 | modules = [] 66 | modules.append(Down(self.max_disp, self.max_disp, 1, n=1)) 67 | modules.append(NConv(self.max_disp, self.max_disp, ks=3, n=2)) 68 | self.cost_post = nn.Sequential(*modules) 69 | 70 | self.up = Up(self.max_disp * 2, self.max_disp, n=2) 71 | self.last_conv = NConv(self.max_disp, self.max_disp, ks=3) 72 | 73 | def forward(self, x): 74 | out = self.cost_post(x) 75 | out = self.up.forward(out, x) 76 | out = self.last_conv(out) 77 | return out 78 | 79 | 80 | class DefaultModel(nn.Module): 81 | 82 | def __init__(self, max_disp=192, cuda_kernel=False): 83 | super(DefaultModel, self).__init__() 84 | 85 | self.levels = 3 86 | self.init_channels = 1 87 | self.layers_3d = 4 88 | self.channels_3d = 4 89 | self.growth_rate = [4, 1, 1] 90 | self.block_size = 2 91 | self.cuda_kernel = cuda_kernel 92 | self.max_disp = max_disp // 2**(self.levels) 93 | 94 | self.feature_network = FeatureNetwork(init_channels=self.init_channels, 95 | levels=self.levels, 96 | block_size=self.block_size) 97 | 98 | self.cost_post = PostFeatureNetwork(self.channels_3d, 99 | self.layers_3d, 100 | self.growth_rate, 101 | self.max_disp) 102 | 103 | for m in self.modules(): 104 | if isinstance(m, nn.Conv2d): 105 | n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels 106 | m.weight.data.normal_(0, math.sqrt(2. / n)) 107 | elif isinstance(m, nn.Conv3d): 108 | n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels 109 | m.weight.data.normal_(0, math.sqrt(2. / n)) 110 | elif isinstance(m, nn.BatchNorm2d): 111 | m.weight.data.fill_(1) 112 | m.bias.data.zero_() 113 | elif isinstance(m, nn.BatchNorm3d): 114 | m.weight.data.fill_(1) 115 | m.bias.data.zero_() 116 | elif isinstance(m, nn.Linear): 117 | m.bias.data.zero_() 118 | 119 | def build_cost_volume(self, feat_l, feat_r, stride=1): 120 | if feat_l.dtype == torch.float32: 121 | cost = torch.zeros(feat_l.size()[0], self.max_disp // stride, feat_l.size()[2], feat_l.size()[3]).cuda() 122 | else: 123 | cost = torch.zeros(feat_l.size()[0], self.max_disp // stride, feat_l.size()[2], feat_l.size()[3]).cuda().half() 124 | 125 | for i in range(0, self.max_disp, stride): 126 | cost[:, i // stride, :, :i] = feat_l[:, :, :, :i].abs().sum(1) 127 | if i > 0: 128 | cost[:, i // stride, :, i:] = torch.norm(feat_l[:, :, :, i:] - feat_r[:, :, :, :-i], 1, 1) 129 | else: 130 | cost[:, i // stride, :, i:] = torch.norm(feat_l[:, :, :, :] - feat_r[:, :, :, :], 1, 1) 131 | 132 | return cost.contiguous() 133 | 134 | def regression(self, cost, left): 135 | dtype = torch.float32 136 | if cost.dtype == torch.half: 137 | dtype = torch.half 138 | img_size = left.size() 139 | pred_low_res = disparityregression(0, self.max_disp, dtype=dtype)(F.softmax(-cost, dim=1)) 140 | pred_low_res = pred_low_res * img_size[2] / pred_low_res.size(2) 141 | disp_up = F.interpolate(pred_low_res, (img_size[2], img_size[3]), mode='bilinear', align_corners=True) 142 | return disp_up 143 | 144 | def forward(self, left, right): 145 | bs = left.size(0) 146 | left_and_right = torch.cat((left, right), 0) 147 | feats = self.feature_network.forward(left_and_right) 148 | l_feat = feats[0:bs, :, :, :] 149 | r_feat = feats[bs:bs * 2, :, :, :] 150 | 151 | # Cost volume pre 152 | if self.cuda_kernel: 153 | new_l_feat = l_feat.squeeze(0) 154 | new_r_feat = r_feat.squeeze(0) 155 | cost = cost_volume(new_l_feat, new_r_feat, self.max_disp) 156 | cost = cost.unsqueeze(0) 157 | else: 158 | cost = self.build_cost_volume(l_feat, r_feat) 159 | 160 | # Cost volume post processing 161 | cost = self.cost_post(cost) 162 | 163 | # Regression 164 | disp_up = self.regression(cost, left) 165 | 166 | return disp_up 167 | 168 | 169 | @click.command() 170 | @click.option('--benchmark/--no-benchmark', default=False, help='Benchmark speed') 171 | @click.option('--tensorrt/--no-tensorrt', default=False, help='Use tensorrt for benchmark') 172 | @click.option('--fp16/--no-fp16', default=False, help='fp16') 173 | def main(benchmark, tensorrt, fp16): 174 | # Print summary 175 | fsa = DefaultModel(max_disp=192, cuda_kernel=False).cuda() 176 | summary(fsa, [(3, 368, 1218), (3, 368, 1218)]) 177 | if benchmark: 178 | fsa = DefaultModel(max_disp=192, cuda_kernel=True).cuda() 179 | #from cost_volume import cost_volume 180 | #fsa.build_cost_volume = cost_volume 181 | 182 | print('Speed benchmark:') 183 | fsa.eval() 184 | tt = TorchTimer(times=200, warmup=10) 185 | torch.backends.cudnn.benchmark = True 186 | 187 | from torchvision import transforms 188 | # Data preparation 189 | mean = [0.0, 0.0, 0.0] 190 | std = [1.0, 1.0, 1.0] 191 | transform = transforms.Compose([transforms.ToTensor(), 192 | transforms.Normalize(mean, std)]) 193 | 194 | left, right = torch.rand((3, 368, 1218)), torch.rand((3, 368, 1218)) 195 | left = left.unsqueeze(0).cuda() 196 | right = right.unsqueeze(0).cuda() 197 | left_and_right = torch.cat((left, right), 0) 198 | 199 | if fp16: 200 | left_and_right = left_and_right.half() 201 | left = left.half() 202 | right = right.half() 203 | fsa = fsa.half() 204 | 205 | if tensorrt: 206 | from torch2trt import torch2trt 207 | fsa.feature_network = torch2trt(fsa.feature_network, [left_and_right], 208 | fp16_mode=fp16, max_batch_size=2) 209 | feats = fsa.feature_network(left_and_right) 210 | l_feat = feats[0:1, :, :, :] 211 | r_feat = feats[1:2, :, :, :] 212 | cost = fsa.build_cost_volume(l_feat, r_feat) 213 | fsa.cost_post = torch2trt(fsa.cost_post, [cost], 214 | fp16_mode=fp16, max_batch_size=1) 215 | 216 | with torch.no_grad(): 217 | 218 | # Full network 219 | full_mean, full_std, _ = tt.run(fsa, left, right) 220 | print(f'Full network elapsed mean time {full_mean:0.8f} s with std {full_std: 0.8f} s') 221 | print() 222 | 223 | # Convs 224 | conv_mean, conv_std, feats = tt.run(fsa.feature_network, left_and_right) 225 | print(f'Feature Conv elapsed mean time {conv_mean:0.8f} s with std {conv_std: 0.8f} s') 226 | 227 | # Cost volume 228 | l_feat = feats[0:1, :, :, :] 229 | r_feat = feats[1:2, :, :, :] 230 | l_feat.squeeze_(0) 231 | r_feat.squeeze_(0) 232 | cost_mean, cost_std, cost = tt.run(cost_volume, l_feat, r_feat, fsa.max_disp) 233 | cost.unsqueeze_(0) 234 | print(f'Cost elapsed mean time {cost_mean:0.8f} s with std {cost_std: 0.8f} s') 235 | 236 | # Post cost 237 | post_cost_mean, post_cost_std, proccesed_cost = tt.run(fsa.cost_post, cost) 238 | print(f'Post Cost elapsed mean time {post_cost_mean:0.8f} s with std {post_cost_std: 0.8f} s') 239 | 240 | # Regression 241 | r_mean, r_std, out = tt.run(fsa.regression, cost, left) 242 | print(f'Regression elapsed mean time {r_mean:0.8f} s with std {r_std: 0.8f} s') 243 | 244 | # Total time by parts 245 | total = conv_mean + cost_mean + post_cost_mean + r_mean 246 | print(f'Total summing means {total}') 247 | 248 | 249 | if __name__ == "__main__": 250 | main() 251 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------