keyword stringclasses 7
values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29
values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14
values |
|---|---|---|---|---|---|---|---|
3D | marcdcfischer/PUNet | src/modules/instruction_model_simple.py | .py | 32,549 | 488 | from argparse import ArgumentParser, Namespace
import pytorch_lightning as pl
import torch
import torch.distributed as dist
from torch import nn
from torch.optim import AdamW
import torch.optim.lr_scheduler as lr_scheduler
from typing import Optional, Any, Dict, Union, List, Tuple
import pathlib as plb
from src.modules... | Python |
3D | marcdcfischer/PUNet | src/modules/instruction_model.py | .py | 55,172 | 757 | from argparse import ArgumentParser, Namespace
import pytorch_lightning as pl
import torch
import torch.distributed as dist
from torch.optim import AdamW
import torch.optim.lr_scheduler as lr_scheduler
from typing import Optional, Any, Dict, Union, List, Tuple
import pathlib as plb
from src.modules.architectures.moment... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/instruction_pool.py | .py | 2,896 | 52 | import torch
import torch.nn as nn
from src.modules.blocks.query_encodings import LearnedNormedQuery, LearnedNormedInstruction
from typing import Tuple, Optional
import einops
class InstructionPool(nn.Module):
def __init__(self,
instruction_pool_size: int, # Atm expects an instruction pool size ... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/sia_block_deep.py | .py | 13,630 | 222 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Sequence, Tuple, Optional, List
from src.modules.blocks.attentive_mechanism_masked import WindowedMaskedAttentionBlock
from src.modules.blocks.query_encodings import DeepInstructedAttentionPositionScores
from einops import rearrange
i... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/sia_res_block_deep.py | .py | 4,634 | 100 | import torch
import torch.nn as nn
import torch.nn.functional as F
from src.modules.blocks.sia_block_deep import DeepShiftedInstructedAttentionBlock
from typing import Sequence, Optional, List
from monai.networks.blocks import Convolution
from monai.networks.layers.utils import get_act_layer, get_norm_layer
from iterto... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/attentive_mechanism_masked.py | .py | 2,819 | 74 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional, Tuple
from src.modules.blocks.attention import WindowedMaskedAttention
from torch.utils.checkpoint import checkpoint
# see https://github.com/KMnP/vpt/blob/e2dd70a5ee291d398d002e6963ddbe0f66f58038/src/models/vit_adapter/ad... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/mlp.py | .py | 542 | 20 | import torch
from torch import nn
class MLP(nn.Module):
def __init__(self,
in_channels: int,
widening_factor: int = 2): # Perceiver used 4
super().__init__()
self.linear_1 = nn.Linear(in_channels, in_channels * widening_factor)
self.act_1 = nn.LeakyReLU(... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/similarity_aggregation.py | .py | 1,732 | 31 | import torch
import torch.nn.functional as F
def similarity_aggregation(latents, instructions, mean_aggregation: bool = False, top_k_selection: bool = False, soft_selection_sigma: float = 0.1):
"""
:param latents: [B, H*W*D, C]
:param instructions: [B, I, N, C]
:return: [B, I, H*W*D]
"""
# Not... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/query_encodings.py | .py | 31,761 | 450 | import torch
import torch.nn as nn
import einops
import math
from typing import Tuple, Optional, Sequence
import warnings
# see e.g. https://github.com/lucidrains/x-transformers/blob/55ca5d96c8b850b064177091f7a1dcfe784b24ce/x_transformers/x_transformers.py#L116
# Note: Perceiver uses slightly different formulation ba... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/sia_up_block_deep.py | .py | 4,587 | 93 | import torch
import torch.nn as nn
import torch.nn.functional as F
from src.modules.blocks.sia_block_deep import DeepShiftedInstructedAttentionBlock
from typing import Sequence, Optional, List
from monai.networks.blocks import Convolution
from monai.networks.layers.utils import get_act_layer, get_norm_layer
from iterto... | Python |
3D | marcdcfischer/PUNet | src/modules/blocks/attention.py | .py | 5,610 | 132 | import torch
from torch import nn
from typing import Optional
import einops
from torch.utils.checkpoint import checkpoint
class Attention(nn.Module):
def __init__(self,
q_channels: int,
kv_channels: Optional[int] = None,
heads_channels: Optional[int] = None,
... | Python |
3D | marcdcfischer/PUNet | src/modules/losses/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/modules/losses/contrastive_protos_teacher.py | .py | 18,421 | 241 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Union, Dict, Tuple, List, Optional
import math
import einops
import numpy as np
class ContrastiveProtosTeacherLoss(nn.Module):
def __init__(self,
reduction_factor: float = 4., # Grid sampling to make loss calc ... | Python |
3D | marcdcfischer/PUNet | src/modules/losses/focal.py | .py | 2,939 | 57 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Tuple, Optional
class FocalLoss(nn.Module):
def __init__(self,
out_channels: int,
loss_weight: float = 1.,
alpha_background: float = 0.1,
alpha_foreground: floa... | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/momentum_model_simple.py | .py | 3,767 | 83 | import torch
import torch.nn as nn
from argparse import ArgumentParser, Namespace
from typing import Union, Dict, Optional, Tuple, List
from src.modules.architectures.baseline_unet import MonaiUNet
from src.modules.architectures.baseline_unetr import MonaiUNETR
from src.modules.architectures.baseline_swin_unetr import ... | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/swin_unetr_deep.py | .py | 28,913 | 456 | import einops
import torch
import torch.nn as nn
import torch.nn.functional as F
from argparse import ArgumentParser, Namespace
from typing import Union, Dict, Optional, Tuple, List
from monai.networks.blocks import Convolution, ResidualUnit, UnetResBlock, UnetUpBlock
from src.modules.blocks.sia_res_block_deep import D... | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/momentum_model.py | .py | 4,150 | 84 | import torch
import torch.nn as nn
from argparse import ArgumentParser, Namespace
from typing import Union, Dict, Optional, Tuple, List
# from src.modules.architectures.interpreter import Interpreter as Architecture
from src.modules.architectures.swin_unetr_deep import DeepSIAUNetr
import warnings
class MomentumModel... | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/baseline_unet.py | .py | 2,029 | 57 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Union, Dict
from argparse import Namespace, ArgumentParser
from monai.networks.nets import UNet
from monai.networks.layers.utils import get_act_layer, get_norm_layer
# Monai UNet model
class MonaiUNet(nn.Module):
def __init__(se... | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/baseline_unetr.py | .py | 3,650 | 81 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Union, Dict
from argparse import Namespace, ArgumentParser
from monai.networks.nets import UNETR
import math
from monai.networks.layers.utils import get_act_layer, get_norm_layer
# Monai UNETR model
# see https://github.com/Project-... | Python |
3D | marcdcfischer/PUNet | src/modules/architectures/baseline_swin_unetr.py | .py | 3,482 | 78 | import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import Union, Dict
from argparse import Namespace, ArgumentParser
from monai.networks.nets import SwinUNETR
import math
from monai.networks.layers.utils import get_act_layer, get_norm_layer
# Monai UNETR model
class MonaiSwinUNETR(nn.Modul... | Python |
3D | marcdcfischer/PUNet | src/utils/initialization.py | .py | 10,484 | 189 | from typing import Type
import pytorch_lightning as pl
import pathlib as plb
from pytorch_lightning import Trainer
from pytorch_lightning.utilities.cloud_io import load as pl_load
import torch
from src.utils import callbacks, logging_custom
import warnings
def setup_training(hparams, cls_dm: Type[pl.LightningDataModu... | Python |
3D | marcdcfischer/PUNet | src/utils/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/utils/logging_custom.py | .py | 1,175 | 30 | from datetime import datetime
import pytorch_lightning as pl
import pathlib as plb
def setup_loggers(hparams, path_root):
timestamp = datetime.now().strftime('%m%d%H%M%S')
run_name = f'{plb.Path(path_root).stem}_{timestamp}'
hparams.__dict__['run_name'] = run_name
log_dir = plb.Path(path_root) / 'log... | Python |
3D | marcdcfischer/PUNet | src/utils/callbacks.py | .py | 1,727 | 43 | from argparse import ArgumentParser
import pathlib as plb
import pytorch_lightning as pl
import os
def setup_checkpointing(hparams, save_top_k: int = 3):
# Note: requires hparams attributes that might only be set in setup_loggers()
# configure checkpoint directory
if hparams.s3_bucket.strip(' ') and hpar... | Python |
3D | marcdcfischer/PUNet | src/utils/aws.py | .py | 6,010 | 164 | import os
from typing import Optional
import pathlib as plb
import boto3
import sys
import threading
import logging
from botocore.exceptions import ClientError
from argparse import ArgumentParser
logger = logging.getLogger(__name__)
MB = 1024 * 1024
# see https://docs.aws.amazon.com/code-samples/latest/catalog/code-c... | Python |
3D | marcdcfischer/PUNet | src/utils/plotting/similarities_student_teacher.py | .py | 7,531 | 132 | import matplotlib
matplotlib.use('Agg')
import os
import numpy as np
import matplotlib.pyplot as plt
from torchvision.utils import make_grid
from typing import Optional, Dict
from scipy import ndimage
import torch
import pathlib as plb
def visualize_similarities_student_teacher(plots: dict,
... | Python |
3D | marcdcfischer/PUNet | src/utils/plotting/image_grid.py | .py | 3,538 | 65 | import matplotlib
matplotlib.use('Agg')
import torch
import matplotlib.pyplot as plt
from torchvision.utils import make_grid
import itertools
import os
import math
from typing import Optional, List
import torch.nn.functional as F
def plot_grid_middle(x,
targets: Optional[torch.Tensor] = None,
... | Python |
3D | marcdcfischer/PUNet | src/utils/plotting/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/data/conversion_monai.py | .py | 2,202 | 50 | import torch
import torchio as tio
import pathlib as plb
from typing import Union, Optional, Tuple
import pandas as pd
import nibabel as nib
import numpy as np
def convert_subjects(df_data: pd.DataFrame,
with_coords: bool = True,
visualize: bool = False):
subject_dicts =... | Python |
3D | marcdcfischer/PUNet | src/data/collate.py | .py | 256 | 10 | from torch.utils.data._utils.collate import default_collate
def collate_list(batch):
"""Flattens list and passes it to standard collate function"""
batch = [item_ for elements_ in batch for item_ in elements_]
return default_collate(batch)
| Python |
3D | marcdcfischer/PUNet | src/data/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/data/loader_monai.py | .py | 13,297 | 208 | from torch.utils.data import WeightedRandomSampler, RandomSampler # Would this (random_split) be a good option for ddp?
from argparse import ArgumentParser, Namespace
from src.data.distributed_wrapper import DistributedSamplerWrapper
import torch
import pytorch_lightning as pl
from typing import Union, Dict, Optional
... | Python |
3D | marcdcfischer/PUNet | src/data/transforms_monai.py | .py | 17,243 | 247 | from typing import Optional, Tuple, List, Type
import monai.transforms as mtransforms
import itertools
import pathlib as plb
# See https://github.com/Project-MONAI/tutorials/blob/master/3d_segmentation/unetr_btcv_segmentation_3d_lightning.ipynb for a recent example
def generate_transforms(patch_size_students: List[Tu... | Python |
3D | marcdcfischer/PUNet | src/data/distributed_wrapper.py | .py | 2,876 | 86 | # Code has been directly copied from
# https://github.com/catalyst-team/catalyst/blob/master/catalyst/data/sampler.py
# https://github.com/catalyst-team/catalyst/blob/df9e07f962ca61986a31c602a4511ad983dad028/catalyst/data/dataset/torch.py#L13
import torch
from torch.utils.data import DistributedSampler, Dataset
from t... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/__init__.py | .py | 0 | 0 | null | Python |
3D | marcdcfischer/PUNet | src/data/datasets/gather_tcia_btcv.py | .py | 5,085 | 98 | from typing import Union, Dict, Tuple
from argparse import ArgumentParser, Namespace
import pathlib as plb
import pandas as pd
import numpy as np
from typing import List
from src.data.datasets.gather_data import _generate_splits, _mask_domains
def generate_dataframes(conf: Union[Dict, Namespace]):
df_dirs = _gat... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/prepare_tcia.py | .py | 5,147 | 108 | import pathlib as plb
import re
import csv
import nibabel as nib
import numpy as np
from sklearn import preprocessing
from src.data.datasets.pre_processing import _rescale
from typing import Tuple
def _process(path_img,
path_lbl,
coords,
dir_out,
classes: Tuple[int,... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/gather_ctorg.py | .py | 4,237 | 86 | from typing import Union, Dict, Tuple
from argparse import ArgumentParser, Namespace
import pathlib as plb
import pandas as pd
import numpy as np
from typing import List
from src.data.datasets.gather_data import _generate_splits, _mask_domains
def generate_dataframes(conf: Union[Dict, Namespace]):
df_dirs = _gat... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/prepare_btcv.py | .py | 5,370 | 111 | import pathlib as plb
import re
import csv
import nibabel as nib
import numpy as np
from sklearn import preprocessing
from src.data.datasets.pre_processing import _rescale
from typing import Tuple
def _process(path_img,
path_lbl,
coords,
dir_out,
classes: Tuple[int,... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/pre_processing.py | .py | 8,278 | 170 | import dicom2nifti
import nibabel as nib
from monai import transforms as mtransforms
from nibabel.orientations import ornt_transform, axcodes2ornt, inv_ornt_aff, apply_orientation, io_orientation, aff2axcodes
from typing import Tuple, Optional, List
import numpy as np
import pathlib as plb
from skimage import transfor... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/prepare_ctorg.py | .py | 3,657 | 92 | import pathlib as plb
import re
import csv
import nibabel as nib
import numpy as np
from sklearn import preprocessing
from src.data.datasets.pre_processing import _rescale
from typing import Tuple
from p_tqdm import p_map
def _process(path_img,
path_lbl,
dir_out,
classes: Tuple[... | Python |
3D | marcdcfischer/PUNet | src/data/datasets/gather_data.py | .py | 3,327 | 73 | from typing import Union, Dict, Tuple
from argparse import ArgumentParser, Namespace
import pathlib as plb
import pandas as pd
import numpy as np
from sklearn.model_selection import KFold, train_test_split
import math
def _generate_splits(df,
domains: Tuple[str, ...] = ('tcia', 'btcv'),
... | Python |
3D | marcdcfischer/PUNet | shell/train.sh | .sh | 5,455 | 119 | #!/bin/bash
# Check amount of arguments
if [[ $# -lt 14 ]] ; then
echo 'A wrong amount of arguments (< 14) has been provided.'
exit 1
fi
# load env variables
username="${14}"
CLUSTER="my_cluster" # EDIT ME
PYTHON="/my/python/versions/3.9.8/bin/python" # EDIT ME
CODE="/my/code/" # EDIT ME
export PYTHONPATH... | Shell |
3D | marcdcfischer/PUNet | shell/cfgs.sh | .sh | 7,069 | 236 | #!/bin/bash
# Configuration based on selected variants
echo "Using configurations -
training: ${cfg_training},
frozen: ${cfg_frozen},
bias: ${cfg_bias},
labels: ${cfg_labels},
downstream: ${cfg_downstream},
dimensions: ${cfg_dimensions},
architecture: ${cfg_architecture},
prompting: ${cfg_prompting},
adaptation: ${cfg_... | Shell |
3D | marcdcfischer/PUNet | shell/train_p2.sh | .sh | 1,442 | 35 | #!/bin/bash
# call via nohup ./train_p2.sh 0 &
cd "$(dirname ${0})" || exit
gpu=$1
# See common/cfgs.sh for all options
cfg_training="meta"
cfg_frozen="frozen"
cfg_bias="all"
cfg_labels="0"
cfg_downstream=true
cfg_dimensions="2d"
cfg_architecture="wip"
cfg_prompting="full"
cfg_adaptation="prompting"
cfg_dataset="tcia... | Shell |
3D | marcdcfischer/PUNet | shell/train_p1.sh | .sh | 1,498 | 33 | #!/bin/bash
# call via nohup ./train_p1.sh 0 &
cd "$(dirname ${0})" || exit
gpu=$1
# See common/cfgs.sh for all options
cfg_training=("meta_self")
cfg_frozen=("nonfrozen")
cfg_bias=("all")
cfg_labels=("0")
cfg_downstream=(false)
cfg_dimensions=("2d")
cfg_architecture=("wip")
cfg_prompting=("full")
cfg_adaptation=("pr... | Shell |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/PoseEMat.m | .m | 1,222 | 58 | % PoseEMat - estimate the pose from essential matrix with SVD.
%
% Usage:
% [R1, R2, t1, t2] = PoseEMat(E)
%
% Input:
% E : essential matrix
%
% Output:
% R1 : 3x3 rotation matrix 1
% R2 : 3x3 rotation matrix 2
% t1 : 3x1 translation vector 1
% t2 ... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/peig5pt.m | .m | 144,129 | 287 | % fast implementation of the 5pt relative pose problem
%
% by M. Bujnak, Z. Kukelova (c)sep2008
%
%
% Please refer to the following paper, when using this code :
%
% Kukelova, Z., Bujnak, M. and Pajdla, Polynomial eigenvalue solutions
% to the 5-pt and 6-pt relative pose problems, BMVC 2008, Leeds, Sept. 20... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/merge2graphs.m | .m | 5,528 | 154 | function GraphAB = merge2graphs(GraphA,GraphB)
commonFrames = intersect(GraphA.frames,GraphB.frames);
[newFramesFromB,indexNewFramesFromB] = setdiff(GraphB.frames,GraphA.frames);
if isempty(commonFrames)
fprintf('no common frames!\n');
GraphAB = [];
return;
end
GraphAB = GraphA;
if isempty(newFramesFr... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/extractFocalFromEXIF.m | .m | 10,459 | 311 | function focal_pixels = extractFocalFromEXIF(imageFileName)
focal_pixels = [];
% Add iphone support
% Refer to http://phototour.cs.washington.edu/focal.html
% list extracted from Bundler by Noah Snavely
ccd_widths = {...
'Asahi Optical Co.,Ltd. PENTAX Optio330RS', 7.176;
'Canon Canon DIGITAL IXUS 400', 7.176;
'Cano... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/visualizeReprojection.m | .m | 1,651 | 42 | function visualizeReprojection(graph, frames)
nfigs = size(graph.ObsIdx,1);
w = ceil(sqrt(nfigs));
h = floor(sqrt(nfigs));
subplot(w,h,1);
for c=1:size(graph.ObsIdx,1)
subplot(w,h,c);
im = imresize(imread(frames.images{c}),frames.imsize(1:2));
imshow(im);
hold on
X = f2K(graph.f) * transformPtsByRt... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/visualizeGraph.m | .m | 286 | 14 | function visualizeGraph(graph,frames)
%figure
plot3(graph.Str(1,:),graph.Str(2,:),graph.Str(3,:),'.r')
axis equal
nCam=length(graph.frames);
for i=1:nCam
drawCamera(graph.Mot(:,:,i), frames.imsize(2), frames.imsize(1), graph.f, 0.001,1); %i*2-1);
end
axis tight
%view(-180,-60);
| MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/estimateE.m | .m | 367 | 9 | function pair = estimateE(pair,frames)
t = .002; % Distance threshold for deciding outliers
[E, inliers] = ransac5point(pair.matches(1:2,:), pair.matches(3:4,:), t, frames.K, 1);
fprintf('%d inliers / %d SIFT matches = %.2f%%\n', length(inliers), size(pair.matches,2), 100*length(inliers)/size(pair.matches,2));
pair... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/estimateF.m | .m | 475 | 9 | function pair = estimateF(pair)
t = .002; % Distance threshold for deciding outliers
[F, inliers] = ransacfitfundmatrix(pair.matches(1:2,:), pair.matches(3:4,:), t, 0);
%t = .02; % Distance threshold for deciding outliers
%[F, inliers] = ransacfitfundmatrix7(SIFTloc_i, SIFTloc_j, t, 1);
fprintf('%d inliers / %d SIFT... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/drawCamera.m | .m | 885 | 26 | function drawCamera(Rt, w, h, f, scale, lineWidth)
% SFMedu: Structrue From Motion for Education Purpose
% Written by Jianxiong Xiao (MIT License)
% Xcamera = Rt * Xworld
V= [...
0 0 0 f -w/2 w/2 w/2 -w/2
0 0 f 0 -h/2 -h/2 h/2 h/2
0 f 0 0 f f f f];
V = V*scale;
V = transformPtsByRt(V, Rt, true);
hold on;... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/full_pipeline.m | .m | 13,567 | 394 | function full_pipeline(data_seq_idx, adjust_focal_length, do_sequential_match, maxSize, visualize, do_dense)
%% run full pipeline with specified parameters
%% data
if data_seq_idx == 0
frames.images{1}='images/B21.jpg';
frames.images{2}='images/B22.jpg';
frames.images{3}='images/B23.jpg';
frames.image... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/showMatches.m | .m | 420 | 14 | function showMatches(pair,frames)
image_i=imresize(imread(frames.images{pair.frames(1)}),frames.imsize(1:2));
image_j=imresize(imread(frames.images{pair.frames(2)}),frames.imsize(1:2));
figure
imshow(image_i);
hold on
plot(size(image_i,2)/2-pair.matches(1,:),size(image_i,1)/2-pair.matches(2,:),'r+');
figure
imshow(im... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtFromE.m | .m | 814 | 36 | function Rtbest=RtFromE(pair,frames)
% Decompose Essential Matrix
[R1, R2, t1, t2] = PoseEMat(pair.E); % MVG Page 257-259
% Four possible solution
Rt(:,:,1) =[R1 t1];
Rt(:,:,2) =[R1 t2];
Rt(:,:,3) =[R2 t1];
Rt(:,:,4) =[R2 t2];
% triangulation
P{1} = frames.K * [eye(3) [0;0;0]];
goodCnt = zeros(1,4);
for i=1:4
... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/SFMedu2.m | .m | 1,509 | 39 | clc;
disp('SFMedu: Structrue From Motion for Education Purpose');
disp('Version 2 @ 2014');
disp('Written by Jianxiong Xiao (MIT License).. Modifications by nick rhinehart');
%% set up things
clear;
close all;
addpath(genpath('matchSIFT'));
addpath(genpath('denseMatch'));
addpath(genpath('RtToolbox'));
%% parameters... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/points2ply.m | .m | 1,439 | 51 | function points2ply(PLYfilename, coordinate, rgb)
% coordinate is 3 * n single matrix for n points
% rgb is 3 * n uint8 matrix for n points range [0, 255]
if size(coordinate,2)==3 && size(coordinate,1)~=3
coordinate = coordinate';
end
isValid = (~isnan(coordinate(1,:))) & (~isn... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/match2viewSURF.m | .m | 2,080 | 61 | function pair = match2viewSURF(frames, frameID_i, frameID_j)
% Tested on Matlab r2014a with Computer Vision System Toolbox
% Similar to image stiching, but instead of homograph, we estimate the fundamental matrix
colorA = imresize(imread(frames.images{frameID_i}),frames.imsize(1:2));
colorB = imresize(imread(frames.... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/reprojectionResidual.m | .m | 1,016 | 46 | function residuals = reprojectionResidual(ObsIdx,ObsVal,px,py,f,Mot,Str)
% (Constant) ObsIdx: index of KxN for N points observed by K cameras, sparse matrix
% (Constant) ObsVal: 2xM for M observations
% px,py: princple points in pixels
% f: focal length in pixels
% Mot: 3x2xK for K cameras
% Str: 3xN for N points
nC... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/removeOutlierPts.m | .m | 2,427 | 78 | function graph=removeOutlierPts(graph,threshold_in_pixels)
if exist('threshold_in_pixels','var')
threshold_in_pixels = threshold_in_pixels^2;
else
threshold_in_pixels = 10^2; % square it so that we don't need to square root everytime
end
threshold_in_degree = 2;
threshold_in_cos = cos(threshold_in_degree / 18... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/reprojectionResidualFull.m | .m | 907 | 40 | function residuals = reprojectionResidualFull(ObsIdx,ObsVal,px,py,fx,fy,Mot,Str)
% (Constant) ObsIdx: index of KxN for N points observed by K cameras, sparse matrix
% (Constant) ObsVal: 2xM for M observations
% px,py: princple points in pixels
% f: focal length in pixels
% Mot: 3x2xK for K cameras
% Str: 3xN for N poi... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/graph2K.m | .m | 106 | 7 | function K = graph2K(graph)
K = eye(3);
K(1,1) = graph.fx;
K(2,2) = graph.fy;
K(1, 3) = px;
K(2, 3) = py; | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/triangulate.m | .m | 653 | 30 | function graph=triangulate(graph,frames)
nPts = size(graph.Str,2);
X = zeros(4,nPts);
for i=1:nPts
validCamera = find(full(graph.ObsIdx(:,i)~=0))';
P=cell (1,length(validCamera));
x=zeros(2,length(validCamera));
cnt = 0;
for c=validCamera
cnt = cnt + 1;
% x (2-by-K matr... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/f2K.m | .m | 56 | 5 | function K = f2K(f)
K = eye(3);
K(1,1) = f;
K(2,2) = f; | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/vgg_X_from_xP_nonlin.m | .m | 1,745 | 82 | %vgg_X_from_xP_nonlin Estimation of 3D point from image matches and camera matrices, nonlinear.
% X = vgg_X_from_xP_lin(x,P,imsize) computes max. likelihood estimate of projective
% 3D point X (column 4-vector) from its projections in K images x (2-by-K matrix)
% and camera matrices P (K-cell of 3-by-4 matrices)... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/pair2graph.m | .m | 355 | 18 | function graph=pair2graph(pair,frames)
graph = pair;
pointCount = size(pair.matches,2);
graph.f = frames.focal_length;
graph.Mot(:,:,1) = [eye(3) [0;0;0]];
graph.Mot(:,:,2) = pair.Rt;
graph.Str = zeros(3,pointCount);
graph.ObsVal = [pair.matches(1:2,:) pair.matches(3:4,:)];
graph.ObsIdx = sparse([1:pointCoun... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/bundleAdjustmentFull.m | .m | 2,517 | 72 | function graph = bundleAdjustmentFull(graph)
% convert from Rt matrix to AngleAxis
nCam=length(graph.frames);
Mot = zeros(3,2,nCam);
for camera=1:nCam
Mot(:,1,camera) = RotationMatrix2AngleAxis(graph.Mot(:,1:3,camera));
Mot(:,2,camera) = graph.Mot(:,4,camera);
end
Str = graph.Str;
f = graph.f;
if ~isfield... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/vgg_X_from_xP_lin.m | .m | 1,095 | 46 | %vgg_X_from_xP_lin Estimation of 3D point from image matches and camera matrices, linear.
% X = vgg_X_from_xP_lin(x,P,imsize) computes projective 3D point X (column 4-vector)
% from its projections in K images x (2-by-K matrix) and camera matrices P (K-cell
% of 3-by-4 matrices). Image sizes imsize (2-by-K matri... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/printReprojectionError.m | .m | 378 | 11 | function printReprojectionError(graph)
Error = 0;
for c=1:size(graph.ObsIdx,1)
X = f2K(graph.f) * transformPtsByRt(graph.Str,graph.Mot(:,:,c));
xy = X(1:2,:) ./ X([3 3],:);
selector = find(graph.ObsIdx(c,:)~=0);
diff = xy(:,selector) - graph.ObsVal(:,graph.ObsIdx(c,selector));
Error = Error + norm(... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/outputPly.m | .m | 964 | 35 | function outputPly(PLYfilename,plyPoint,plyColor)
% SFMedu: Structrue From Motion for Education Purpose
% Written by Jianxiong Xiao (MIT License)
count = size(plyPoint,2);
fprintf('Writing ply point cloud file: ');
file = fopen(PLYfilename,'w');
fprintf (file, 'ply\n');
fprintf (file, 'format binary_little_endian 1... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/unpackMotStrf.m | .m | 301 | 12 | function [Mot,Str,f] = unpackMotStrf(nCam,vec)
if mod(length(vec),3)==0
cut = 3*2*nCam;
Mot = reshape(vec(1:cut),3,2,[]);
Str = reshape(vec(cut+1:end),3,[]);
else
cut = 1+3*2*nCam;
f = vec(1);
Mot = reshape(vec(2:cut),3,2,[]);
Str = reshape(vec(cut+1:end),3,[]);
end | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/ransac5point.m | .m | 3,580 | 131 | function [E, inliers] = ransac5point(x1, x2, t, K, feedback)
% written by Fisher Yu @ 2014
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
if nargin == 4
feedback = 0;
end
[rows,npts] = size(x1);
if rows~=2 && rows~=3
error... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/unpackMotStrFull.m | .m | 211 | 11 | function [Mot,Str,fx,fy,px,py] = unpackMotStrFull(nCam,vec)
cut = 3*2*nCam;
fx = vec(1);
fy = vec(2);
px = vec(3);
py = vec(4);
Mot = reshape(vec(5:(cut + 4)),3,2,[]);
Str = reshape(vec(cut+5:end),3,[]);
end | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/xy.m | .m | 0 | 0 | null | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/vgg_contreps.m | .m | 1,355 | 36 | function Y = vgg_contreps(X)
% vgg_contreps Contraction with epsilon tensor.
%
% B = vgg_contreps(A) is tensor obtained by contraction of A with epsilon tensor.
% However, it works only if the argument and result fit to matrices, in particular:
%
% - if A is row or column 3-vector ... B = [A]_x
% - if A is skew-symm... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/bundleAdjustment.m | .m | 2,584 | 70 | function graph = bundleAdjustment(graph, adjustFocalLength)
% convert from Rt matrix to AngleAxis
nCam=length(graph.frames);
Mot = zeros(3,2,nCam);
for camera=1:nCam
Mot(:,1,camera) = RotationMatrix2AngleAxis(graph.Mot(:,1:3,camera));
Mot(:,2,camera) = graph.Mot(:,4,camera);
end
Str = graph.Str;
f = graph.... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/inverseRt.m | .m | 91 | 4 | function RtOut = inverseRt(RtIn)
RtOut = [RtIn(1:3,1:3)', - RtIn(1:3,1:3)'* RtIn(1:3,4)];
| MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/concatenateRts.m | .m | 165 | 6 | function Rt = concatenateRts(RtOuter, RtInner)
% Rt * X = RtOuter * RtInner * X
Rt = [RtOuter(:,1:3)* RtInner(:,1:3) RtOuter(:,1:3)*RtInner(:,4) + RtOuter(:,4)];
| MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/AngleAxis2RotationMatrix.m | .m | 1,351 | 38 | function R = AngleAxis2RotationMatrix(angle_axis)
theta2 = dot(angle_axis,angle_axis);
if (theta2 > 0.0)
% We want to be careful to only evaluate the square root if the
% norm of the angle_axis vector is greater than zero. Otherwise
% we get a division by zero.
theta = sqrt(theta2);
wx = angle... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/AngleAxisRotatePts.m | .m | 1,457 | 53 | function result = AngleAxisRotatePts(angle_axis, pt)
angle_axis = reshape(angle_axis(1:3),1,3);
theta2 = dot(angle_axis,angle_axis);
if (theta2 > 0.0)
% Away from zero, use the rodriguez formula
%
% result = pt costheta + (w x pt) * sintheta + w (w . pt) (1 - costheta)
%
% We want to be careful... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/transformPtsByRt.m | .m | 209 | 8 | function Y3D = transformPtsByRt(X3D, Rt, isInverse)
if nargin<3 || ~isInverse
Y3D = Rt(:,1:3) * X3D + repmat(Rt(:,4),1,size(X3D,2));
else
Y3D = Rt(:,1:3)' * (X3D - repmat(Rt(:,4),1,size(X3D,2)));
end
| MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/xprodmat.m | .m | 335 | 26 | function A=xprodmat(a)
%Matrix representation of a cross product
%
% A=xprodmat(a)
%
%in:
%
% a: 3D vector
%
%out:
%
% A: a matrix such that A*b=cross(a,b)
if length(a)<3, error 'Input must be a vector of length 3'; end
ax=a(1);
ay=a(2);
az=a(3);
A=zeros(3);
A(2,1)=az; A(1,2)=-az;
A(3,1)=-ay; A(1,3)=ay;
A(3,2)=ax... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/RotationMatrix2AngleAxis.m | .m | 2,817 | 71 | function angle_axis = RotationMatrix2AngleAxis(R)
% The conversion of a rotation matrix to the angle-axis form is
% numerically problematic when then rotation angle is close to zero
% or to Pi. The following implementation detects when these two cases
% occurs and deals with them by taking code paths that are guarante... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/RtToolbox/transformDirByRt.m | .m | 69 | 5 | function DirT = transformDirByRt(Dir,Rt)
DirT = Rt(1:3,1:3) * Dir;
| MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/denseMatch.m | .m | 1,899 | 66 | function pair = denseMatch(pair, frames, frameID_i, frameID_j)
% SFMedu: Structrue From Motion for Education Purpose
% Written by Jianxiong Xiao (MIT License)
im1=imresize(imread(frames.images{frameID_i}),frames.imsize(1:2));
im2=imresize(imread(frames.images{frameID_j}),frames.imsize(1:2));
HalfSizePropagate = 2;
... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/ReliableArea.m | .m | 254 | 8 | function rim = ReliableArea(im)
rim = max( max( abs(im-im([2:end 1],:)) , abs(im-im([end 1:end-1],:)) ), max( abs(im-im(:,[2:end 1])) , abs(im-im(:,[end 1:end-1])) ));
rim([1 end], :) = 0;
rim(:, [1 end]) = 0;
rim = ( rim < 0.01 );
rim = double(1-rim);
| MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/ZNCCpatch_all.m | .m | 684 | 16 | function zncc = ZNCCpatch_all(im, HalfSizeWindow)
zncc = zeros(size(im,1),size(im,2), (2*HalfSizeWindow + 1)^2);
k = 1;
for x=-HalfSizeWindow:HalfSizeWindow
for y=-HalfSizeWindow:HalfSizeWindow
zncc( (HalfSizeWindow + 1):(end-HalfSizeWindow),(HalfSizeWindow + 1):(end-HalfSizeWindow),k) = ...
... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/propagate.m | .m | 4,847 | 115 | function [match_pair match_im_i match_im_j] = propagate(initial_match, im_i, im_j, matchable_im_i, matchable_im_j, zncc_i, zncc_j , WinHalfSize)
%{
Please cite this paper if you use this code.
J. Xiao, J. Chen, D.-Y. Yeung, and L. Quan
Learning Two-view Stereo Matching
Proceedings of the 10th European Conference on C... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/pq_pop.m | .m | 725 | 26 | % PQ_POP removes the topmost element of the priority queue
%
% SYNTAX
% [idx, cost] = pq_pop(pq)
%
% INPUT PARAMETERS
% pq: a pointer to the priority queue
%
% OUTPUT PARAMETERS
% idx: the index of the popped element
% cost: the cost of the popped element
%
% DESCRIPTION
% Removes the topmost element from a prio... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/pq_push.m | .m | 902 | 29 | % PQ_PUSH inserts a new element/update a cost in the priority queue
%
% SYNTAX
% pq_push(pq, idx, cost)
%
% INPUT PARAMETERS
% pq: a pointer to the priority queue
%
% OUTPUT PARAMETERS
% idx: the index of the element
% cost: the cost of the newly inserted element or the
% cost to which the element shoul... | MATLAB |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/pq_pop.cpp | .cpp | 2,033 | 62 | //==============================================================================
// Name : pq_pop.cpp
// Author : Andrea Tagliasacchi
// Version : 1.0
// Copyright : 2009 (c) Andrea Tagliasacchi
// Description : pops an element from the PQ and returns its index and cost
//
// May 22, 2009: Created
//=... | C++ |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/pq_size.cpp | .cpp | 1,845 | 53 | //==============================================================================
// Name : pq_size.cpp
// Author : Andrea Tagliasacchi
// Version : 1.0
// Copyright : 2009 (c) Andrea Tagliasacchi
// Description : Returns the size of the priority queue
//
// May 22, 2009: Created
//====================... | C++ |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/pq_demo.cpp | .cpp | 7,872 | 330 | #include "MyHeap.h"
#include <stdlib.h>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
/// TEST FOR MAXHEAP
int test1(){
MaxHeap<double> pq(7); // heap of ints compared by doubles
pq.push( 1,1 );
pq.push( 6,0 );
pq.push( 2,4 );
pq.push( 3,3 );
pq.push( 4,2 );
pq.push( 5,5 );
//... | C++ |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/MyHeap_old.h | .h | 13,341 | 474 | /**
* @file MyHeaps.h
* @author Andrea Tagliasacchi
* @data 26 March 2008
* @copyright (c) Andrea Tagliasacchi - All rights reserved
*/
#ifndef MYHEAPS_H_
#define MYHEAPS_H_
#include <vector>
#include <exception> // general exception
#include <stdexcept> // out_of_range
#include <iostream>
#include <cassert>
#in... | Unknown |
3D | stillbreeze/3D-reconstruction-Using-SfM-and-Stereo-Matching | code/SFMedu/denseMatch/priority_queue_1.0_old/pq_push.cpp | .cpp | 2,968 | 91 | //==============================================================================
// Name : pq_push.cpp
// Author : Andrea Tagliasacchi
// Version : 1.0
// Copyright : 2009 (c) Andrea Tagliasacchi
// Description : inserts a new element in the priority queue
//
// May 22, 2009: Created
//===============... | C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.