plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
jianxiongxiao/ProfXkit-master
vl_test_imarray.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_imarray.m
795
utf_8
c5e6a5aa8c2e63e248814f5bd89832a8
function results = vl_test_imarray(varargin) % VL_TEST_IMARRAY vl_test_init ; function test_movie_rgb(s) A = rand(23,15,3,4) ; B = vl_imarray(A,'movie',true) ; function test_movie_indexed(s) cmap = get(0,'DefaultFigureColormap') ; A = uint8(size(cmap,1)*rand(23,15,4)) ; A = min(A,size(cmap,1)-1) ; B = vl_imarray(A,'movie',true) ; function test_movie_gray_indexed(s) A = uint8(255*rand(23,15,4)) ; B = vl_imarray(A,'movie',true,'cmap',gray(256)) ; for k=1:size(A,3) vl_assert_equal(squeeze(A(:,:,k)), ... frame2im(B(k))) ; end function test_basic(s) M = 3 ; N = 4 ; width = 32 ; height = 15 ; for i=1:M for j=1:N A{i,j} = rand(width,height) ; end end A1 = A'; A1 = cat(3,A1{:}) ; A2 = cell2mat(A) ; B = vl_imarray(A1, 'layout', [M N]) ; vl_assert_equal(A2,B) ;
github
jianxiongxiao/ProfXkit-master
vl_test_homkermap.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_homkermap.m
1,903
utf_8
c157052bf4213793a961bde1f73fb307
function results = vl_test_homkermap(varargin) % VL_TEST_HOMKERMAP vl_test_init ; function check_ker(ker, n, window, period) args = {n, ker, 'window', window} ; if nargin > 3 args = {args{:}, 'period', period} ; end x = [-1 -.5 0 .5 1] ; y = linspace(0,2,100) ; for conv = {@single, @double} x = feval(conv{1}, x) ; y = feval(conv{1}, y) ; sx = sign(x) ; sy = sign(y) ; psix = vl_homkermap(x, args{:}) ; psiy = vl_homkermap(y, args{:}) ; k = vl_alldist(psix,psiy,'kl2') ; k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ; vl_assert_almost_equal(k, k_, 2e-2) ; end function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ; function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ; function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ; function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ; function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ; function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ; function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ; function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ; function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ; function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ; function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ; function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ; function test_gamma() x = linspace(0,1,20) ; for gamma = linspace(.2,2,10) k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ; psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ; assert(norm(k - psix'*psix) < 1e-2) ; end function test_negative() x = linspace(-1,1,20) ; k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ; psix = vl_homkermap(x, 3, 'kchi2') ; assert(norm(k - psix'*psix) < 1e-2) ;
github
jianxiongxiao/ProfXkit-master
vl_test_slic.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_slic.m
200
utf_8
12a6465e3ef5b4bcfd7303cd8a9229d4
function results = vl_test_slic(varargin) % VL_TEST_SLIC vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; function test_slic(s) segmentation = vl_slic(s.im, 10, 0.1) ;
github
jianxiongxiao/ProfXkit-master
vl_test_ikmeans.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_ikmeans.m
466
utf_8
1ee2f647ac0035ed0d704a0cd615b040
function results = vl_test_ikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [centers, assign] = vl_ikmeans(s.data,100) ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ;
github
jianxiongxiao/ProfXkit-master
vl_test_mser.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_mser.m
242
utf_8
1ad33563b0c86542a2978ee94e0f4a39
function results = vl_test_mser(varargin) % VL_TEST_MSER vl_test_init ; function s = setup() s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ; function test_mser(s) [regions,frames] = vl_mser(s.im) ; mask = vl_erfill(s.im, regions(1)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_inthist.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_inthist.m
811
utf_8
459027d0c54d8f197563a02ab66ef45d
function results = vl_test_inthist(varargin) % VL_TEST_INTHIST vl_test_init ; function s = setup() rand('state',0) ; s.labels = uint32(8*rand(123, 76, 3)) ; function test_basic(s) l = 10 ; hist = vl_inthist(s.labels, 'numlabels', l) ; hist_ = inthist_slow(s.labels, l) ; vl_assert_equal(double(hist),hist_) ; function test_sample(s) rand('state',0) ; boxes = 10 * rand(4,20) + .5 ; boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ; boxes = min(boxes, 10) ; boxes = uint32(boxes) ; inthist = vl_inthist(s.labels) ; hist = vl_sampleinthist(inthist, boxes) ; function hist = inthist_slow(labels, numLabels) m = size(labels,1) ; n = size(labels,2) ; l = numLabels ; b = zeros(m*n,l) ; b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ; b = reshape(b,m,n,l) ; for k=1:l hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ; end
github
jianxiongxiao/ProfXkit-master
vl_test_imdisttf.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_imdisttf.m
1,885
utf_8
ae921197988abeb984cbcdf9eaf80e77
function results = vl_test_imdisttf(varargin) % VL_TEST_DISTTF vl_test_init ; function test_basic() for conv = {@single, @double} conv = conv{1} ; I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ; D = vl_imdisttf(I); assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ; I(2,2) = -3 ; [D,map] = vl_imdisttf(I) ; assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ; assert(isequal(map, 5 * ones(3))) ; end function test_1x1() assert(isequal(1, vl_imdisttf(1))) ; function test_rand() I = rand(13,31) ; for t=1:4 param = [rand randn rand randn] ; [D0,map0] = imdisttf_equiv(I,param) ; [D,map] = vl_imdisttf(I,param) ; vl_assert_almost_equal(D,D0,1e-10) assert(isequal(map,map0)) ; end function test_param() I = zeros(3,4) ; I(1,1) = -1 ; [D,map] = vl_imdisttf(I,[1 0 1 0]); assert(isequal(-[1 0 0 0 ; 0 0 0 0 ; 0 0 0 0 ;], D)) ; D0 = -[1 .9 .6 .1 ; 0 0 0 0 ; 0 0 0 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[1 .9 .6 .1 ; .9 .8 .5 0 ; .6 .5 .2 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 .1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[.9 1 .9 .6 ; .8 .9 .8 .5 ; .5 .6 .5 .2 ; ] ; [D,map] = vl_imdisttf(I,[.1 1 .1 0]); vl_assert_almost_equal(D,D0,1e-10); function test_special() I = rand(13,31) -.5 ; D = vl_imdisttf(I, [0 0 1e5 0]) ; vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10); D = vl_imdisttf(I, [1e5 0 0 0]) ; vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10); function [D,map]=imdisttf_equiv(I,param) D = inf + zeros(size(I)) ; map = zeros(size(I)) ; ur = 1:size(D,2) ; vr = 1:size(D,1) ; [u,v] = meshgrid(ur,vr) ; for v_=vr for u_=ur E = I(v_,u_) + ... param(1) * (u - u_ - param(2)).^2 + ... param(3) * (v - v_ - param(4)).^2 ; map(E < D) = sub2ind(size(I),v_,u_) ; D = min(D,E) ; end end
github
jianxiongxiao/ProfXkit-master
vl_test_vlad.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_vlad.m
1,977
utf_8
d3797288d6edb1d445b890db3780c8ce
function results = vl_test_vlad(varargin) % VL_TEST_VLAD vl_test_init ; function s = setup() randn('state',0) ; s.x = randn(128,256) ; s.mu = randn(128,16) ; assignments = rand(16, 256) ; s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ; function test_basic (s) x = [1, 2, 3] ; mu = [0, 0, 0] ; assignments = eye(3) ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 2 3]') ; mu = [0, 1, 2] ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 1 1]') ; phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ; vl_assert_equal(phi, [2 2 2]') ; function test_rand (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ; vl_assert_equal(phi, phi_) ; function test_norm (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments) ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_sqrt (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_individual (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_mass (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function enc = simple_vlad(x, mu, assign) for i = 1:size(assign,1) enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ; end enc = cat(1, enc{:}) ;
github
jianxiongxiao/ProfXkit-master
vl_test_pr.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_pr.m
3,763
utf_8
4d1da5ccda1a7df2bec35b8f12fdd620
function results = vl_test_pr(varargin) % VL_TEST_PR vl_test_init ; function s = setup() s.scores0 = [5 4 3 2 1] ; s.scores1 = [5 3 4 2 1] ; s.labels = [1 1 -1 -1 -1] ; function test_perfect_tptn(s) [rc,pr] = vl_pr(s.labels,s.scores0) ; vl_assert_almost_equal(pr, [1 1/1 2/2 2/3 2/4 2/5]) ; vl_assert_almost_equal(rc, [0 1 2 2 2 2] / 2) ; function test_perfect_metrics(s) [rc,pr,info] = vl_pr(s.labels,s.scores0) ; vl_assert_almost_equal(info.auc, 1) ; vl_assert_almost_equal(info.ap, 1) ; vl_assert_almost_equal(info.ap_interp_11, 1) ; function test_swap1_tptn(s) [rc,pr] = vl_pr(s.labels,s.scores1) ; vl_assert_almost_equal(pr, [1 1/1 1/2 2/3 2/4 2/5]) ; vl_assert_almost_equal(rc, [0 1 1 2 2 2] / 2) ; function test_swap1_tptn_stable(s) [rc,pr] = vl_pr(s.labels,s.scores1,'stable',true) ; vl_assert_almost_equal(pr, [1/1 2/3 1/2 2/4 2/5]) ; vl_assert_almost_equal(rc, [1 2 1 2 2] / 2) ; function test_swap1_metrics(s) [rc,pr,info] = vl_pr(s.labels,s.scores1) ; clf; vl_pr(s.labels,s.scores1) ; vl_assert_almost_equal(info.auc, [.5 + .5 * (.5 + 2/3)/2]) ; vl_assert_almost_equal(info.ap, [1/1 + 2/3]/2) ; vl_assert_almost_equal(info.ap_interp_11, mean([1 1 1 1 1 1 2/3 2/3 2/3 2/3 2/3])) ; function test_inf(s) scores = [1 -inf -1 -1 -1 -1] ; labels = [1 1 -1 -1 -1 -1] ; [rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true) ; [rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false) ; vl_assert_equal(numel(rc1), numel(rc2) + 1) ; vl_assert_almost_equal(info1.auc, [1 * .5 + (1/5 + 2/6)/2 * .5]) ; vl_assert_almost_equal(info1.ap, [1 * .5 + 2/6 * .5]) ; vl_assert_almost_equal(info1.ap_interp_11, [1 * 6/11 + 2/6 * 5/11]) ; vl_assert_almost_equal(info2.auc, 0.5) ; vl_assert_almost_equal(info2.ap, 0.5) ; vl_assert_almost_equal(info2.ap_interp_11, 1 * 6 / 11) ; function test_inf_stable(s) scores = [-1 -1 -1 -1 -inf +1] ; labels = [-1 -1 -1 -1 +1 +1] ; [rc1,pr1,info1] = vl_pr(labels, scores, 'includeInf', true, 'stable', true) ; [rc2,pr2,info2] = vl_pr(labels, scores, 'includeInf', false, 'stable', true) ; [rc1_,pr1_,info1_] = vl_pr(labels, scores, 'includeInf', true, 'stable', false) ; [rc2_,pr2_,info2_] = vl_pr(labels, scores, 'includeInf', false, 'stable', false) ; % stability does not change scores vl_assert_almost_equal(info1,info1_) ; vl_assert_almost_equal(info2,info2_) ; % unstable with inf (first point (0,1) is conventional) vl_assert_almost_equal(rc1_, [0 .5 .5 .5 .5 .5 1]) vl_assert_almost_equal(pr1_, [1 1 1/2 1/3 1/4 1/5 2/6]) % unstable without inf vl_assert_almost_equal(rc2_, [0 .5 .5 .5 .5 .5]) vl_assert_almost_equal(pr2_, [1 1 1/2 1/3 1/4 1/5]) % stable with inf (no conventional point here) vl_assert_almost_equal(rc1, [.5 .5 .5 .5 1 .5]) ; vl_assert_almost_equal(pr1, [1/2 1/3 1/4 1/5 2/6 1]) ; % stable without inf (no conventional point and -inf are NaN) vl_assert_almost_equal(rc2, [.5 .5 .5 .5 NaN .5]) ; vl_assert_almost_equal(pr2, [1/2 1/3 1/4 1/5 NaN 1]) ; function test_normalised_pr(s) scores = [+1 +2] ; labels = [+1 -1] ; [rc1,pr1,info1] = vl_pr(labels,scores) ; [rc2,pr2,info2] = vl_pr(labels,scores,'normalizePrior',.5) ; vl_assert_almost_equal(pr1, pr2) ; vl_assert_almost_equal(rc1, rc2) ; scores_ = [+1 +2 +2 +2] ; labels_ = [+1 -1 -1 -1] ; [rc3,pr3,info3] = vl_pr(labels_,scores_) ; [rc4,pr4,info4] = vl_pr(labels,scores,'normalizePrior',1/4) ; vl_assert_almost_equal(info3, info4) ; function test_normalised_pr_corner_cases(s) scores = 1:10 ; labels = ones(1,10) ; [rc1,pr1,info1] = vl_pr(labels,scores) ; vl_assert_almost_equal(rc1, (0:10)/10) ; vl_assert_almost_equal(pr1, ones(1,11)) ; scores = 1:10 ; labels = zeros(1,10) ; [rc2,pr2,info2] = vl_pr(labels,scores) ; vl_assert_almost_equal(rc2, zeros(1,11)) ; vl_assert_almost_equal(pr2, ones(1,11)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_hog.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_hog.m
1,555
utf_8
eed7b2a116d142040587dc9c4eb7cd2e
function results = vl_test_hog(varargin) % VL_TEST_HOG vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; [x,y]= meshgrid(linspace(-1,1,128)) ; s.round = single(x.^2+y.^2); s.imSmall = s.im(1:128,1:128,:) ; s.imSmall = s.im ; s.imSmallFlipped = s.imSmall(:,end:-1:1,:) ; function test_basic_call(s) cellSize = 8 ; hog = vl_hog(s.im, cellSize) ; function test_bilinear_orientations(s) cellSize = 8 ; vl_hog(s.im, cellSize, 'bilinearOrientations') ; function test_variants_and_flipping(s) variants = {'uoctti', 'dalaltriggs'} ; numOrientationsRange = 3:9 ; cellSize = 8 ; for cellSize = [4 8 16] for i=1:numel(variants) for j=1:numel(numOrientationsRange) args = {'bilinearOrientations', ... 'variant', variants{i}, ... 'numOrientations', numOrientationsRange(j)} ; hog = vl_hog(s.imSmall, cellSize, args{:}) ; perm = vl_hog('permutation', args{:}) ; hog1 = vl_hog(s.imSmallFlipped, cellSize, args{:}) ; hog2 = hog(:,end:-1:1,perm) ; %norm(hog1(:)-hog2(:)) vl_assert_almost_equal(hog1,hog2,1e-3) ; end end end function test_polar(s) cellSize = 8 ; im = s.round ; for b = [0 1] if b args = {'bilinearOrientations'} ; else args = {} ; end hog1 = vl_hog(im, cellSize, args{:}) ; [ix,iy] = vl_grad(im) ; m = sqrt(ix.^2 + iy.^2) ; a = atan2(iy,ix) ; m(:,[1 end]) = 0 ; m([1 end],:) = 0 ; hog2 = vl_hog(cat(3,m,a), cellSize, 'DirectedPolarField', args{:}) ; vl_assert_almost_equal(hog1,hog2,norm(hog1(:))/1000) ; end
github
jianxiongxiao/ProfXkit-master
vl_test_argparse.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_argparse.m
795
utf_8
e72185b27206d0ee1dfdc19fe77a5be6
function results = vl_test_argparse(varargin) % VL_TEST_ARGPARSE vl_test_init ; function test_basic() opts.field1 = 1 ; opts.field2 = 2 ; opts.field3 = 3 ; opts_ = opts ; opts_.field1 = 3 ; opts_.field2 = 10 ; opts = vl_argparse(opts, {'field2', 10, 'field1', 3}) ; assert(isequal(opts, opts_)) ; opts_.field1 = 9 ; opts = vl_argparse(opts, {'field1', 4, 'field1', 9}) ; assert(isequal(opts, opts_)) ; function test_error() opts.field1 = 1 ; try opts = vl_argparse(opts, {'field2', 5}) ; catch e return ; end assert(false) ; function test_leftovers() opts1.field1 = 1 ; opts2.field2 = 1 ; opts1_.field1 = 2 ; opts2_.field2 = 2 ; [opts1,args] = vl_argparse(opts1, {'field1', 2, 'field2', 2}) ; opts2 = vl_argparse(opts2, args) ; assert(isequal(opts1,opts1_), isequal(opts2,opts2_)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_liop.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_liop.m
1,023
utf_8
a162be369073bed18e61210f44088cf3
function results = vl_test_liop(varargin) % VL_TEST_SIFT vl_test_init ; function s = setup() randn('state',0) ; s.patch = randn(65,'single') ; xr = -32:32 ; [x,y] = meshgrid(xr) ; s.blob = - single(x.^2+y.^2) ; function test_basic(s) d = vl_liop(s.patch) ; function test_blob(s) % with a blob, all local intensity order pattern are equal. In % particular, if the blob intensity decreases away from the center, % then all local intensities sampled in a neighbourhood of 2 elements % are already sorted (see LIOP details). d = vl_liop(s.blob, ... 'IntensityThreshold', 0, ... 'NumNeighbours', 2, ... 'NumSpatialBins', 1) ; assert(isequal(d, single([1;0]))) ; function test_neighbours(s) for n=2:5 for p=1:3 d = vl_liop(s.patch, 'NumNeighbours', n, 'NumSpatialBins', p) ; assert(numel(d) == p * factorial(n)) ; end end function test_multiple(s) x = randn(31,31,3, 'single') ; d = vl_liop(x) ; for i=1:3 d_(:,i) = vl_liop(squeeze(x(:,:,i))) ; end assert(isequal(d,d_)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_binsearch.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_binsearch.m
1,339
utf_8
85dc020adce3f228fe7dfb24cf3acc63
function results = vl_test_binsearch(varargin) % VL_TEST_BINSEARCH vl_test_init ; function test_inf_bins() x = [-inf -1 0 1 +inf] ; vl_assert_equal(vl_binsearch([], x), [0 0 0 0 0]) ; vl_assert_equal(vl_binsearch([-inf 0], x), [1 1 2 2 2]) ; vl_assert_equal(vl_binsearch([-inf], x), [1 1 1 1 1]) ; vl_assert_equal(vl_binsearch([-inf +inf], x), [1 1 1 1 2]) ; function test_empty() vl_assert_equal(vl_binsearch([], []), []) ; function test_bnd() vl_assert_equal(vl_binsearch([], [1]), [0]) ; vl_assert_equal(vl_binsearch([], [-inf]), [0]) ; vl_assert_equal(vl_binsearch([], [+inf]), [0]) ; vl_assert_equal(vl_binsearch([1], [.9]), [0]) ; vl_assert_equal(vl_binsearch([1], [1]), [1]) ; vl_assert_equal(vl_binsearch([1], [-inf]), [0]) ; vl_assert_equal(vl_binsearch([1], [+inf]), [1]) ; function test_basic() vl_assert_equal(vl_binsearch(-10:10, -10:10), 1:21) ; vl_assert_equal(vl_binsearch(-10:10, -11:10), 0:21) ; vl_assert_equal(vl_binsearch(-10:10, [-inf, -11:10, +inf]), [0 0:21 21]) ; function test_frac() vl_assert_equal(vl_binsearch(1:10, 1:.5:10), floor(1:.5:10)) vl_assert_equal(vl_binsearch(1:10, fliplr(1:.5:10)), ... fliplr(floor(1:.5:10))) ; function test_array() a = reshape(1:100,10,10) ; b = reshape(1:.5:100.5, 2, []) ; c = floor(b) ; vl_assert_equal(vl_binsearch(a,b), c) ;
github
jianxiongxiao/ProfXkit-master
vl_roc.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/plotop/vl_roc.m
8,747
utf_8
6b8b4786c9242d5112ca90a616db507a
function [tpr,tnr,info] = vl_roc(labels, scores, varargin) %VL_ROC ROC curve. % [TPR,TNR] = VL_ROC(LABELS, SCORES) computes the Receiver Operating % Characteristic (ROC) curve. LABELS are the ground truth labels, % greather than zero for a positive sample and smaller than zero for % a negative one. SCORES are the scores of the samples obtained from % a classifier, where lager scores should correspond to positive % labels. % % Samples are ranked by decreasing scores, starting from rank 1. % TPR(K) and TNR(K) are the true positive and true negative rates % when samples of rank smaller or equal to K-1 are predicted to be % positive. So for example TPR(3) is the true positive rate when the % two samples with largest score are predicted to be % positive. Similarly, TPR(1) is the true positive rate when no % samples are predicted to be positive, i.e. the constant 0. % % Set the zero the lables of samples that should be ignored in the % evaluation. Set to -INF the scores of samples which are not % retrieved. If there are samples with -INF score, then the ROC curve % may have maximum TPR and TNR smaller than 1. % % [TPR,TNR,INFO] = VL_ROC(...) returns an additional structure INFO % with the following fields: % % info.auc:: Area under the ROC curve (AUC). % The ROC curve has a `staircase shape' because for each sample % only TP or TN changes, but not both at the same time. Therefore % there is no approximation involved in the computation of the % area. % % info.eer:: Equal error rate (EER). % The equal error rate is the value of FPR (or FNR) when the ROC % curves intersects the line connecting (0,0) to (1,1). % % VL_ROC(...) with no output arguments plots the ROC curve in the % current axis. % % VL_ROC() acccepts the following options: % % Plot:: [] % Setting this option turns on plotting unconditionally. The % following plot variants are supported: % % tntp:: Plot TPR against TNR (standard ROC plot). % tptn:: Plot TNR against TPR (recall on the horizontal axis). % fptp:: Plot TPR against FPR. % fpfn:: Plot FNR against FPR (similar to DET curve). % % NumPositives:: [] % NumNegatives:: [] % If set to a number, pretend that LABELS contains this may % positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be % smaller than the actual number of positive/negative entrires in % LABELS. The additional positive/negative labels are appended to % the end of the sequence, as if they had -INF scores (not % retrieved). This is useful to evaluate large retrieval systems in % which one stores ony a handful of top results for efficiency % reasons. % % About the ROC curve:: % Consider a classifier that predicts as positive all samples whose % score is not smaller than a threshold S. The ROC curve represents % the performance of such classifier as the threshold S is % changed. Formally, define % % P = overall num. of positive samples, % N = overall num. of negative samples, % % and for each threshold S % % TP(S) = num. of samples that are correctly classified as positive, % TN(S) = num. of samples that are correctly classified as negative, % FP(S) = num. of samples that are incorrectly classified as positive, % FN(S) = num. of samples that are incorrectly classified as negative. % % Consider also the rates: % % TPR = TP(S) / P, FNR = FN(S) / P, % TNR = TN(S) / N, FPR = FP(S) / N, % % and notice that by definition % % P = TP(S) + FN(S) , N = TN(S) + FP(S), % 1 = TPR(S) + FNR(S), 1 = TNR(S) + FPR(S). % % The ROC curve is the parametric curve (TPR(S), TNR(S)) obtained % as the classifier threshold S is varied in the reals. The TPR is % also known as recall (see VL_PR()). % % The ROC curve is contained in the square with vertices (0,0) The % (average) ROC curve of a random classifier is a line which % connects (1,0) and (0,1). % % The ROC curve is independent of the prior probability of the % labels (i.e. of P/(P+N) and N/(P+N)). % % REFERENCES: % [1] http://en.wikipedia.org/wiki/Receiver_operating_characteristic % % See also: VL_PR(), VL_DET(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). [tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ; opts.plot = [] ; opts.stable = false ; opts = vl_argparse(opts,varargin) ; % compute the rates small = 1e-10 ; tpr = tp / max(p, small) ; fpr = fp / max(n, small) ; fnr = 1 - tpr ; tnr = 1 - fpr ; % -------------------------------------------------------------------- % Additional info % -------------------------------------------------------------------- if nargout > 2 || nargout == 0 % Area under the curve. Since the curve is a staircase (in the % sense that for each sample either tn is decremented by one % or tp is incremented by one but the other remains fixed), % the integral is particularly simple and exact. info.auc = sum(tnr .* diff([0 tpr])) ; % Equal error rate. One must find the index S for which there is a % crossing between TNR(S) and TPR(s). If such a crossing exists, % there are two cases: % % o tnr o % / \ % 1-eer = tnr o-x-o 1-eer = tpr o-x-o % / \ % tpr o o % % Moreover, if the maximum TPR is smaller than 1, then it is % possible that neither of the two cases realizes (then EER=NaN). s = max(find(tnr > tpr)) ; if s == length(tpr) info.eer = NaN ; else if tpr(s) == tpr(s+1) info.eer = 1 - tpr(s) ; else info.eer = 1 - tnr(s) ; end end end % -------------------------------------------------------------------- % Plot % -------------------------------------------------------------------- if ~isempty(opts.plot) || nargout == 0 if isempty(opts.plot), opts.plot = 'fptp' ; end cla ; hold on ; switch lower(opts.plot) case {'truenegatives', 'tn', 'tntp'} hroc = plot(tnr, tpr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('true negative rate') ; ylabel('true positive rate (recall)') ; loc = 'sw' ; case {'falsepositives', 'fp', 'fptp'} hroc = plot(fpr, tpr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [0 1], 'r--', 'linewidth', 2) ; spline([1 0], [0 1], 'k--', 'linewidth', 1) ; plot(info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('false positive rate') ; ylabel('true positive rate (recall)') ; loc = 'se' ; case {'tptn'} hroc = plot(tpr, tnr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(1-info.eer, 1-info.eer, 'k*', 'linewidth', 1) ; xlabel('true positive rate (recall)') ; ylabel('false positive rate') ; loc = 'sw' ; case {'fpfn'} hroc = plot(fpr, fnr, 'b', 'linewidth', 2) ; hrand = spline([0 1], [1 0], 'r--', 'linewidth', 2) ; spline([0 1], [0 1], 'k--', 'linewidth', 1) ; plot(info.eer, info.eer, 'k*', 'linewidth', 1) ; xlabel('false positive (false alarm) rate') ; ylabel('false negative (miss) rate') ; loc = 'ne' ; otherwise error('''%s'' is not a valid PLOT type.', opts.plot); end grid on ; xlim([0 1]) ; ylim([0 1]) ; axis square ; title(sprintf('ROC (AUC: %.2f%%, EER: %.2f%%)', info.auc * 100, info.eer * 100), ... 'interpreter', 'none') ; legend([hroc hrand], 'ROC', 'ROC rand.', 'location', loc) ; end % -------------------------------------------------------------------- % Stable output % -------------------------------------------------------------------- if opts.stable tpr(1) = [] ; tnr(1) = [] ; tpr_ = tpr ; tnr_ = tnr ; tpr = NaN(size(tpr)) ; tnr = NaN(size(tnr)) ; tpr(perm) = tpr_ ; tnr(perm) = tnr_ ; end % -------------------------------------------------------------------- function h = spline(x,y,spec,varargin) % -------------------------------------------------------------------- prop = vl_linespec2prop(spec) ; h = line(x,y,prop{:},varargin{:}) ;
github
jianxiongxiao/ProfXkit-master
vl_click.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/plotop/vl_click.m
2,661
utf_8
6982e869cf80da57fdf68f5ebcd05a86
function P = vl_click(N,varargin) ; % VL_CLICK Click a point % P=VL_CLICK() let the user click a point in the current figure and % returns its coordinates in P. P is a two dimensiona vectors where % P(1) is the point X-coordinate and P(2) the point Y-coordinate. The % user can abort the operation by pressing any key, in which case the % empty matrix is returned. % % P=VL_CLICK(N) lets the user select N points in a row. The user can % stop inserting points by pressing any key, in which case the % partial list is returned. % % VL_CLICK() accepts the following options: % % PlotMarker:: [0] % Plot a marker as points are selected. The markers are deleted on % exiting the function. % % See also: VL_CLICKPOINT(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). plot_marker = 0 ; for k=1:2:length(varargin) switch lower(varargin{k}) case 'plotmarker' plot_marker = varargin{k+1} ; otherwise error(['Uknown option ''', varargin{k}, '''.']) ; end end if nargin < 1 N=1; end % -------------------------------------------------------------------- % Do job % -------------------------------------------------------------------- fig = gcf ; is_hold = ishold ; hold on ; bhandler = get(fig,'WindowButtonDownFcn') ; khandler = get(fig,'KeyPressFcn') ; pointer = get(fig,'Pointer') ; set(fig,'WindowButtonDownFcn',@click_handler) ; set(fig,'KeyPressFcn',@key_handler) ; set(fig,'Pointer','crosshair') ; P=[] ; h=[] ; data.exit=0; guidata(fig,data) ; while size(P,2) < N uiwait(fig) ; data = guidata(fig) ; if(data.exit) break ; end P = [P data.P] ; if( plot_marker ) h=[h plot(data.P(1),data.P(2),'rx')] ; end end if ~is_hold hold off ; end if( plot_marker ) pause(.1); delete(h) ; end set(fig,'WindowButtonDownFcn',bhandler) ; set(fig,'KeyPressFcn',khandler) ; set(fig,'Pointer',pointer) ; % ==================================================================== function click_handler(obj,event) % -------------------------------------------------------------------- data = guidata(gcbo) ; P = get(gca, 'CurrentPoint') ; P = [P(1,1); P(1,2)] ; data.P = P ; guidata(obj,data) ; uiresume(gcbo) ; % ==================================================================== function key_handler(obj,event) % -------------------------------------------------------------------- data = guidata(gcbo) ; data.exit = 1 ; guidata(obj,data) ; uiresume(gcbo) ;
github
jianxiongxiao/ProfXkit-master
vl_pr.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/plotop/vl_pr.m
9,135
utf_8
c5d1b9d67f843d10c0b2c6b48fab3c53
function [recall, precision, info] = vl_pr(labels, scores, varargin) %VL_PR Precision-recall curve. % [RECALL, PRECISION] = VL_PR(LABELS, SCORES) computes the % precision-recall (PR) curve. LABELS are the ground truth labels, % greather than zero for a positive sample and smaller than zero for % a negative one. SCORES are the scores of the samples obtained from % a classifier, where lager scores should correspond to positive % samples. % % Samples are ranked by decreasing scores, starting from rank 1. % PRECISION(K) and RECALL(K) are the precison and recall when % samples of rank smaller or equal to K-1 are predicted to be % positive and the remaining to be negative. So for example % PRECISION(3) is the percentage of positive samples among the two % samples with largest score. PRECISION(1) is the precision when no % samples are predicted to be positive and is conventionally set to % the value 1. % % Set to zero the lables of samples that should be ignored in the % evaluation. Set to -INF the scores of samples which are not % retrieved. If there are samples with -INF score, then the PR curve % may have maximum recall smaller than 1, unless the INCLUDEINF % option is used (see below). The options NUMNEGATIVES and % NUMPOSITIVES can be used to add additional surrogate samples with % -INF score (see below). % % [RECALL, PRECISION, INFO] = VL_PR(...) returns an additional % structure INFO with the following fields: % % info.auc:: % The area under the precision-recall curve. If the INTERPOLATE % option is set to FALSE, then trapezoidal interpolation is used % to integrate the PR curve. If the INTERPOLATE option is set to % TRUE, then the curve is piecewise constant and no other % approximation is introduced in the calculation of the area. In % the latter case, INFO.AUC is the same as INFO.AP. % % info.ap:: % Average precision as defined by TREC. This is the average of the % precision observed each time a new positive sample is % recalled. In this calculation, any sample with -INF score % (unless INCLUDEINF is used) and any additional positive induced % by NUMPOSITIVES has precision equal to zero. If the INTERPOLATE % option is set to true, the AP is computed from the interpolated % precision and the result is the same as INFO.AUC. Note that AP % as defined by TREC normally does not use interpolation [1]. % % info.ap_interp_11:: % 11-points interpolated average precision as defined by TREC. % This is the average of the maximum precision for recall levels % greather than 0.0, 0.1, 0.2, ..., 1.0. This measure was used in % the PASCAL VOC challenge up to the 2008 edition. % % info.auc_pa08:: % Deprecated. It is the same of INFO.AP_INTERP_11. % % VL_PR(...) with no output arguments plots the PR curve in the % current axis. % % VL_PR() accepts the following options: % % Interpolate:: false % If set to true, use interpolated precision. The interpolated % precision is defined as the maximum precision for a given recall % level and onwards. Here it is implemented as the culumative % maximum from low to high scores of the precision. % % NumPositives:: [] % NumNegatives:: [] % If set to a number, pretend that LABELS contains this may % positive/negative labels. NUMPOSITIVES/NUMNEGATIVES cannot be % smaller than the actual number of positive/negative entrires in % LABELS. The additional positive/negative labels are appended to % the end of the sequence, as if they had -INF scores (not % retrieved). This is useful to evaluate large retrieval systems % for which one stores ony a handful of top results for efficiency % reasons. % % IncludeInf:: false % If set to true, data with -INF score SCORES is included in the % evaluation and the maximum recall is 1 even if -INF scores are % present. This option does not include any additional positive or % negative data introduced by specifying NUMPOSITIVES and % NUMNEGATIVES. % % Stable:: false % If set to true, RECALL and PRECISION are returned the same order % of LABELS and SCORES rather than being sorted by decreasing % score (increasing recall). Samples with -INF scores are assigned % RECALL and PRECISION equal to NaN. % % NormalizePrior:: [] % If set to a scalar, reweights positive and negative labels so % that the fraction of positive ones is equal to the specified % value. This computes the normalised PR curves of [2] % % About the PR curve:: % This section uses the same symbols used in the documentation of % the VL_ROC() function. In addition to those quantities, define: % % PRECISION(S) = TP(S) / (TP(S) + FP(S)) % RECALL(S) = TPR(S) = TP(S) / P % % The precision is the fraction of positivie predictions which are % correct, and the recall is the fraction of positive labels that % have been correctly classified (recalled). Notice that the recall % is also equal to the true positive rate for the ROC curve (see % VL_ROC()). % % REFERENCES: % [1] C. D. Manning, P. Raghavan, and H. Schutze. An Introduction to % Information Retrieval. Cambridge University Press, 2008. % [2] D. Hoiem, Y. Chodpathumwan, and Q. Dai. Diagnosing error in % object detectors. In Proc. ECCV, 2012. % % See also VL_ROC(), VL_HELP(). % Author: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). % TP and FP are the vectors of true positie and false positve label % counts for decreasing scores, P and N are the total number of % positive and negative labels. Note that if certain options are used % some labels may actually not be stored explicitly by LABELS, so P+N % can be larger than the number of element of LABELS. [tp, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ; opts.stable = false ; opts.interpolate = false ; opts.normalizePrior = [] ; opts = vl_argparse(opts,varargin) ; % compute precision and recall small = 1e-10 ; recall = tp / max(p, small) ; if isempty(opts.normalizePrior) precision = max(tp, small) ./ max(tp + fp, small) ; else a = opts.normalizePrior ; precision = max(tp * a/max(p,small), small) ./ ... max(tp * a/max(p,small) + fp * (1-a)/max(n,small), small) ; end % interpolate precision if needed if opts.interpolate precision = fliplr(vl_cummax(fliplr(precision))) ; end % -------------------------------------------------------------------- % Additional info % -------------------------------------------------------------------- if nargout > 2 || nargout == 0 % area under the curve using trapezoid interpolation if ~opts.interpolate info.auc = 0.5 * sum((precision(1:end-1) + precision(2:end)) .* diff(recall)) ; end % average precision (for each recalled positive sample) sel = find(diff(recall)) + 1 ; info.ap = sum(precision(sel)) / p ; if opts.interpolate info.auc = info.ap ; end % TREC 11 points average interpolated precision info.ap_interp_11 = 0.0 ; for rc = linspace(0,1,11) pr = max([0, precision(recall >= rc)]) ; info.ap_interp_11 = info.ap_interp_11 + pr / 11 ; end % legacy definition info.auc_pa08 = info.ap_interp_11 ; end % -------------------------------------------------------------------- % Plot % -------------------------------------------------------------------- if nargout == 0 cla ; hold on ; plot(recall,precision,'linewidth',2) ; if isempty(opts.normalizePrior) randomPrecision = p / (p + n) ; else randomPrecision = opts.normalizePrior ; end spline([0 1], [1 1] * randomPrecision, 'r--', 'linewidth', 2) ; axis square ; grid on ; xlim([0 1]) ; xlabel('recall') ; ylim([0 1]) ; ylabel('precision') ; title(sprintf('PR (AUC: %.2f%%, AP: %.2f%%, AP11: %.2f%%)', ... info.auc * 100, ... info.ap * 100, ... info.ap_interp_11 * 100)) ; if opts.interpolate legend('PR interp.', 'PR rand.', 'Location', 'SouthEast') ; else legend('PR', 'PR rand.', 'Location', 'SouthEast') ; end clear recall precision info ; end % -------------------------------------------------------------------- % Stable output % -------------------------------------------------------------------- if opts.stable precision(1) = [] ; recall(1) = [] ; precision_ = precision ; recall_ = recall ; precision = NaN(size(precision)) ; recall = NaN(size(recall)) ; precision(perm) = precision_ ; recall(perm) = recall_ ; end % -------------------------------------------------------------------- function h = spline(x,y,spec,varargin) % -------------------------------------------------------------------- prop = vl_linespec2prop(spec) ; h = line(x,y,prop{:},varargin{:}) ;
github
jianxiongxiao/ProfXkit-master
vl_ubcread.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/sift/vl_ubcread.m
3,015
utf_8
e8ddd3ecd87e76b6c738ba153fef050f
function [f,d] = vl_ubcread(file, varargin) % SIFTREAD Read Lowe's SIFT implementation data files % [F,D] = VL_UBCREAD(FILE) reads the frames F and the descriptors D % from FILE in UBC (Lowe's original implementation of SIFT) format % and returns F and D as defined by VL_SIFT(). % % VL_UBCREAD(FILE, 'FORMAT', 'OXFORD') assumes the format used by % Oxford VGG implementations . % % See also: VL_SIFT(), VL_HELP(). % Authors: Andrea Vedaldi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.verbosity = 0 ; opts.format = 'ubc' ; opts = vl_argparse(opts, varargin) ; g = fopen(file, 'r'); if g == -1 error(['Could not open file ''', file, '''.']) ; end [header, count] = fscanf(g, '%d', [1 2]) ; if count ~= 2 error('Invalid keypoint file header.'); end switch opts.format case 'ubc' numKeypoints = header(1) ; descrLen = header(2) ; case 'oxford' numKeypoints = header(2) ; descrLen = header(1) ; otherwise error('Unknown format ''%s''.', opts.format) ; end if(opts.verbosity > 0) fprintf('%d keypoints, %d descriptor length.\n', numKeypoints, descrLen) ; end %creates two output matrices switch opts.format case 'ubc' P = zeros(4,numKeypoints) ; case 'oxford' P = zeros(5,numKeypoints) ; end L = zeros(descrLen, numKeypoints) ; %parse tmp.key for k = 1:numKeypoints switch opts.format case 'ubc' % Record format: i,j,s,th [record, count] = fscanf(g, '%f', [1 4]) ; if count ~= 4 error(... sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) ); end P(:,k) = record(:) ; case 'oxford' % Record format: x, y, a, b, c such that x' [a b ; b c] x = 1 [record, count] = fscanf(g, '%f', [1 5]) ; if count ~= 5 error(... sprintf('Invalid keypoint file (parsing keypoint %d, frame part)',k) ); end P(:,k) = record(:) ; end % Record format: descriptor [record, count] = fscanf(g, '%d', [1 descrLen]) ; if count ~= descrLen error(... sprintf('Invalid keypoint file (parsing keypoint %d, descriptor part)',k) ); end L(:,k) = record(:) ; end fclose(g) ; switch opts.format case 'ubc' P(1:2,:) = flipud(P(1:2,:)) + 1 ; % i,j -> x,y f=[ P(1:2,:) ; P(3,:) ; -P(4,:) ] ; d=uint8(L) ; p=[1 2 3 4 5 6 7 8] ; q=[1 8 7 6 5 4 3 2] ; for j=0:3 for i=0:3 d(8*(i+4*j)+p,:) = d(8*(i+4*j)+q,:) ; end end case 'oxford' P(1:2,:) = P(1:2,:) + 1 ; % matlab origin f = P ; f(3:5,:) = inv2x2(f(3:5,:)) ; d = uint8(L) ; end % -------------------------------------------------------------------- function S = inv2x2(C) % -------------------------------------------------------------------- den = C(1,:) .* C(3,:) - C(2,:) .* C(2,:) ; S = [C(3,:) ; -C(2,:) ; C(1,:)] ./ den([1 1 1], :) ;
github
jianxiongxiao/ProfXkit-master
vl_frame2oell.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/sift/vl_frame2oell.m
2,160
utf_8
457c5f2e8b637108c8c1b2256396de13
function eframes = vl_frame2oell(frames) % FRAMES2OELL Convert generic feature frames to oriented ellipses % EFRAMES = VL_FRAME2OELL(FRAMES) converts the specified FRAMES to % the oriented ellipses EFRAMES. % % A frame is either a point, disc, oriented disc, ellipse, or % oriented ellipse. These are represened respecively by % 2, 3, 4, 5 and 6 parameters each, as described in VL_PLOTFRAME(). % % An oriented ellipse is the most general frame. When an unoriented % frame is converted to an oriented ellipse, the rotation is selected % so that the positive Y direction is unchanged. % % See: VL_PLOTFRAME(), VL_HELP(). % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). [D,K] = size(frames) ; eframes = zeros(6,K) ; switch D case 2 eframes(1:2,:) = frames(1:2,:) ; case 3 eframes(1:2,:) = frames(1:2,:) ; eframes(3,:) = frames(3,:) ; eframes(6,:) = frames(3,:) ; case 4 r = frames(3,:) ; c = r.*cos(frames(4,:)) ; s = r.*sin(frames(4,:)) ; eframes(1:2,:) = frames(1:2,:) ; eframes(3:6,:) = [c ; s ; -s ; c] ; case 5 eframes(1:2,:) = frames(1:2,:) ; eframes(3:6,:) = mapFromS(frames(3:5,:)) ; case 6 eframes = frames ; otherwise error('FRAMES format is unknown.') ; end % -------------------------------------------------------------------- function A = mapFromS(S) % -------------------------------------------------------------------- % Returns the (stacking of the) 2x2 matrix A that maps the unit circle % into the ellipses satisfying the equation x' inv(S) x = 1. Here S % is a stacked covariance matrix, with elements S11, S12 and S22. % % The goal is to find A such that AA' = S. In order to let the Y % direction unaffected (upright feature), the assumption is taht % A = [a b ; 0 c]. Hence % % AA' = [a^2, ab ; ab, b^2+c^2] = S. A = zeros(4,size(S,2)) ; a = sqrt(S(1,:)); b = S(2,:) ./ max(a, 1e-18) ; A(1,:) = a ; A(2,:) = b ; A(4,:) = sqrt(max(S(3,:) - b.*b, 0)) ;
github
jianxiongxiao/ProfXkit-master
vl_plotsiftdescriptor.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/sift/vl_plotsiftdescriptor.m
4,725
utf_8
395bf4e0d7417674401ddf34cc8a70da
function h=vl_plotsiftdescriptor(d,f,varargin) % VL_PLOTSIFTDESCRIPTOR Plot SIFT descriptor % VL_PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptors D, stored as % columns of the matrix D. D has the same format used by VL_SIFT(). % % VL_PLOTSIFTDESCRIPTOR(D,F) plots the SIFT descriptors warped to % the SIFT frames F, specified as columns of the matrix F. F has the % same format used by VL_SIFT(). % % H=VL_PLOTSIFTDESCRIPTOR(...) returns the handle H to the line drawing % representing the descriptors. % % REMARK. By default, the function assumes descriptors with 4x4 % spatial bins and 8 orientation bins (Lowe's default.) % % The function supports the following options % % NumSpatialBins:: [4] % Number of spatial bins in each spatial direction. % % NumOrientBins:: [8] % Number of orientation bis. % % Magnif:: [3] % Magnification factor. % % See also: VL_SIFT(), VL_PLOTFRAME(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). magnif = 3.0 ; NBP = 4 ; NBO = 8 ; maxv = 0 ; if nargin > 1 if ~ isnumeric(f) error('F must be a numeric type (use [] to leave it unspecified)') ; end end for k=1:2:length(varargin) opt=lower(varargin{k}) ; arg=varargin{k+1} ; switch opt case 'numspatialbins' NBP = arg ; case 'numorientbins' NBO = arg ; case 'magnif' magnif = arg ; case 'maxv' maxv = arg ; otherwise error(sprintf('Unknown option ''%s''.', opt)) ; end end % -------------------------------------------------------------------- % Check the arguments % -------------------------------------------------------------------- if(size(d,1) ~= NBP*NBP*NBO) error('The number of rows of D does not match the geometry of the descriptor') ; end if nargin > 1 if (~isempty(f) & (size(f,1) < 2 | size(f,1) > 6)) error('F must be either empty of have from 2 to six rows.'); end if size(f,1) == 2 % translation only f(3:6,:) = deal([10 0 0 10]') ; %f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ; end if size(f,1) == 3 % translation and scale f(3:6,:) = [1 0 0 1]' * f(3,:) ; %f = [f; 0 * zeros(1, size(f,2))] ; end if size(f,1) == 4 c = cos(f(4,:)) ; s = sin(f(4,:)) ; f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ; end if size(f,1) == 5 assert(false) ; c = cos(f(4,:)) ; s = sin(f(4,:)) ; f(3:6,:) = bsxfun(@times, f(3,:), [c ; s ; -s ; c]) ; end if(~isempty(f) & size(f,2) ~= size(d,2)) error('D and F have incompatible dimension') ; end end % Descriptors are often non-double numeric arrays d = double(d) ; K = size(d,2) ; if nargin < 2 | isempty(f) f = repmat([0;0;1;0],1,K) ; end % -------------------------------------------------------------------- % Do the job % -------------------------------------------------------------------- xall=[] ; yall=[] ; for k=1:K [x,y] = render_descr(d(:,k), NBP, NBO, maxv) ; xall = [xall magnif*f(3,k)*x + magnif*f(5,k)*y + f(1,k)] ; yall = [yall magnif*f(4,k)*x + magnif*f(6,k)*y + f(2,k)] ; end h=line(xall,yall) ; % -------------------------------------------------------------------- function [x,y] = render_descr(d, BP, BO, maxv) % -------------------------------------------------------------------- [x,y] = meshgrid(-BP/2:BP/2,-BP/2:BP/2) ; % Rescale d so that the biggest peak fits inside the bin diagram if maxv d = 0.4 * d / maxv ; else d = 0.4 * d / max(d(:)+eps) ; end % We have BP*BP bins to plot. Here are the centers: xc = x(1:end-1,1:end-1) + 0.5 ; yc = y(1:end-1,1:end-1) + 0.5 ; % We scramble the the centers to have the in row major order % (descriptor convention). xc = xc' ; yc = yc' ; % Each spatial bin contains a star with BO tips xc = repmat(xc(:)',BO,1) ; yc = repmat(yc(:)',BO,1) ; % Do the stars th=linspace(0,2*pi,BO+1) ; th=th(1:end-1) ; xd = repmat(cos(th), 1, BP*BP) ; yd = repmat(sin(th), 1, BP*BP) ; xd = xd .* d(:)' ; yd = yd .* d(:)' ; % Re-arrange in sequential order the lines to draw nans = NaN * ones(1,BP^2*BO) ; x1 = xc(:)' ; y1 = yc(:)' ; x2 = x1 + xd ; y2 = y1 + yd ; xstars = [x1;x2;nans] ; ystars = [y1;y2;nans] ; % Horizontal lines of the grid nans = NaN * ones(1,BP+1); xh = [x(:,1)' ; x(:,end)' ; nans] ; yh = [y(:,1)' ; y(:,end)' ; nans] ; % Verical lines of the grid xv = [x(1,:) ; x(end,:) ; nans] ; yv = [y(1,:) ; y(end,:) ; nans] ; x=[xstars(:)' xh(:)' xv(:)'] ; y=[ystars(:)' yh(:)' yv(:)'] ;
github
jianxiongxiao/ProfXkit-master
phow_caltech101.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/apps/phow_caltech101.m
11,595
utf_8
cdd4c2add2b7bbfe66a43831513f99fc
function phow_caltech101() % PHOW_CALTECH101 Image classification in the Caltech-101 dataset % This program demonstrates how to use VLFeat to construct an image % classifier on the Caltech-101 data. The classifier uses PHOW % features (dense SIFT), spatial histograms of visual words, and a % Chi2 SVM. To speedup computation it uses VLFeat fast dense SIFT, % kd-trees, and homogeneous kernel map. The program also % demonstrates VLFeat PEGASOS SVM solver, although for this small % dataset other solvers such as LIBLINEAR can be more efficient. % % By default 15 training images are used, which should result in % about 64% performance (a good performance considering that only a % single feature type is being used). % % Call PHOW_CALTECH101 to train and test a classifier on a small % subset of the Caltech-101 data. Note that the program % automatically downloads a copy of the Caltech-101 data from the % Internet if it cannot find a local copy. % % Edit the PHOW_CALTECH101 file to change the program configuration. % % To run on the entire dataset change CONF.TINYPROBLEM to FALSE. % % The Caltech-101 data is saved into CONF.CALDIR, which defaults to % 'data/caltech-101'. Change this path to the desired location, for % instance to point to an existing copy of the Caltech-101 data. % % The program can also be used to train a model on custom data by % pointing CONF.CALDIR to it. Just create a subdirectory for each % class and put the training images there. Make sure to adjust % CONF.NUMTRAIN accordingly. % % Intermediate files are stored in the directory CONF.DATADIR. All % such files begin with the prefix CONF.PREFIX, which can be changed % to test different parameter settings without overriding previous % results. % % The program saves the trained model in % <CONF.DATADIR>/<CONF.PREFIX>-model.mat. This model can be used to % test novel images independently of the Caltech data. % % load('data/baseline-model.mat') ; # change to the model path % label = model.classify(model, im) ; % % Author: Andrea Vedaldi % Copyright (C) 2011-2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). conf.calDir = 'data/caltech-101' ; conf.dataDir = 'data/' ; conf.autoDownloadData = true ; conf.numTrain = 15 ; conf.numTest = 15 ; conf.numClasses = 102 ; conf.numWords = 600 ; conf.numSpatialX = [2 4] ; conf.numSpatialY = [2 4] ; conf.quantizer = 'kdtree' ; conf.svm.C = 10 ; conf.svm.solver = 'sdca' ; %conf.svm.solver = 'sgd' ; %conf.svm.solver = 'liblinear' ; conf.svm.biasMultiplier = 1 ; conf.phowOpts = {'Step', 3} ; conf.clobber = false ; conf.tinyProblem = true ; conf.prefix = 'baseline' ; conf.randSeed = 1 ; if conf.tinyProblem conf.prefix = 'tiny' ; conf.numClasses = 5 ; conf.numSpatialX = 2 ; conf.numSpatialY = 2 ; conf.numWords = 300 ; conf.phowOpts = {'Verbose', 2, 'Sizes', 7, 'Step', 5} ; end conf.vocabPath = fullfile(conf.dataDir, [conf.prefix '-vocab.mat']) ; conf.histPath = fullfile(conf.dataDir, [conf.prefix '-hists.mat']) ; conf.modelPath = fullfile(conf.dataDir, [conf.prefix '-model.mat']) ; conf.resultPath = fullfile(conf.dataDir, [conf.prefix '-result']) ; randn('state',conf.randSeed) ; rand('state',conf.randSeed) ; vl_twister('state',conf.randSeed) ; % -------------------------------------------------------------------- % Download Caltech-101 data % -------------------------------------------------------------------- if ~exist(conf.calDir, 'dir') || ... (~exist(fullfile(conf.calDir, 'airplanes'),'dir') && ... ~exist(fullfile(conf.calDir, '101_ObjectCategories', 'airplanes'))) if ~conf.autoDownloadData error(... ['Caltech-101 data not found. ' ... 'Set conf.autoDownloadData=true to download the required data.']) ; end vl_xmkdir(conf.calDir) ; calUrl = ['http://www.vision.caltech.edu/Image_Datasets/' ... 'Caltech101/101_ObjectCategories.tar.gz'] ; fprintf('Downloading Caltech-101 data to ''%s''. This will take a while.', conf.calDir) ; untar(calUrl, conf.calDir) ; end if ~exist(fullfile(conf.calDir, 'airplanes'),'dir') conf.calDir = fullfile(conf.calDir, '101_ObjectCategories') ; end % -------------------------------------------------------------------- % Setup data % -------------------------------------------------------------------- classes = dir(conf.calDir) ; classes = classes([classes.isdir]) ; classes = {classes(3:conf.numClasses+2).name} ; images = {} ; imageClass = {} ; for ci = 1:length(classes) ims = dir(fullfile(conf.calDir, classes{ci}, '*.jpg'))' ; ims = vl_colsubset(ims, conf.numTrain + conf.numTest) ; ims = cellfun(@(x)fullfile(classes{ci},x),{ims.name},'UniformOutput',false) ; images = {images{:}, ims{:}} ; imageClass{end+1} = ci * ones(1,length(ims)) ; end selTrain = find(mod(0:length(images)-1, conf.numTrain+conf.numTest) < conf.numTrain) ; selTest = setdiff(1:length(images), selTrain) ; imageClass = cat(2, imageClass{:}) ; model.classes = classes ; model.phowOpts = conf.phowOpts ; model.numSpatialX = conf.numSpatialX ; model.numSpatialY = conf.numSpatialY ; model.quantizer = conf.quantizer ; model.vocab = [] ; model.w = [] ; model.b = [] ; model.classify = @classify ; % -------------------------------------------------------------------- % Train vocabulary % -------------------------------------------------------------------- if ~exist(conf.vocabPath) || conf.clobber % Get some PHOW descriptors to train the dictionary selTrainFeats = vl_colsubset(selTrain, 30) ; descrs = {} ; %for ii = 1:length(selTrainFeats) parfor ii = 1:length(selTrainFeats) im = imread(fullfile(conf.calDir, images{selTrainFeats(ii)})) ; im = standarizeImage(im) ; [drop, descrs{ii}] = vl_phow(im, model.phowOpts{:}) ; end descrs = vl_colsubset(cat(2, descrs{:}), 10e4) ; descrs = single(descrs) ; % Quantize the descriptors to get the visual words vocab = vl_kmeans(descrs, conf.numWords, 'verbose', 'algorithm', 'elkan', 'MaxNumIterations', 50) ; save(conf.vocabPath, 'vocab') ; else load(conf.vocabPath) ; end model.vocab = vocab ; if strcmp(model.quantizer, 'kdtree') model.kdtree = vl_kdtreebuild(vocab) ; end % -------------------------------------------------------------------- % Compute spatial histograms % -------------------------------------------------------------------- if ~exist(conf.histPath) || conf.clobber hists = {} ; parfor ii = 1:length(images) % for ii = 1:length(images) fprintf('Processing %s (%.2f %%)\n', images{ii}, 100 * ii / length(images)) ; im = imread(fullfile(conf.calDir, images{ii})) ; hists{ii} = getImageDescriptor(model, im); end hists = cat(2, hists{:}) ; save(conf.histPath, 'hists') ; else load(conf.histPath) ; end % -------------------------------------------------------------------- % Compute feature map % -------------------------------------------------------------------- psix = vl_homkermap(hists, 1, 'kchi2', 'gamma', .5) ; % -------------------------------------------------------------------- % Train SVM % -------------------------------------------------------------------- if ~exist(conf.modelPath) || conf.clobber switch conf.svm.solver case {'sgd', 'sdca'} lambda = 1 / (conf.svm.C * length(selTrain)) ; w = [] ; parfor ci = 1:length(classes) perm = randperm(length(selTrain)) ; fprintf('Training model for class %s\n', classes{ci}) ; y = 2 * (imageClass(selTrain) == ci) - 1 ; [w(:,ci) b(ci) info] = vl_svmtrain(psix(:, selTrain(perm)), y(perm), lambda, ... 'Solver', conf.svm.solver, ... 'MaxNumIterations', 50/lambda, ... 'BiasMultiplier', conf.svm.biasMultiplier, ... 'Epsilon', 1e-3); end case 'liblinear' svm = train(imageClass(selTrain)', ... sparse(double(psix(:,selTrain))), ... sprintf(' -s 3 -B %f -c %f', ... conf.svm.biasMultiplier, conf.svm.C), ... 'col') ; w = svm.w(:,1:end-1)' ; b = svm.w(:,end)' ; end model.b = conf.svm.biasMultiplier * b ; model.w = w ; save(conf.modelPath, 'model') ; else load(conf.modelPath) ; end % -------------------------------------------------------------------- % Test SVM and evaluate % -------------------------------------------------------------------- % Estimate the class of the test images scores = model.w' * psix + model.b' * ones(1,size(psix,2)) ; [drop, imageEstClass] = max(scores, [], 1) ; % Compute the confusion matrix idx = sub2ind([length(classes), length(classes)], ... imageClass(selTest), imageEstClass(selTest)) ; confus = zeros(length(classes)) ; confus = vl_binsum(confus, ones(size(idx)), idx) ; % Plots figure(1) ; clf; subplot(1,2,1) ; imagesc(scores(:,[selTrain selTest])) ; title('Scores') ; set(gca, 'ytick', 1:length(classes), 'yticklabel', classes) ; subplot(1,2,2) ; imagesc(confus) ; title(sprintf('Confusion matrix (%.2f %% accuracy)', ... 100 * mean(diag(confus)/conf.numTest) )) ; print('-depsc2', [conf.resultPath '.ps']) ; save([conf.resultPath '.mat'], 'confus', 'conf') ; % ------------------------------------------------------------------------- function im = standarizeImage(im) % ------------------------------------------------------------------------- im = im2single(im) ; if size(im,1) > 480, im = imresize(im, [480 NaN]) ; end % ------------------------------------------------------------------------- function hist = getImageDescriptor(model, im) % ------------------------------------------------------------------------- im = standarizeImage(im) ; width = size(im,2) ; height = size(im,1) ; numWords = size(model.vocab, 2) ; % get PHOW features [frames, descrs] = vl_phow(im, model.phowOpts{:}) ; % quantize local descriptors into visual words switch model.quantizer case 'vq' [drop, binsa] = min(vl_alldist(model.vocab, single(descrs)), [], 1) ; case 'kdtree' binsa = double(vl_kdtreequery(model.kdtree, model.vocab, ... single(descrs), ... 'MaxComparisons', 50)) ; end for i = 1:length(model.numSpatialX) binsx = vl_binsearch(linspace(1,width,model.numSpatialX(i)+1), frames(1,:)) ; binsy = vl_binsearch(linspace(1,height,model.numSpatialY(i)+1), frames(2,:)) ; % combined quantization bins = sub2ind([model.numSpatialY(i), model.numSpatialX(i), numWords], ... binsy,binsx,binsa) ; hist = zeros(model.numSpatialY(i) * model.numSpatialX(i) * numWords, 1) ; hist = vl_binsum(hist, ones(size(bins)), bins) ; hists{i} = single(hist / sum(hist)) ; end hist = cat(1,hists{:}) ; hist = hist / sum(hist) ; % ------------------------------------------------------------------------- function [className, score] = classify(model, im) % ------------------------------------------------------------------------- hist = getImageDescriptor(model, im) ; psix = vl_homkermap(hist, 1, 'kchi2', 'period', .7) ; scores = model.w' * psix + model.b' ; [score, best] = max(scores) ; className = model.classes{best} ;
github
jianxiongxiao/ProfXkit-master
sift_mosaic.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/apps/sift_mosaic.m
4,621
utf_8
8fa3ad91b401b8f2400fb65944c79712
function mosaic = sift_mosaic(im1, im2) % SIFT_MOSAIC Demonstrates matching two images using SIFT and RANSAC % % SIFT_MOSAIC demonstrates matching two images based on SIFT % features and RANSAC and computing their mosaic. % % SIFT_MOSAIC by itself runs the algorithm on two standard test % images. Use SIFT_MOSAIC(IM1,IM2) to compute the mosaic of two % custom images IM1 and IM2. % AUTORIGHTS if nargin == 0 im1 = imread(fullfile(vl_root, 'data', 'river1.jpg')) ; im2 = imread(fullfile(vl_root, 'data', 'river2.jpg')) ; end % make single im1 = im2single(im1) ; im2 = im2single(im2) ; % make grayscale if size(im1,3) > 1, im1g = rgb2gray(im1) ; else im1g = im1 ; end if size(im2,3) > 1, im2g = rgb2gray(im2) ; else im2g = im2 ; end % -------------------------------------------------------------------- % SIFT matches % -------------------------------------------------------------------- [f1,d1] = vl_sift(im1g) ; [f2,d2] = vl_sift(im2g) ; [matches, scores] = vl_ubcmatch(d1,d2) ; numMatches = size(matches,2) ; X1 = f1(1:2,matches(1,:)) ; X1(3,:) = 1 ; X2 = f2(1:2,matches(2,:)) ; X2(3,:) = 1 ; % -------------------------------------------------------------------- % RANSAC with homography model % -------------------------------------------------------------------- clear H score ok ; for t = 1:100 % estimate homograpyh subset = vl_colsubset(1:numMatches, 4) ; A = [] ; for i = subset A = cat(1, A, kron(X1(:,i)', vl_hat(X2(:,i)))) ; end [U,S,V] = svd(A) ; H{t} = reshape(V(:,9),3,3) ; % score homography X2_ = H{t} * X1 ; du = X2_(1,:)./X2_(3,:) - X2(1,:)./X2(3,:) ; dv = X2_(2,:)./X2_(3,:) - X2(2,:)./X2(3,:) ; ok{t} = (du.*du + dv.*dv) < 6*6 ; score(t) = sum(ok{t}) ; end [score, best] = max(score) ; H = H{best} ; ok = ok{best} ; % -------------------------------------------------------------------- % Optional refinement % -------------------------------------------------------------------- function err = residual(H) u = H(1) * X1(1,ok) + H(4) * X1(2,ok) + H(7) ; v = H(2) * X1(1,ok) + H(5) * X1(2,ok) + H(8) ; d = H(3) * X1(1,ok) + H(6) * X1(2,ok) + 1 ; du = X2(1,ok) - u ./ d ; dv = X2(2,ok) - v ./ d ; err = sum(du.*du + dv.*dv) ; end if exist('fminsearch') == 2 H = H / H(3,3) ; opts = optimset('Display', 'none', 'TolFun', 1e-8, 'TolX', 1e-8) ; H(1:8) = fminsearch(@residual, H(1:8)', opts) ; else warning('Refinement disabled as fminsearch was not found.') ; end % -------------------------------------------------------------------- % Show matches % -------------------------------------------------------------------- dh1 = max(size(im2,1)-size(im1,1),0) ; dh2 = max(size(im1,1)-size(im2,1),0) ; figure(1) ; clf ; subplot(2,1,1) ; imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ; o = size(im1,2) ; line([f1(1,matches(1,:));f2(1,matches(2,:))+o], ... [f1(2,matches(1,:));f2(2,matches(2,:))]) ; title(sprintf('%d tentative matches', numMatches)) ; axis image off ; subplot(2,1,2) ; imagesc([padarray(im1,dh1,'post') padarray(im2,dh2,'post')]) ; o = size(im1,2) ; line([f1(1,matches(1,ok));f2(1,matches(2,ok))+o], ... [f1(2,matches(1,ok));f2(2,matches(2,ok))]) ; title(sprintf('%d (%.2f%%) inliner matches out of %d', ... sum(ok), ... 100*sum(ok)/numMatches, ... numMatches)) ; axis image off ; drawnow ; % -------------------------------------------------------------------- % Mosaic % -------------------------------------------------------------------- box2 = [1 size(im2,2) size(im2,2) 1 ; 1 1 size(im2,1) size(im2,1) ; 1 1 1 1 ] ; box2_ = inv(H) * box2 ; box2_(1,:) = box2_(1,:) ./ box2_(3,:) ; box2_(2,:) = box2_(2,:) ./ box2_(3,:) ; ur = min([1 box2_(1,:)]):max([size(im1,2) box2_(1,:)]) ; vr = min([1 box2_(2,:)]):max([size(im1,1) box2_(2,:)]) ; [u,v] = meshgrid(ur,vr) ; im1_ = vl_imwbackward(im2double(im1),u,v) ; z_ = H(3,1) * u + H(3,2) * v + H(3,3) ; u_ = (H(1,1) * u + H(1,2) * v + H(1,3)) ./ z_ ; v_ = (H(2,1) * u + H(2,2) * v + H(2,3)) ./ z_ ; im2_ = vl_imwbackward(im2double(im2),u_,v_) ; mass = ~isnan(im1_) + ~isnan(im2_) ; im1_(isnan(im1_)) = 0 ; im2_(isnan(im2_)) = 0 ; mosaic = (im1_ + im2_) ./ mass ; figure(2) ; clf ; imagesc(mosaic) ; axis image off ; title('Mosaic') ; if nargout == 0, clear mosaic ; end end
github
jianxiongxiao/ProfXkit-master
encodeImage.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/apps/recognition/encodeImage.m
5,278
utf_8
5d9dc6161995b8e10366b5649bf4fda4
function descrs = encodeImage(encoder, im, varargin) % ENCODEIMAGE Apply an encoder to an image % DESCRS = ENCODEIMAGE(ENCODER, IM) applies the ENCODER % to image IM, returning a corresponding code vector PSI. % % IM can be an image, the path to an image, or a cell array of % the same, to operate on multiple images. % % ENCODEIMAGE(ENCODER, IM, CACHE) utilizes the specified CACHE % directory to store encodings for the given images. The cache % is used only if the images are specified as file names. % % See also: TRAINENCODER(). % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.cacheDir = [] ; opts.cacheChunkSize = 512 ; opts = vl_argparse(opts,varargin) ; if ~iscell(im), im = {im} ; end % break the computation into cached chunks startTime = tic ; descrs = cell(1, numel(im)) ; numChunks = ceil(numel(im) / opts.cacheChunkSize) ; for c = 1:numChunks n = min(opts.cacheChunkSize, numel(im) - (c-1)*opts.cacheChunkSize) ; chunkPath = fullfile(opts.cacheDir, sprintf('chunk-%03d.mat',c)) ; if ~isempty(opts.cacheDir) && exist(chunkPath) fprintf('%s: loading descriptors from %s\n', mfilename, chunkPath) ; load(chunkPath, 'data') ; else range = (c-1)*opts.cacheChunkSize + (1:n) ; fprintf('%s: processing a chunk of %d images (%3d of %3d, %5.1fs to go)\n', ... mfilename, numel(range), ... c, numChunks, toc(startTime) / (c - 1) * (numChunks - c + 1)) ; data = processChunk(encoder, im(range)) ; if ~isempty(opts.cacheDir) save(chunkPath, 'data') ; end end descrs{c} = data ; clear data ; end descrs = cat(2,descrs{:}) ; % -------------------------------------------------------------------- function psi = processChunk(encoder, im) % -------------------------------------------------------------------- psi = cell(1,numel(im)) ; if numel(im) > 1 & matlabpool('size') > 1 parfor i = 1:numel(im) psi{i} = encodeOne(encoder, im{i}) ; end else % avoiding parfor makes debugging easier for i = 1:numel(im) psi{i} = encodeOne(encoder, im{i}) ; end end psi = cat(2, psi{:}) ; % -------------------------------------------------------------------- function psi = encodeOne(encoder, im) % -------------------------------------------------------------------- im = encoder.readImageFn(im) ; features = encoder.extractorFn(im) ; imageSize = size(im) ; psi = {} ; for i = 1:size(encoder.subdivisions,2) minx = encoder.subdivisions(1,i) * imageSize(2) ; miny = encoder.subdivisions(2,i) * imageSize(1) ; maxx = encoder.subdivisions(3,i) * imageSize(2) ; maxy = encoder.subdivisions(4,i) * imageSize(1) ; ok = ... minx <= features.frame(1,:) & features.frame(1,:) < maxx & ... miny <= features.frame(2,:) & features.frame(2,:) < maxy ; descrs = encoder.projection * bsxfun(@minus, ... features.descr(:,ok), ... encoder.projectionCenter) ; if encoder.renormalize descrs = bsxfun(@times, descrs, 1./max(1e-12, sqrt(sum(descrs.^2)))) ; end w = size(im,2) ; h = size(im,1) ; frames = features.frame(1:2,:) ; frames = bsxfun(@times, bsxfun(@minus, frames, [w;h]/2), 1./[w;h]) ; descrs = extendDescriptorsWithGeometry(encoder.geometricExtension, frames, descrs) ; switch encoder.type case 'bovw' [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ... descrs, ... 'MaxComparisons', 100) ; z = vl_binsum(zeros(encoder.numWords,1), 1, double(words)) ; z = sqrt(z) ; case 'fv' z = vl_fisher(descrs, ... encoder.means, ... encoder.covariances, ... encoder.priors, ... 'Improved') ; case 'vlad' [words,distances] = vl_kdtreequery(encoder.kdtree, encoder.words, ... descrs, ... 'MaxComparisons', 15) ; assign = zeros(encoder.numWords, numel(words), 'single') ; assign(sub2ind(size(assign), double(words), 1:numel(words))) = 1 ; z = vl_vlad(descrs, ... encoder.words, ... assign, ... 'SquareRoot', ... 'NormalizeComponents') ; end z = z / max(sqrt(sum(z.^2)), 1e-12) ; psi{i} = z(:) ; end psi = cat(1, psi{:}) ; % -------------------------------------------------------------------- function psi = getFromCache(name, cache) % -------------------------------------------------------------------- [drop, name] = fileparts(name) ; cachePath = fullfile(cache, [name '.mat']) ; if exist(cachePath, 'file') data = load(cachePath) ; psi = data.psi ; else psi = [] ; end % -------------------------------------------------------------------- function storeToCache(name, cache, psi) % -------------------------------------------------------------------- [drop, name] = fileparts(name) ; cachePath = fullfile(cache, [name '.mat']) ; vl_xmkdir(cache) ; data.psi = psi ; save(cachePath, '-STRUCT', 'data') ;
github
jianxiongxiao/ProfXkit-master
experiments.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/apps/recognition/experiments.m
6,905
utf_8
1e4a4911eed4a451b9488b9e6cc9b39c
function experiments() % EXPERIMENTS Run image classification experiments % The experimens download a number of benchmark datasets in the % 'data/' subfolder. Make sure that there are several GBs of % space available. % % By default, experiments run with a lite option turned on. This % quickly runs all of them on tiny subsets of the actual data. % This is used only for testing; to run the actual experiments, % set the lite variable to false. % % Running all the experiments is a slow process. Using parallel % MATLAB and several cores/machiens is suggested. % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). lite = true ; clear ex ; ex(1).prefix = 'fv-aug' ; ex(1).trainOpts = {'C', 10} ; ex(1).datasets = {'fmd', 'scene67'} ; ex(1).seed = 1 ; ex(1).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(2) = ex(1) ; ex(2).datasets = {'caltech101'} ; ex(2).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(3) = ex(1) ; ex(3).datasets = {'voc07'} ; ex(3).C = 1 ; ex(4) = ex(1) ; ex(4).prefix = 'vlad-aug' ; ex(4).opts = {... 'type', 'vlad', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 100, ... 'whitening', true, ... 'whiteningRegul', 0.01, ... 'renormalize', true, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(5) = ex(4) ; ex(5).datasets = {'caltech101'} ; ex(5).opts{end} = ex(2).opts{end} ; ex(6) = ex(4) ; ex(6).datasets = {'voc07'} ; ex(6).C = 1 ; ex(7) = ex(1) ; ex(7).prefix = 'bovw-aug' ; ex(7).opts = {... 'type', 'bovw', ... 'numWords', 4096, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'xy', ... 'numPcaDimensions', 100, ... 'whitening', true, ... 'whiteningRegul', 0.01, ... 'renormalize', true, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(8) = ex(7) ; ex(8).datasets = {'caltech101'} ; ex(8).opts{end} = ex(2).opts{end} ; ex(9) = ex(7) ; ex(9).datasets = {'voc07'} ; ex(9).C = 1 ; ex(10).prefix = 'fv' ; ex(10).trainOpts = {'C', 10} ; ex(10).datasets = {'fmd', 'scene67'} ; ex(10).seed = 1 ; ex(10).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1'}, ... 'geometricExtension', 'none', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(11) = ex(10) ; ex(11).datasets = {'caltech101'} ; ex(11).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(12) = ex(10) ; ex(12).datasets = {'voc07'} ; ex(12).C = 1 ; ex(13).prefix = 'fv-sp' ; ex(13).trainOpts = {'C', 10} ; ex(13).datasets = {'fmd', 'scene67'} ; ex(13).seed = 1 ; ex(13).opts = {... 'type', 'fv', ... 'numWords', 256, ... 'layouts', {'1x1', '3x1'}, ... 'geometricExtension', 'none', ... 'numPcaDimensions', 80, ... 'extractorFn', @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(1:-.5:-3))}; ex(14) = ex(13) ; ex(14).datasets = {'caltech101'} ; ex(14).opts{6} = {'1x1', '2x2'} ; ex(14).opts{end} = @(x) getDenseSIFT(x, ... 'step', 4, ... 'scales', 2.^(0:-.5:-3)) ; ex(15) = ex(13) ; ex(15).datasets = {'voc07'} ; ex(15).C = 1 ; if lite, tag = 'lite' ; else, tag = 'ex' ; end for i=1:numel(ex) for j=1:numel(ex(i).datasets) dataset = ex(i).datasets{j} ; if ~isfield(ex(i), 'trainOpts') || ~iscell(ex(i).trainOpts) ex(i).trainOpts = {} ; end traintest(... 'prefix', [tag '-' dataset '-' ex(i).prefix], ... 'seed', ex(i).seed, ... 'dataset', char(dataset), ... 'datasetDir', fullfile('data', dataset), ... 'lite', lite, ... ex(i).trainOpts{:}, ... 'encoderParams', ex(i).opts) ; end end % print HTML table pf('<table>\n') ; ph('method', 'VOC07', 'Caltech 101', 'Scene 67', 'FMD') ; pr('FV', ... ge([tag '-voc07-fv'],'ap11'), ... ge([tag '-caltech101-fv']), ... ge([tag '-scene67-fv']), ... ge([tag '-fmd-fv'])) ; pr('FV + aug.', ... ge([tag '-voc07-fv-aug'],'ap11'), ... ge([tag '-caltech101-fv-aug']), ... ge([tag '-scene67-fv-aug']), ... ge([tag '-fmd-fv-aug'])) ; pr('FV + s.p.', ... ge([tag '-voc07-fv-sp'],'ap11'), ... ge([tag '-caltech101-fv-sp']), ... ge([tag '-scene67-fv-sp']), ... ge([tag '-fmd-fv-sp'])) ; %pr('VLAD', ... % ge([tag '-voc07-vlad'],'ap11'), ... % ge([tag '-caltech101-vlad']), ... % ge([tag '-scene67-vlad']), ... % ge([tag '-fmd-vlad'])) ; pr('VLAD + aug.', ... ge([tag '-voc07-vlad-aug'],'ap11'), ... ge([tag '-caltech101-vlad-aug']), ... ge([tag '-scene67-vlad-aug']), ... ge([tag '-fmd-vlad-aug'])) ; %pr('VLAD+sp', ... % ge([tag '-voc07-vlad-sp'],'ap11'), ... % ge([tag '-caltech101-vlad-sp']), ... % ge([tag '-scene67-vlad-sp']), ... % ge([tag '-fmd-vlad-sp'])) ; %pr('BOVW', ... % ge([tag '-voc07-bovw'],'ap11'), ... % ge([tag '-caltech101-bovw']), ... % ge([tag '-scene67-bovw']), ... % ge([tag '-fmd-bovw'])) ; pr('BOVW + aug.', ... ge([tag '-voc07-bovw-aug'],'ap11'), ... ge([tag '-caltech101-bovw-aug']), ... ge([tag '-scene67-bovw-aug']), ... ge([tag '-fmd-bovw-aug'])) ; %pr('BOVW+sp', ... % ge([tag '-voc07-bovw-sp'],'ap11'), ... % ge([tag '-caltech101-bovw-sp']), ... % ge([tag '-scene67-bovw-sp']), ... % ge([tag '-fmd-bovw-sp'])) ; pf('</table>\n'); function pf(str) fprintf(str) ; function str = ge(name, format) if nargin == 1, format = 'acc'; end data = load(fullfile('data', name, 'result.mat')) ; switch format case 'acc' str = sprintf('%.2f%% <span style="font-size:8px;">Acc</span>', mean(diag(data.confusion)) * 100) ; case 'ap11' str = sprintf('%.2f%% <span style="font-size:8px;">mAP</span>', mean(data.ap11) * 100) ; end function pr(varargin) fprintf('<tr>') ; for i=1:numel(varargin), fprintf('<td>%s</td>',varargin{i}) ; end fprintf('</tr>\n') ; function ph(varargin) fprintf('<tr>') ; for i=1:numel(varargin), fprintf('<th>%s</th>',varargin{i}) ; end fprintf('</tr>\n') ;
github
jianxiongxiao/ProfXkit-master
getDenseSIFT.m
.m
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/apps/recognition/getDenseSIFT.m
1,679
utf_8
2059c0a2a4e762226d89121408c6e51c
function features = getDenseSIFT(im, varargin) % GETDENSESIFT Extract dense SIFT features % FEATURES = GETDENSESIFT(IM) extract dense SIFT features from % image IM. % Author: Andrea Vedaldi % Copyright (C) 2013 Andrea Vedaldi % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). opts.scales = logspace(log10(1), log10(.25), 5) ; opts.contrastthreshold = 0 ; opts.step = 3 ; opts.rootSift = false ; opts.normalizeSift = true ; opts.binSize = 8 ; opts.geometry = [4 4 8] ; opts.sigma = 0 ; opts = vl_argparse(opts, varargin) ; dsiftOpts = {'norm', 'fast', 'floatdescriptors', ... 'step', opts.step, ... 'size', opts.binSize, ... 'geometry', opts.geometry} ; if size(im,3)>1, im = rgb2gray(im) ; end im = im2single(im) ; im = vl_imsmooth(im, opts.sigma) ; for si = 1:numel(opts.scales) im_ = imresize(im, opts.scales(si)) ; [frames{si}, descrs{si}] = vl_dsift(im_, dsiftOpts{:}) ; % root SIFT if opts.rootSift descrs{si} = sqrt(descrs{si}) ; end if opts.normalizeSift descrs{si} = snorm(descrs{si}) ; end % zero low contrast descriptors info.contrast{si} = frames{si}(3,:) ; kill = info.contrast{si} < opts.contrastthreshold ; descrs{si}(:,kill) = 0 ; % store frames frames{si}(1:2,:) = (frames{si}(1:2,:)-1) / opts.scales(si) + 1 ; frames{si}(3,:) = opts.binSize / opts.scales(si) / 3 ; end features.frame = cat(2, frames{:}) ; features.descr = cat(2, descrs{:}) ; features.contrast = cat(2, info.contrast{:}) ; function x = snorm(x) x = bsxfun(@times, x, 1./max(1e-5,sqrt(sum(x.^2,1)))) ;
github
jianxiongxiao/ProfXkit-master
svm_write.m
.m
ProfXkit-master/linearSVM/svm_write.m
1,689
utf_8
1d97a7261c2221bfbca849652a3f67de
% written by Jianxiong Xiao http://mit.edu/jxiao/ function success = svm_write(x, y, c, wMin) % add one example to the training cache global X global Y global n global D if n==size(X,1) % SVM cache is full. Fail to add more training example success = false; else n = n+1; X(n,:) = x; Y(n) = sqrt(c) * y; D(n) = sqrt(c) * (1- y * x * wMin(1:size(X,2))); success = true; end % We aim to solve the following SVM optimization problem % min_{w,e} lambda/2 * ||(w-wMin)||^2 + 1/2 sum_i c_i e_i^2 % s.t. y_i * (w .* X_i + b) >= 1 - e_i % % let v = (w-wMin) % min_{w,e} lambda/2 * v'v + 1/2 sum_i c_i e_i^2 % s.t. y_i * ((v+wMin) .* X_i + b) >= 1 - e_i % let out_i = sqrt(c_i) e_i % min_{w,e} lambda/2 * v'v + 1/2 sum_i out_i^2 % s.t. y_i * ((v+wMin) .* X_i + b) >= 1 - out_i/sqrt(c_i) % that is % min_{w,e} lambda/2 * v'v + 1/2 sum_i out_i^2 % s.t. y_i * (v X_i + wMin X_i + b) >= 1 - out_i/sqrt(c_i) % that is % min_{w,e} lambda/2 * v'v + 1/2 sum_i out_i^2 % s.t. y_i * (v X_i + b) >= (1- y_i *wMin X_i) - out_i/sqrt(c_i) % that is % min_{w,e} lambda/2 * v'v + 1/2 sum_i out_i^2 % s.t. sqrt(c_i) * y_i * (v X_i + b) >= sqrt(c_i) * (1- y_i *wMin X_i) - out_i % that is % min_{w,e} lambda/2 * v'v + 1/2 sum_i out_i^2 % s.t. (sqrt(c_i) * y_i) * (v X_i + b) >= (sqrt(c_i) * (1- y_i *wMin X_i)) - out_i % input transform % Y_i = sqrt(c_i) * y_i; % D_i = sqrt(c_i) * (1- y_i * wMin X_i); % vInit = wInit - wMin; % output transform % w = v+wMin; % [v,b,sv,obj] = linear_primal_svm(lambda,vInit,D, noneg, maxIteration); % min_{w,e} lambda/2 * v'v + 1/2 sum_i out_i^2 % s.t. Y_i * (v .* X_i + b) >= D_i - out_i
github
jianxiongxiao/ProfXkit-master
linear_primal_svm.m
.m
ProfXkit-master/linearSVM/linear_primal_svm.m
8,133
utf_8
903523303e1e128aca50a41e615c2701
function [w,b,sv,obj] = linear_primal_svm(lambda,wInit,bInit,D,noneg, maxIteration,opt) % Solves the following SVM optimization problem in the primal (with quatratic % penalization of the training errors). Default solved by Newton. % % min_{w,e} lambda/2 * w'w + 1/2 sum_i out_i^2 % s.t. Y_i * (w .* X_i + b) >= D_i - out_i % w(nonneg)>=0 % % A global variable X containing the training inputs % should be defined. X is an n x d matrix (n = number of points). % X can be either normal matrix or sparse matrix. % A global variable Y is the target vector of size nx1. Normal SVM will % have +1 and -1 value, but it can be actually aribitury value % A global variable n is the number of elements that you want to use for training. % LAMBDA is the regularization parameter ( = 1/C) % wInit is an optional input for the initial value of [w;b] % dvec is an optional input, usually it is 1 for standard SVM % maxIteration is the number of iterations allowd % % W is the hyperplane w (vector of length d). % B is the bias % The outputs on the training points are either X*W+B % SV is the support vector index number % OBJ is the objective function value % OPT is a structure containing the options (in brackets default values): % cg: Do not use Newton, but nonlinear conjugate gradients [0] % lin_cg: Compute the Newton step with linear CG % [0 unless solving sparse linear SVM] % iter_max_Newton: Maximum number of Newton steps [20] % prec: Stopping criterion % cg_prec and cg_it: stopping criteria for the linear CG. % Original written by Olivier Chapelle @ http://olivier.chapelle.cc/primal/ % Modified by Jianxiong Xiao to have several advance features @ http://mit.edu/jxiao/ if ~exist('maxIteration','var') || maxIteration==Inf % Assign the options to their default values maxIteration = 10000000; end if ~exist('opt','var') % Assign the options to their default values opt = []; end if ~isfield(opt,'cg'), opt.cg = 0; end; if ~isfield(opt,'lin_cg'), opt.lin_cg = 0; end; if ~isfield(opt,'iter_max_Newton'), opt.iter_max_Newton = 20; end; % used to be 20 if ~isfield(opt,'prec'), opt.prec = 1e-6; end; if ~isfield(opt,'cg_prec'), opt.cg_prec = 1e-4; end; if ~isfield(opt,'cg_it'), opt.cg_it = 20; end; global X; global Y; if ~exist('noneg','var') noneg = []; end if ~exist('dvec','var') || isempty(D) D = ones(numel(Y),1); end if isempty(X), error('Global variable X undefined'); end; if ~exist('bInit','var') bInit=0; end if ~exist('wInit','var') d = size(X,2); wInit = zeros(d,1); end if issparse(X) opt.lin_cg = 1; end; if ~opt.cg [sol,obj, sv] = primal_svm_linear (lambda,maxIteration,wInit,bInit,D,noneg,opt); else [sol,obj, sv] = primal_svm_linear_cg(lambda,maxIteration,wInit,bInit,D,noneg,opt); end; % The last component of the solution is the bias b. b = sol(end); w = sol(1:end-1); fprintf('\n'); % ------------------------------- % Train a linear SVM using Newton % ------------------------------- function [w,obj,sv] = primal_svm_linear(lambda,maxIteration,wInit,bInit,D,noneg,opt) global X; global Y; global n; d = size(X,2); w = [wInit; bInit]; % The last component of w is b. w(noneg) = max(w(noneg),0); %out = ones(n,1); % Vector containing 1-Y.*(X*w) out = D(1:n) - Y(1:n).*(X(1:n,:)*w(1:end-1)+w(end)); for iter=1:maxIteration if iter > opt.iter_max_Newton; warning('PrimalSVM:MaxNumNewton','Maximum number of Newton steps reached. Try larger lambda'); break; end; [obj, grad, sv] = obj_fun_linear(w,lambda,out); % Compute the Newton direction either exactly or by linear CG if opt.lin_cg % Advantage of linear CG when using sparse input: the Hessian is never computed explicitly. [step, foo, relres] = minres(@hess_vect_mult, -grad, opt.cg_prec,opt.cg_it,[],[],[],sv,lambda); else Xsv = X(sv,:); hess = lambda*diag([ones(d,1); 0]) + [[Xsv'*Xsv sum(Xsv,1)']; [sum(Xsv) length(sv)]]; % Hessian step = - hess \ grad; % Newton direction end; % Do an exact line search [t,out, sv] = line_search_linear(w,step,out, lambda); w = w + t*step; w(noneg) = max(w(noneg),0); fprintf('Iter = %d, Obj = %f, Nb of sv = %d, Newton decr = %.3f, Line search = %.3f',iter,obj,length(sv),-step'*grad/2,t); if opt.lin_cg fprintf(', Lin CG acc = %.4f \n',relres); else fprintf(' \n'); end; if -step'*grad < opt.prec * obj % Stop when the Newton decrement is small enough break; end; end; % ----------------------------------------------------- % Train a linear SVM using nonlinear conjugate gradient % ----------------------------------------------------- function [w, obj, sv] = primal_svm_linear_cg(lambda,maxIteration,wInit,bInit, D,noneg,opt) global X; global Y; global n; d = size(X,2); w = [wInit; bInit]; % The last component of w is b. w(noneg) = max(w(noneg),0); %out = ones(n,1); % Vector containing 1-Y.*(X*w) out = D(1:n) - Y(1:n).*(X(1:n,:)*w(1:end-1)+w(end)); %go = [X(1:n,:)'*Y(1:n); sum(Y(1:n))]; % -gradient at w=0, need to be change for w!=0 initialization [~, grad] = obj_fun_linear(w,lambda,out); go = -grad; % -gradient s = go; % The first search direction is given by the gradient for iter=1:maxIteration if iter > opt.cg_it * min(n,d) warning('PrimalSVM:MaxNumCG','Maximum number of CG iterations reached. Try larger lambda'); break; end; % Do an exact line search [t,out,sv] = line_search_linear(w,s,out,lambda); w = w + t*s; w(noneg) = max(w(noneg),0); % Compute the new gradient [obj, gn, sv] = obj_fun_linear(w,lambda,out); gn=-gn; fprintf('Iter = %d, Obj = %f, Norm of grad = %.3f \n',iter,obj,norm(gn)); % Stop when the relative decrease in the objective function is small if t*s'*go < opt.prec*obj, break; end; % Flecher-Reeves update. Change 0 in 1 for Polack-Ribiere be = (gn'*gn - 0*gn'*go) / (go'*go); s = be*s+gn; go = gn; end; function [obj, grad, sv] = obj_fun_linear(w,lambda,out) % Compute the objective function, its gradient and the set of support vectors % Out is supposed to contain 1-Y.*(X*w) global X; global Y; global n; out = max(0,out); wb0 = w; wb0(end) = 0; % Do not penalize b <= Very important for object detection obj = sum(out.^2)/2 + lambda*(wb0')*wb0/2; % L2 penalization of the errors grad = lambda*wb0 - [((out.*Y(1:n))'*X(1:n,:))'; sum(out.*Y(1:n))]; % Gradient sv = find(out>0); function [t,out,sv] = line_search_linear(w,d,out,lambda) % From the current solution w, do a line search in the direction d by % 1D Newton minimization global X; global Y; global n; t = 0; % Precompute some dots products Xd = X(1:n,:)*d(1:end-1)+d(end); wd = lambda * w(1:end-1)'*d(1:end-1); dd = lambda * d(1:end-1)'*d(1:end-1); while 1 out2 = out - t*(Y(1:n).*Xd); % The new outputs after a step of length t sv = find(out2>0); g = wd + t*dd - (out2(sv).*Y(sv))'*Xd(sv); % The gradient (along the line) h = dd + Xd(sv)'*Xd(sv); % The second derivative (along the line) t = t - g/h; % Take the 1D Newton step. Note that if d was an exact Newton % direction, t is 1 after the first iteration. if g^2/h < 1e-10, break; end; % fprintf('%f %f\n',t,g^2/h) end; out = out2; function y = hess_vect_mult(w,sv,lambda) % Compute the Hessian times a given vector x. % hess = lambda*diag([ones(d-1,1); 0]) + (X(sv,:)'*X(sv,:)); global X; global n; y = lambda*w; y(end) = 0; z = (X(1:n,:)*w(1:end-1)+w(end)); % Computing X(sv,:)*x takes more time in Matlab :-( zz = zeros(length(z),1); zz(sv)=z(sv); y = y + [(zz'*X(1:n,:))'; sum(zz)];
github
jianxiongxiao/ProfXkit-master
svm_prune.m
.m
ProfXkit-master/linearSVM/svm_prune.m
256
utf_8
b46fdc15f178d5195fca08c9cac7c746
% written by Jianxiong Xiao http://mit.edu/jxiao/ function svm_prune(alwaysKeep) global n; global X; global Y; global D; global SV; SV = unique([SV; alwaysKeep(:)]); SV = SV(SV<=n); n = numel(SV); X(1:n,:) = X(SV,:); Y(1:n) = Y(SV,:); D(1:n) = D(SV);
github
jianxiongxiao/ProfXkit-master
svm_initialize.m
.m
ProfXkit-master/linearSVM/svm_initialize.m
612
utf_8
7d4b63b7e8f43129a9049e7bbdc7374c
% written by Jianxiong Xiao http://mit.edu/jxiao/ function svm_initialize(dimension, RAMsize, isSparse) global n; global X; global Y; global D; global sv; %{ RAMsize = 8; % max memory if RAMsize > memoryLinux()*0.50 RAMsize = min(8,round(memoryLinux()*0.30)); %<- so that we can run two scripts on the same machines end fprintf('Using %.1f GB\n',RAMsize); %} n = round(RAMsize*1024*1024*1024 / (dimension*8) ); % use 8 byte for double fprintf('SVM initalize size = %d\n',n); if isSparse X = sparse(n, dimension); else X = zeros(n, dimension); end Y = zeros(n,1); D = ones(n,1); sv = []; n = 0;
github
jianxiongxiao/ProfXkit-master
estimateRt.m
.m
ProfXkit-master/align2RGBD/align2RGBD/estimateRt.m
501
utf_8
d7ad6f4ea024b18ceb9915fec69b9a71
% Usage: Rt = estimateRt(x1, x2) % Rt = estimateRt(x) % % Arguments: % x1, x2 - Two sets of corresponding 3xN set of homogeneous % points. % % x - If a single argument is supplied it is assumed that it % is in the form x = [x1; x2] % Returns: % Rt - The rotation matrix such that x1 = R * x2 + t function Rt = estimateRt(x, npts) [T, Eps] = estimateRigidTransform(x(1:3,:), x(4:6,:)); Rt = T(1:3,:); end
github
jianxiongxiao/ProfXkit-master
transformPointCloud.m
.m
ProfXkit-master/align2RGBD/align2RGBD/transformPointCloud.m
130
utf_8
ebf18e96a2a3d9ca20da267e9d345dcd
function XYZtransform = transformPointCloud(XYZ,Rt) XYZtransform = Rt(1:3,1:3) * XYZ + repmat(Rt(1:3,4),1,size(XYZ,2)); end
github
jianxiongxiao/ProfXkit-master
ransacfitRt.m
.m
ProfXkit-master/align2RGBD/align2RGBD/ransacfitRt.m
2,888
utf_8
738399412f806f9855724ff192fe4494
% Usage: [Rt, inliers] = ransacfitRt(x1, x2, t) % % Arguments: % x1 - 3xN set of 3D points. % x2 - 3xN set of 3D points such that x1<->x2. % t - The distance threshold between data point and the model % used to decide whether a point is an inlier or not. % % Note that it is assumed that the matching of x1 and x2 are putative and it % is expected that a percentage of matches will be wrong. % % Returns: % Rt - The 3x4 transformation matrix such that x1 = R*x2 + t. % inliers - An array of indices of the elements of x1, x2 that were % the inliers for the best model. % % See Also: RANSAC % Author: Jianxiong Xiao function [Rt, inliers] = ransacfitRt(x, t, feedback) s = 3; % Number of points needed to fit a Rt matrix. if size(x,2)==s inliers = 1:s; Rt = estimateRt(x); return; end fittingfn = @estimateRt; distfn = @euc3Ddist; degenfn = @isdegenerate; % x1 and x2 are 'stacked' to create a 6xN array for ransac [Rt, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback); if length(inliers)<s Rt = [eye(3) zeros(3,1)]; inliers = []; return; end % Now do a final least squares fit on the data points considered to % be inliers. Rt = estimateRt(x(:,inliers)); end %-------------------------------------------------------------------------- % Note that this code allows for Rt being a cell array of matrices of % which we have to pick the best one. function [bestInliers, bestRt] = euc3Ddist(Rt, x, t) if iscell(Rt) % We have several solutions each of which must be tested nRt = length(Rt); % Number of solutions to test bestRt = Rt{1}; % Initial allocation of best solution ninliers = 0; % Number of inliers for k = 1:nRt d = sum((x(1:3,:) - (Rt{k}(:,1:3)*x(4:6,:)+repmat(Rt{k}(:,4),1,size(x,2)))).^2,1).^0.5; inliers = find(abs(d) < t); % Indices of inlying points if length(inliers) > ninliers % Record best solution ninliers = length(inliers); bestRt = Rt{k}; bestInliers = inliers; end end else % We just have one solution d = sum((x(1:3,:) - (Rt(:,1:3)*x(4:6,:)+repmat(Rt(:,4),1,size(x,2)))).^2,1).^0.5; bestInliers = find(abs(d) < t); % Indices of inlying points bestRt = Rt; % Copy Rt directly to bestRt end end %---------------------------------------------------------------------- % (Degenerate!) function to determine if a set of matched points will result % in a degeneracy in the calculation of a fundamental matrix as needed by % RANSAC. This function assumes this cannot happen... function r = isdegenerate(x) r = 0; end
github
jianxiongxiao/ProfXkit-master
show.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/show.m
4,944
utf_8
e2225be3d05b416c72fc6f1acbde02d0
% SHOW - Displays an image with the right size and colors and with a title. % % Usage: % h = show(im) % h = show(im, figNo) % h = show(im, title) % h = show(im, figNo, title) % % Arguments: im - Either a 2 or 3D array of pixel values or the name % of an image file; % figNo - Optional figure number to display image in. If % figNo is 0 the current figure or subplot is % assumed. % title - Optional string specifying figure title % % Returns: h - Handle to the figure. This allows you to set % additional figure attributes if desired. % % The function displays the image, automatically setting the colour map to % grey if it is a 2D image, or leaving it as colour otherwise, and setting % the axes to be 'equal'. The image is also displayed as 'TrueSize', that % is, pixels on the screen match pixels in the image (if it is possible % to fit it on the screen, otherwise MATLAB rescales it to fit). % % Unless you are doing a subplot (figNo==0) the window is sized to match % the image, leaving no border, and hence saving desktop real estate. % % If figNo is omitted a new figure window is created for the image. If % figNo is supplied, and the figure exists, the existing window is reused to % display the image, otherwise a new window is created. If figNo is 0 the % current figure or subplot is assumed. % % See also: SHOWSURF % Copyright (c) 2000-2009 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2000 Original version % March 2003 Mods to alow figure name in window bar and allow for subplots. % April 2007 Proper recording and restoring of MATLAB warning state. % September 2008 Octave compatible % May 2009 Reworked argument handling logic for extra flexibility function h = show(im, param2, param3) Octave = exist('OCTAVE_VERSION') ~= 0; % Are we running under Octave? if ~Octave s = warning('query','all'); % Record existing warning state. warning('off'); % Turn off warnings that might arise if image % has to be rescaled to fit on screen end % Check case where im is an image filename rather than image data if ~isnumeric(im) & ~islogical(im) Title = im; % Default title is file name im = imread(im); else Title = inputname(1); % Default title is variable name of image data end figNo = -1; % Default value indicating create new figure % If two arguments check type of 2nd argument to see if it is the title or % figure number that has been supplied if nargin == 2 if strcmp(class(param2),'char') Title = param2; elseif isnumeric(param2) && length(param2) == 1 figNo = param2; else error('2nd argument must be a figure number or title'); end elseif nargin == 3 figNo = param2; Title = param3; if ~strcmp(class(Title),'char') error('Title must be a string'); end if ~isnumeric(param2) || length(param2) ~= 1 error('Figure number must be an integer'); end end if figNo > 0 % We have a valid figure number figure(figNo); % Reuse or create a figure window with this number if ~Octave subplot('position',[0 0 1 1]); % Use the whole window end elseif figNo == -1 figNo = figure; % Create new figure window if ~Octave subplot('position',[0 0 1 1]); % Use the whole window end end if ndims(im) == 2 % Display as greyscale imagesc(im); colormap('gray'); else imshow(im); % Display as RGB end if figNo == 0 % Assume we are trying to do a subplot figNo = gcf; % Get the current figure number axis('image'); axis('off'); title(Title); % Use a title rather than rename the figure else axis('image'); axis('off'); set(figNo,'name', [' ' Title]) if ~Octave truesize(figNo); end end if nargout == 1 h = figNo; end if ~Octave warning(s); % Restore warnings end
github
jianxiongxiao/ProfXkit-master
nonmaxsuppts.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/nonmaxsuppts.m
5,086
utf_8
6d711b2f28fd3ea2543d59f3e89139b7
% NONMAXSUPPTS - Non-maximal suppression for features/corners % % Non maxima suppression and thresholding for points generated by a feature % or corner detector. % % Usage: [r,c] = nonmaxsuppts(cim, radius, thresh, im) % / % optional % % [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im) % % Arguments: % cim - corner strength image. % radius - radius of region considered in non-maximal % suppression. Typical values to use might % be 1-3 pixels. % thresh - threshold. % im - optional image data. If this is supplied the % thresholded corners are overlayed on this % image. This can be useful for parameter tuning. % Returns: % r - row coordinates of corner points (integer valued). % c - column coordinates of corner points. % rsubp - If four return values are requested sub-pixel % csubp - localization of feature points is attempted and % returned as an additional set of floating point % coords. Note that you may still want to use the integer % valued coords to specify centres of correlation windows % for feature matching. % % Copyright (c) 2003-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 2003 Original version % August 2005 Subpixel localization and Octave compatibility % January 2010 Fix for completely horizontal and vertical lines (by Thomas Stehle, % RWTH Aachen University) % January 2011 Warning given if no maxima found function [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im) subPixel = nargout == 4; % We want sub-pixel locations [rows,cols] = size(cim); % Extract local maxima by performing a grey scale morphological % dilation and then finding points in the corner strength image that % match the dilated image and are also greater than the threshold. sze = 2*radius+1; % Size of dilation mask. mx = ordfilt2(cim,sze^2,ones(sze)); % Grey-scale dilate. % Make mask to exclude points within radius of the image boundary. bordermask = zeros(size(cim)); bordermask(radius+1:end-radius, radius+1:end-radius) = 1; % Find maxima, threshold, and apply bordermask cimmx = (cim==mx) & (cim>thresh) & bordermask; [r,c] = find(cimmx); % Find row,col coords. if subPixel % Compute local maxima to sub pixel accuracy if ~isempty(r) % ...if we have some ponts to work with ind = sub2ind(size(cim),r,c); % 1D indices of feature points w = 1; % Width that we look out on each side of the feature % point to fit a local parabola % Indices of points above, below, left and right of feature point indrminus1 = max(ind-w,1); indrplus1 = min(ind+w,rows*cols); indcminus1 = max(ind-w*rows,1); indcplus1 = min(ind+w*rows,rows*cols); % Solve for quadratic down rows rowshift = zeros(size(ind)); cy = cim(ind); ay = (cim(indrminus1) + cim(indrplus1))/2 - cy; by = ay + cy - cim(indrminus1); rowshift(ay ~= 0) = -w*by(ay ~= 0)./(2*ay(ay ~= 0)); % Maxima of quadradic rowshift(ay == 0) = 0; % Solve for quadratic across columns colshift = zeros(size(ind)); cx = cim(ind); ax = (cim(indcminus1) + cim(indcplus1))/2 - cx; bx = ax + cx - cim(indcminus1); colshift(ax ~= 0) = -w*bx(ax ~= 0)./(2*ax(ax ~= 0)); % Maxima of quadradic colshift(ax == 0) = 0; rsubp = r+rowshift; % Add subpixel corrections to original row csubp = c+colshift; % and column coords. else rsubp = []; csubp = []; end end if nargin==4 & ~isempty(r) % Overlay corners on supplied image. figure(1), imshow(im,[]), hold on if subPixel plot(csubp,rsubp,'r+'), title('corners detected'); else plot(c,r,'r+'), title('corners detected'); end hold off end if isempty(r) % fprintf('No maxima above threshold found\n'); end
github
jianxiongxiao/ProfXkit-master
ransacfitfundmatrix.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/ransacfitfundmatrix.m
5,544
utf_8
b87d72c56902f27c573b6c545f6754ab
% RANSACFITFUNDMATRIX - fits fundamental matrix using RANSAC % % Usage: [F, inliers] = ransacfitfundmatrix(x1, x2, t) % % Arguments: % x1 - 2xN or 3xN set of homogeneous points. If the data is % 2xN it is assumed the homogeneous scale factor is 1. % x2 - 2xN or 3xN set of homogeneous points such that x1<->x2. % t - The distance threshold between data point and the model % used to decide whether a point is an inlier or not. % Note that point coordinates are normalised to that their % mean distance from the origin is sqrt(2). The value of % t should be set relative to this, say in the range % 0.001 - 0.01 % % Note that it is assumed that the matching of x1 and x2 are putative and it % is expected that a percentage of matches will be wrong. % % Returns: % F - The 3x3 fundamental matrix such that x2'Fx1 = 0. % inliers - An array of indices of the elements of x1, x2 that were % the inliers for the best model. % % See Also: RANSAC, FUNDMATRIX % Copyright (c) 2004-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % February 2004 Original version % August 2005 Distance error function changed to match changes in RANSAC function [F, inliers] = ransacfitfundmatrix(x1, x2, t, feedback) if ~all(size(x1)==size(x2)) error('Data sets x1 and x2 must have the same dimension'); end if nargin == 3 feedback = 0; end [rows,npts] = size(x1); if rows~=2 & rows~=3 error('x1 and x2 must have 2 or 3 rows'); end if rows == 2 % Pad data with homogeneous scale factor of 1 x1 = [x1; ones(1,npts)]; x2 = [x2; ones(1,npts)]; end % Normalise each set of points so that the origin is at centroid and % mean distance from origin is sqrt(2). normalise2dpts also ensures the % scale parameter is 1. Note that 'fundmatrix' will also call % 'normalise2dpts' but the code in 'ransac' that calls the distance % function will not - so it is best that we normalise beforehand. [x1, T1] = normalise2dpts(x1); [x2, T2] = normalise2dpts(x2); s = 8; % Number of points needed to fit a fundamental matrix. Note that % only 7 are needed but the function 'fundmatrix' only % implements the 8-point solution. fittingfn = @fundmatrix; distfn = @funddist; degenfn = @isdegenerate; % x1 and x2 are 'stacked' to create a 6xN array for ransac [F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback); % Now do a final least squares fit on the data points considered to % be inliers. F = fundmatrix(x1(:,inliers), x2(:,inliers)); % Denormalise F = T2'*F*T1; %-------------------------------------------------------------------------- % Function to evaluate the first order approximation of the geometric error % (Sampson distance) of the fit of a fundamental matrix with respect to a % set of matched points as needed by RANSAC. See: Hartley and Zisserman, % 'Multiple View Geometry in Computer Vision', page 270. % % Note that this code allows for F being a cell array of fundamental matrices of % which we have to pick the best one. (A 7 point solution can return up to 3 % solutions) function [bestInliers, bestF] = funddist(F, x, t); x1 = x(1:3,:); % Extract x1 and x2 from x x2 = x(4:6,:); if iscell(F) % We have several solutions each of which must be tested nF = length(F); % Number of solutions to test bestF = F{1}; % Initial allocation of best solution ninliers = 0; % Number of inliers for k = 1:nF x2tFx1 = zeros(1,length(x1)); for n = 1:length(x1) x2tFx1(n) = x2(:,n)'*F{k}*x1(:,n); end Fx1 = F{k}*x1; Ftx2 = F{k}'*x2; % Evaluate distances d = x2tFx1.^2 ./ ... (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2); inliers = find(abs(d) < t); % Indices of inlying points if length(inliers) > ninliers % Record best solution ninliers = length(inliers); bestF = F{k}; bestInliers = inliers; end end else % We just have one solution x2tFx1 = zeros(1,length(x1)); for n = 1:length(x1) x2tFx1(n) = x2(:,n)'*F*x1(:,n); end Fx1 = F*x1; Ftx2 = F'*x2; % Evaluate distances d = x2tFx1.^2 ./ ... (Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2); bestInliers = find(abs(d) < t); % Indices of inlying points bestF = F; % Copy F directly to bestF end %---------------------------------------------------------------------- % (Degenerate!) function to determine if a set of matched points will result % in a degeneracy in the calculation of a fundamental matrix as needed by % RANSAC. This function assumes this cannot happen... function r = isdegenerate(x) r = 0;
github
jianxiongxiao/ProfXkit-master
matrix2quaternion.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/matrix2quaternion.m
2,010
utf_8
ad7a1983aceaa9953be167eddabb22ae
% MATRIX2QUATERNION - Homogeneous matrix to quaternion % % Converts 4x4 homogeneous rotation matrix to quaternion % % Usage: Q = matrix2quaternion(T) % % Argument: T - 4x4 Homogeneous transformation matrix % Returns: Q - a quaternion in the form [w, xi, yj, zk] % % See Also QUATERNION2MATRIX % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function Q = matrix2quaternion(T) % This code follows the implementation suggested by Hartley and Zisserman R = T(1:3, 1:3); % Extract rotation part of T % Find rotation axis as the eigenvector having unit eigenvalue % Solve (R-I)v = 0; [v,d] = eig(R-eye(3)); % The following code assumes the eigenvalues returned are not necessarily % sorted by size. This may be overcautious on my part. d = diag(abs(d)); % Extract eigenvalues [s, ind] = sort(d); % Find index of smallest one if d(ind(1)) > 0.001 % Hopefully it is close to 0 warning('Rotation matrix is dubious'); end axis = v(:,ind(1)); % Extract appropriate eigenvector if abs(norm(axis) - 1) > .0001 % Debug warning('non unit rotation axis'); end % Now determine the rotation angle twocostheta = trace(R)-1; twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]'; twosintheta = axis'*twosinthetav; theta = atan2(twosintheta, twocostheta); Q = [cos(theta/2); axis*sin(theta/2)];
github
jianxiongxiao/ProfXkit-master
harris.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/harris.m
4,707
utf_8
9123c3c21835dfa4d233abe149d6620d
% HARRIS - Harris corner detector % % Usage: cim = harris(im, sigma) % [cim, r, c] = harris(im, sigma, thresh, radius, disp) % [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp) % % Arguments: % im - image to be processed. % sigma - standard deviation of smoothing Gaussian. Typical % values to use might be 1-3. % thresh - threshold (optional). Try a value ~1000. % radius - radius of region considered in non-maximal % suppression (optional). Typical values to use might % be 1-3. % disp - optional flag (0 or 1) indicating whether you want % to display corners overlayed on the original % image. This can be useful for parameter tuning. This % defaults to 0 % % Returns: % cim - binary image marking corners. % r - row coordinates of corner points. % c - column coordinates of corner points. % rsubp - If five return values are requested sub-pixel % csubp - localization of feature points is attempted and % returned as an additional set of floating point % coords. Note that you may still want to use the integer % valued coords to specify centres of correlation windows % for feature matching. % % If thresh and radius are omitted from the argument list only 'cim' is returned % as a raw corner strength image. You may then want to look at the values % within 'cim' to determine the appropriate threshold value to use. Note that % the Harris corner strength varies with the intensity gradient raised to the % 4th power. Small changes in input image contrast result in huge changes in % the appropriate threshold. % % Note that this code computes Noble's version of the detector which does not % require the parameter 'k'. See comments in code if you wish to use Harris' % original measure. % % See also: NONMAXSUPPTS, DERIVATIVE5 % References: % C.G. Harris and M.J. Stephens. "A combined corner and edge detector", % Proceedings Fourth Alvey Vision Conference, Manchester. % pp 147-151, 1988. % % Alison Noble, "Descriptions of Image Surfaces", PhD thesis, Department % of Engineering Science, Oxford University 1989, p45. % Copyright (c) 2002-2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2002 - Original version % December 2002 - Updated comments % August 2005 - Changed so that code calls nonmaxsuppts % August 2010 - Changed to use Farid and Simoncelli's derivative filters function [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp) error(nargchk(2,5,nargin)); if nargin == 4 disp = 0; end if ~isa(im,'double') im = double(im); end subpixel = nargout == 5; % Compute derivatives and elements of the structure tensor. [Ix, Iy] = derivative5(im, 'x', 'y'); Ix2 = gaussfilt(Ix.^2, sigma); Iy2 = gaussfilt(Iy.^2, sigma); Ixy = gaussfilt(Ix.*Iy, sigma); % Compute the Harris corner measure. Note that there are two measures % that can be calculated. I prefer the first one below as given by % Nobel in her thesis (reference above). The second one (commented out) % requires setting a parameter, it is commonly suggested that k=0.04 - I % find this a bit arbitrary and unsatisfactory. cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % My preferred measure. % k = 0.04; % cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; % Original Harris measure. if nargin > 2 % We should perform nonmaximal suppression and threshold if disp % Call nonmaxsuppts to so that image is displayed if subpixel [r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh, im); else [r,c] = nonmaxsuppts(cim, radius, thresh, im); end else % Just do the nonmaximal suppression if subpixel [r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh); else [r,c] = nonmaxsuppts(cim, radius, thresh); end end end
github
jianxiongxiao/ProfXkit-master
hnormalise.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/hnormalise.m
1,010
utf_8
5c1ed3ba361fa6f28b1517af1924af40
% HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1 % % Usage: nx = hnormalise(x) % % Argument: % x - an Nxnpts array of homogeneous coordinates. % % Returns: % nx - an Nxnpts array of homogeneous coordinates rescaled so % that the scale values nx(N,:) are all 1. % % Note that any homogeneous coordinates at infinity (having a scale value of % 0) are left unchanged. % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/~pk % % February 2004 function nx = hnormalise(x) [rows,npts] = size(x); nx = x; % Find the indices of the points that are not at infinity finiteind = find(abs(x(rows,:)) > eps); %if length(finiteind) ~= npts % warning('Some points are at infinity'); %end % Normalise points not at infinity for r = 1:rows-1 nx(r,finiteind) = x(r,finiteind)./x(rows,finiteind); end nx(rows,finiteind) = 1;
github
jianxiongxiao/ProfXkit-master
homography2d.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/homography2d.m
2,493
utf_8
60985e0ab95fe690d769c83adff61080
% HOMOGRAPHY2D - computes 2D homography % % Usage: H = homography2d(x1, x2) % H = homography2d(x) % % Arguments: % x1 - 3xN set of homogeneous points % x2 - 3xN set of homogeneous points such that x1<->x2 % % x - If a single argument is supplied it is assumed that it % is in the form x = [x1; x2] % Returns: % H - the 3x3 homography such that x2 = H*x1 % % This code follows the normalised direct linear transformation % algorithm given by Hartley and Zisserman "Multiple View Geometry in % Computer Vision" p92. % % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % May 2003 - Original version. % Feb 2004 - Single argument allowed for to enable use with RANSAC. % Feb 2005 - SVD changed to 'Economy' decomposition (thanks to Paul O'Leary) function H = homography2d(varargin) [x1, x2] = checkargs(varargin(:)); % Attempt to normalise each set of points so that the origin % is at centroid and mean distance from origin is sqrt(2). [x1, T1] = normalise2dpts(x1); [x2, T2] = normalise2dpts(x2); % Note that it may have not been possible to normalise % the points if one was at infinity so the following does not % assume that scale parameter w = 1. Npts = length(x1); A = zeros(3*Npts,9); O = [0 0 0]; for n = 1:Npts X = x1(:,n)'; x = x2(1,n); y = x2(2,n); w = x2(3,n); A(3*n-2,:) = [ O -w*X y*X]; A(3*n-1,:) = [ w*X O -x*X]; A(3*n ,:) = [-y*X x*X O ]; end [U,D,V] = svd(A,0); % 'Economy' decomposition for speed % Extract homography H = reshape(V(:,9),3,3)'; % Denormalise H = T2\H*T1; %-------------------------------------------------------------------------- % Function to check argument values and set defaults function [x1, x2] = checkargs(arg); if length(arg) == 2 x1 = arg{1}; x2 = arg{2}; if ~all(size(x1)==size(x2)) error('x1 and x2 must have the same size'); elseif size(x1,1) ~= 3 error('x1 and x2 must be 3xN'); end elseif length(arg) == 1 if size(arg{1},1) ~= 6 error('Single argument x must be 6xN'); else x1 = arg{1}(1:3,:); x2 = arg{1}(4:6,:); end else error('Wrong number of arguments supplied'); end
github
jianxiongxiao/ProfXkit-master
iscolinear.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/iscolinear.m
2,318
utf_8
65025b7413f8f6b4cb16dd1689a5900f
% ISCOLINEAR - are 3 points colinear % % Usage: r = iscolinear(p1, p2, p3, flag) % % Arguments: % p1, p2, p3 - Points in 2D or 3D. % flag - An optional parameter set to 'h' or 'homog' % indicating that p1, p2, p3 are homogneeous % coordinates with arbitrary scale. If this is % omitted it is assumed that the points are % inhomogeneous, or that they are homogeneous with % equal scale. % % Returns: % r = 1 if points are co-linear, 0 otherwise % Copyright (c) 2004-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % February 2004 % January 2005 - modified to allow for homogeneous points of arbitrary % scale (thanks to Michael Kirchhof) function r = iscolinear(p1, p2, p3, flag) if nargin == 3 % Assume inhomogeneous coords flag = 'inhomog'; end if ~all(size(p1)==size(p2)) | ~all(size(p1)==size(p3)) | ... ~(length(p1)==2 | length(p1)==3) error('points must have the same dimension of 2 or 3'); end % If data is 2D, assume they are 2D inhomogeneous coords. Make them % homogeneous with scale 1. if length(p1) == 2 p1(3) = 1; p2(3) = 1; p3(3) = 1; end if flag(1) == 'h' % Apply test that allows for homogeneous coords with arbitrary % scale. p1 X p2 generates a normal vector to plane defined by % origin, p1 and p2. If the dot product of this normal with p3 % is zero then p3 also lies in the plane, hence co-linear. r = abs(dot(cross(p1, p2),p3)) < eps; else % Assume inhomogeneous coords, or homogeneous coords with equal % scale. r = norm(cross(p2-p1, p3-p1)) < eps; end
github
jianxiongxiao/ProfXkit-master
monofilt.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/monofilt.m
6,435
utf_8
07ef46eb32d19a4d79e9ec304c6cb2d3
% MONOFILT - Apply monogenic filters to an image to obtain 2D analytic signal % % Implementation of Felsberg's monogenic filters % % Usage: [f, h1f, h2f, A, theta, psi] = ... % monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap) % 3 4 2 0.65 1/0 % Arguments: % The convolutions are done via the FFT. Many of the parameters relate % to the specification of the filters in the frequency plane. % % Variable Suggested Description % name value % ---------------------------------------------------------- % im Image to be convolved. % nscale = 3; Number of filter scales. % minWaveLength = 4; Wavelength of smallest scale filter. % mult = 2; Scaling factor between successive filters. % sigmaOnf = 0.65; Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's % transfer function in the frequency domain % to the filter center frequency. % orientWrap 1/0 Optional flag 1/0 to turn on/off % 'wrapping' of orientation data from a % range of -pi .. pi to the range 0 .. pi. % This affects the interpretation of the % phase angle - see note below. Defaults to 0. % Returns: % % f - cell array of bandpass filter responses with respect to scale. % h1f - cell array of bandpass h1 filter responses wrt scale. % h2f - cell array of bandpass h2 filter responses. % A - cell array of monogenic energy responses. % theta - cell array of phase orientation responses. % psi - cell array of phase angle responses. % % If orientWrap is 1 (on) theta will be returned in the range 0 .. pi and % psi (the phase angle) will be returned in the range -pi .. pi. If % orientWrap is 0 theta will be returned in the range -pi .. pi and psi will % be returned in the range -pi/2 .. pi/2. Try both options on an image of a % circle to see what this means! % % Experimentation with sigmaOnf can be useful depending on your application. % I have found values as low as 0.2 (a filter with a *very* large bandwidth) % to be useful on some occasions. % % See also: GABORCONVOLVE % References: % Michael Felsberg and Gerald Sommer. "A New Extension of Linear Signal % Processing for Estimating Local Properties and Detecting Features" % DAGM Symposium 2000, Kiel % % Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE % Transactions on Signal Processing, 49(12):3136-3144, December 2001 % Copyright (c) 2004-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2004 - Original version. % May 2005 - Orientation wrapping and code cleaned up. % August 2005 - Phase calculation improved. function [f, h1f, h2f, A, theta, psi] = ... monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap) if nargin == 5 orientWrap = 0; % Default is no orientation wrapping end if nargout > 4 thetaPhase = 1; % Calculate orientation and phase else thetaPhase = 0; % Only return filter outputs end [rows,cols] = size(im); IM = fft2(double(im)); % Generate horizontal and vertical frequency grids that vary from % -0.5 to 0.5 [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ... ([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2))); u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners u2 = ifftshift(u2); radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency % values as a radius from centre % (but quadrant shifted) % Get rid of the 0 radius value in the middle (at top left corner after % fftshifting) so that taking the log of the radius, or dividing by the % radius, will not cause trouble. radius(1,1) = 1; H1 = i*u1./radius; % The two monogenic filters in the frequency domain H2 = i*u2./radius; % The two monogenic filters H1 and H2 are oriented in frequency space % but are not selective in terms of the magnitudes of the % frequencies. The code below generates bandpass log-Gabor filters % which are point-wise multiplied by H1 and H2 to produce different % bandpass versions of H1 and H2 for s = 1:nscale wavelength = minWaveLength*mult^(s-1); fo = 1.0/wavelength; % Centre frequency of filter. logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(1,1) = 0; % undo the radius fudge. % Generate bandpass versions of H1 and H2 at this scale H1s = H1.*logGabor; H2s = H2.*logGabor; % Apply filters to image in the frequency domain and get spatial % results f{s} = real(ifft2(IM.*logGabor)); h1f{s} = real(ifft2(IM.*H1s)); h2f{s} = real(ifft2(IM.*H2s)); A{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2); % Magnitude of Energy. % If requested calculate the orientation and phase angles if thetaPhase theta{s} = atan2(h2f{s}, h1f{s}); % Orientation. % Here phase is measured relative to the h1f-h2f plane as an % 'elevation' angle that ranges over +- pi/2 psi{s} = atan2(f{s}, sqrt(h1f{s}.^2 + h2f{s}.^2)); if orientWrap % Wrap orientation values back into the range 0-pi negind = find(theta{s}<0); theta{s}(negind) = theta{s}(negind) + pi; % Where orientation values have been wrapped we should % adjust phase accordingly **check** psi{s}(negind) = pi-psi{s}(negind); morethanpi = find(psi{s}>pi); psi{s}(morethanpi) = psi{s}(morethanpi)-2*pi; end end end
github
jianxiongxiao/ProfXkit-master
ransacfithomography.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/ransacfithomography.m
4,920
utf_8
d479d49f7c8e8689283005bcbe340b61
% RANSACFITHOMOGRAPHY - fits 2D homography using RANSAC % % Usage: [H, inliers] = ransacfithomography(x1, x2, t) % % Arguments: % x1 - 2xN or 3xN set of homogeneous points. If the data is % 2xN it is assumed the homogeneous scale factor is 1. % x2 - 2xN or 3xN set of homogeneous points such that x1<->x2. % t - The distance threshold between data point and the model % used to decide whether a point is an inlier or not. % Note that point coordinates are normalised to that their % mean distance from the origin is sqrt(2). The value of % t should be set relative to this, say in the range % 0.001 - 0.01 % % Note that it is assumed that the matching of x1 and x2 are putative and it % is expected that a percentage of matches will be wrong. % % Returns: % H - The 3x3 homography such that x2 = H*x1. % inliers - An array of indices of the elements of x1, x2 that were % the inliers for the best model. % % See Also: ransac, homography2d, homography1d % Copyright (c) 2004-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % February 2004 - original version % July 2004 - error in denormalising corrected (thanks to Andrew Stein) % August 2005 - homogdist2d modified to fit new ransac specification. function [H, inliers] = ransacfithomography(x1, x2, t) if ~all(size(x1)==size(x2)) error('Data sets x1 and x2 must have the same dimension'); end [rows,npts] = size(x1); if rows~=2 & rows~=3 error('x1 and x2 must have 2 or 3 rows'); end if npts < 4 error('Must have at least 4 points to fit homography'); end if rows == 2 % Pad data with homogeneous scale factor of 1 x1 = [x1; ones(1,npts)]; x2 = [x2; ones(1,npts)]; end % Normalise each set of points so that the origin is at centroid and % mean distance from origin is sqrt(2). normalise2dpts also ensures the % scale parameter is 1. Note that 'homography2d' will also call % 'normalise2dpts' but the code in 'ransac' that calls the distance % function will not - so it is best that we normalise beforehand. [x1, T1] = normalise2dpts(x1); [x2, T2] = normalise2dpts(x2); s = 4; % Minimum No of points needed to fit a homography. fittingfn = @homography2d; distfn = @homogdist2d; degenfn = @isdegenerate; % x1 and x2 are 'stacked' to create a 6xN array for ransac [H, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t); % Now do a final least squares fit on the data points considered to % be inliers. H = homography2d(x1(:,inliers), x2(:,inliers)); % Denormalise H = T2\H*T1; %---------------------------------------------------------------------- % Function to evaluate the symmetric transfer error of a homography with % respect to a set of matched points as needed by RANSAC. function [inliers, H] = homogdist2d(H, x, t); x1 = x(1:3,:); % Extract x1 and x2 from x x2 = x(4:6,:); % Calculate, in both directions, the transfered points Hx1 = H*x1; invHx2 = H\x2; % Normalise so that the homogeneous scale parameter for all coordinates % is 1. x1 = hnormalise(x1); x2 = hnormalise(x2); Hx1 = hnormalise(Hx1); invHx2 = hnormalise(invHx2); d2 = sum((x1-invHx2).^2) + sum((x2-Hx1).^2); inliers = find(abs(d2) < t); %---------------------------------------------------------------------- % Function to determine if a set of 4 pairs of matched points give rise % to a degeneracy in the calculation of a homography as needed by RANSAC. % This involves testing whether any 3 of the 4 points in each set is % colinear. function r = isdegenerate(x) x1 = x(1:3,:); % Extract x1 and x2 from x x2 = x(4:6,:); r = ... iscolinear(x1(:,1),x1(:,2),x1(:,3)) | ... iscolinear(x1(:,1),x1(:,2),x1(:,4)) | ... iscolinear(x1(:,1),x1(:,3),x1(:,4)) | ... iscolinear(x1(:,2),x1(:,3),x1(:,4)) | ... iscolinear(x2(:,1),x2(:,2),x2(:,3)) | ... iscolinear(x2(:,1),x2(:,2),x2(:,4)) | ... iscolinear(x2(:,1),x2(:,3),x2(:,4)) | ... iscolinear(x2(:,2),x2(:,3),x2(:,4));
github
jianxiongxiao/ProfXkit-master
fundmatrix.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/fundmatrix.m
3,961
utf_8
250dfa8051640daab30229f35667f4d6
% FUNDMATRIX - computes fundamental matrix from 8 or more points % % Function computes the fundamental matrix from 8 or more matching points in % a stereo pair of images. The normalised 8 point algorithm given by % Hartley and Zisserman p265 is used. To achieve accurate results it is % recommended that 12 or more points are used % % Usage: [F, e1, e2] = fundmatrix(x1, x2) % [F, e1, e2] = fundmatrix(x) % % Arguments: % x1, x2 - Two sets of corresponding 3xN set of homogeneous % points. % % x - If a single argument is supplied it is assumed that it % is in the form x = [x1; x2] % Returns: % F - The 3x3 fundamental matrix such that x2'*F*x1 = 0. % e1 - The epipole in image 1 such that F*e1 = 0 % e2 - The epipole in image 2 such that F'*e2 = 0 % % Copyright (c) 2002-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % Feb 2002 - Original version. % May 2003 - Tidied up and numerically improved. % Feb 2004 - Single argument allowed to enable use with RANSAC. % Mar 2005 - Epipole calculation added, 'economy' SVD used. % Aug 2005 - Octave compatibility function [F,e1,e2] = fundmatrix(varargin) [x1, x2, npts] = checkargs(varargin(:)); Octave = exist('OCTAVE_VERSION') ~= 0; % Are we running under Octave? % Normalise each set of points so that the origin % is at centroid and mean distance from origin is sqrt(2). % normalise2dpts also ensures the scale parameter is 1. [x1, T1] = normalise2dpts(x1); [x2, T2] = normalise2dpts(x2); % Build the constraint matrix A = [x2(1,:)'.*x1(1,:)' x2(1,:)'.*x1(2,:)' x2(1,:)' ... x2(2,:)'.*x1(1,:)' x2(2,:)'.*x1(2,:)' x2(2,:)' ... x1(1,:)' x1(2,:)' ones(npts,1) ]; if Octave [U,D,V] = svd(A); % Don't seem to be able to use the economy % decomposition under Octave here else [U,D,V] = svd(A,0); % Under MATLAB use the economy decomposition end % Extract fundamental matrix from the column of V corresponding to % smallest singular value. F = reshape(V(:,9),3,3)'; % Enforce constraint that fundamental matrix has rank 2 by performing % a svd and then reconstructing with the two largest singular values. [U,D,V] = svd(F,0); F = U*diag([D(1,1) D(2,2) 0])*V'; % Denormalise F = T2'*F*T1; if nargout == 3 % Solve for epipoles [U,D,V] = svd(F,0); e1 = hnormalise(V(:,3)); e2 = hnormalise(U(:,3)); end %-------------------------------------------------------------------------- % Function to check argument values and set defaults function [x1, x2, npts] = checkargs(arg); if length(arg) == 2 x1 = arg{1}; x2 = arg{2}; if ~all(size(x1)==size(x2)) error('x1 and x2 must have the same size'); elseif size(x1,1) ~= 3 error('x1 and x2 must be 3xN'); end elseif length(arg) == 1 if size(arg{1},1) ~= 6 error('Single argument x must be 6xN'); else x1 = arg{1}(1:3,:); x2 = arg{1}(4:6,:); end else error('Wrong number of arguments supplied'); end npts = size(x1,2); if npts < 8 error('At least 8 points are needed to compute the fundamental matrix'); end
github
jianxiongxiao/ProfXkit-master
hline.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/hline.m
1,584
utf_8
7887599478d2ebb7e50fdef565f8f3f5
% HLINE - Plot 2D lines defined in homogeneous coordinates. % % Function for ploting 2D homogeneous lines defined by 2 points % or a line defined by a single homogeneous vector % % Usage: hline(p1,p2) where p1 and p2 are 2D homogeneous points. % hline(p1,p2,'colour_name') 'black' 'red' 'white' etc % hline(l) where l is a line in homogeneous coordinates % hline(l,'colour_name') % % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk @ csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % April 2000 function hline(a,b,c) col = 'blue'; % default colour if nargin >= 2 & isa(a,'double') & isa(b,'double') % Two points specified p1 = a./a(3); % make sure homogeneous points lie in z=1 plane p2 = b./b(3); if nargin == 3 & isa(c,'char') % 2 points and a colour specified col = c; end elseif nargin >= 1 & isa(a,'double') % A single line specified a = a./a(3); % ensure line in z = 1 plane (not needed??) if abs(a(1)) > abs(a(2)) % line is more vertical ylim = get(get(gcf,'CurrentAxes'),'Ylim'); p1 = hcross(a, [0 1 0]'); p2 = hcross(a, [0 -1/ylim(2) 1]'); else % line more horizontal xlim = get(get(gcf,'CurrentAxes'),'Xlim'); p1 = hcross(a, [1 0 0]'); p2 = hcross(a, [-1/xlim(2) 0 1]'); end if nargin == 2 & isa(b,'char') % 1 line vector and a colour specified col = b; end else error('Bad arguments passed to hline'); end line([p1(1) p2(1)], [p1(2) p2(2)], 'color', col);
github
jianxiongxiao/ProfXkit-master
ransac.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/ransac.m
9,584
utf_8
a009148eda9992679a2d30a901282f54
% RANSAC - Robustly fits a model to data with the RANSAC algorithm % % Usage: % % [M, inliers] = ransac(x, fittingfn, distfn, degenfn s, t, feedback, ... % maxDataTrials, maxTrials) % % Arguments: % x - Data sets to which we are seeking to fit a model M % It is assumed that x is of size [d x Npts] % where d is the dimensionality of the data and Npts is % the number of data points. % % fittingfn - Handle to a function that fits a model to s % data from x. It is assumed that the function is of the % form: % M = fittingfn(x) % Note it is possible that the fitting function can return % multiple models (for example up to 3 fundamental matrices % can be fitted to 7 matched points). In this case it is % assumed that the fitting function returns a cell array of % models. % If this function cannot fit a model it should return M as % an empty matrix. % % distfn - Handle to a function that evaluates the % distances from the model to data x. % It is assumed that the function is of the form: % [inliers, M] = distfn(M, x, t) % This function must evaluate the distances between points % and the model returning the indices of elements in x that % are inliers, that is, the points that are within distance % 't' of the model. Additionally, if M is a cell array of % possible models 'distfn' will return the model that has the % most inliers. If there is only one model this function % must still copy the model to the output. After this call M % will be a non-cell object representing only one model. % % degenfn - Handle to a function that determines whether a % set of datapoints will produce a degenerate model. % This is used to discard random samples that do not % result in useful models. % It is assumed that degenfn is a boolean function of % the form: % r = degenfn(x) % It may be that you cannot devise a test for degeneracy in % which case you should write a dummy function that always % returns a value of 1 (true) and rely on 'fittingfn' to return % an empty model should the data set be degenerate. % % s - The minimum number of samples from x required by % fittingfn to fit a model. % % t - The distance threshold between a data point and the model % used to decide whether the point is an inlier or not. % % feedback - An optional flag 0/1. If set to one the trial count and the % estimated total number of trials required is printed out at % each step. Defaults to 0. % % maxDataTrials - Maximum number of attempts to select a non-degenerate % data set. This parameter is optional and defaults to 100. % % maxTrials - Maximum number of iterations. This parameter is optional and % defaults to 1000. % % Returns: % M - The model having the greatest number of inliers. % inliers - An array of indices of the elements of x that were % the inliers for the best model. % % For an example of the use of this function see RANSACFITHOMOGRAPHY or % RANSACFITPLANE % References: % M.A. Fishler and R.C. Boles. "Random sample concensus: A paradigm % for model fitting with applications to image analysis and automated % cartography". Comm. Assoc. Comp, Mach., Vol 24, No 6, pp 381-395, 1981 % % Richard Hartley and Andrew Zisserman. "Multiple View Geometry in % Computer Vision". pp 101-113. Cambridge University Press, 2001 % Copyright (c) 2003-2006 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % May 2003 - Original version % February 2004 - Tidied up. % August 2005 - Specification of distfn changed to allow model fitter to % return multiple models from which the best must be selected % Sept 2006 - Random selection of data points changed to ensure duplicate % points are not selected. % February 2007 - Jordi Ferrer: Arranged warning printout. % Allow maximum trials as optional parameters. % Patch the problem when non-generated data % set is not given in the first iteration. % August 2008 - 'feedback' parameter restored to argument list and other % breaks in code introduced in last update fixed. % December 2008 - Octave compatibility mods % June 2009 - Argument 'MaxTrials' corrected to 'maxTrials'! function [M, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback, ... maxDataTrials, maxTrials) Octave = exist('OCTAVE_VERSION') ~= 0; % Test number of parameters error ( nargchk ( 6, 9, nargin ) ); if nargin < 9; maxTrials = 50000; end; if nargin < 8; maxDataTrials = 1000; end; if nargin < 7; feedback = 0; end; [rows, npts] = size(x); p = 0.99; % Desired probability of choosing at least one sample % free from outliers bestM = NaN; % Sentinel value allowing detection of solution failure. trialcount = 0; bestscore = 0; N = 1; % Dummy initialisation for number of trials. % for debugging, we fix the set stream = RandStream.getGlobalStream; reset(stream); while N > trialcount % Select at random s datapoints to form a trial model, M. % In selecting these points we have to check that they are not in % a degenerate configuration. degenerate = 1; count = 1; while degenerate % Generate s random indicies in the range 1..npts % (If you do not have the statistics toolbox, or are using Octave, % use the function RANDOMSAMPLE from my webpage) if Octave | ~exist('randsample.m') ind = randomsample(npts, s); else ind = randsample(npts, s); end % Test that these points are not a degenerate configuration. degenerate = feval(degenfn, x(:,ind)); if ~degenerate % Fit model to this random selection of data points. % Note that M may represent a set of models that fit the data in % this case M will be a cell array of models M = feval(fittingfn, x(:,ind)); % Depending on your problem it might be that the only way you % can determine whether a data set is degenerate or not is to % try to fit a model and see if it succeeds. If it fails we % reset degenerate to true. if isempty(M) degenerate = 1; end end % Safeguard against being stuck in this loop forever count = count + 1; if count > maxDataTrials warning('Unable to select a nondegenerate data set'); break end end % Once we are out here we should have some kind of model... % Evaluate distances between points and model returning the indices % of elements in x that are inliers. Additionally, if M is a cell % array of possible models 'distfn' will return the model that has % the most inliers. After this call M will be a non-cell object % representing only one model. [inliers, M] = feval(distfn, M, x, t); % Find the number of inliers to this model. ninliers = length(inliers); % Jianxiong: I change it from > to >= if ninliers >= bestscore % Largest set of inliers so far... bestscore = ninliers; % Record data for this model bestinliers = inliers; bestM = M; % Update estimate of N, the number of trials to ensure we pick, % with probability p, a data set with no outliers. fracinliers = ninliers/npts; pNoOutliers = 1 - fracinliers^s; pNoOutliers = max(eps, pNoOutliers); % Avoid division by -Inf pNoOutliers = min(1-eps, pNoOutliers);% Avoid division by 0. N = log(1-p)/log(pNoOutliers); N = max(N,500); % at least try 50 times end trialcount = trialcount+1; if feedback fprintf('trial %d out of %d \r',trialcount, ceil(N)); end % Safeguard against being stuck in this loop forever if trialcount > maxTrials warning( ... sprintf('ransac reached the maximum number of %d trials',... maxTrials)); break end end %fprintf('\n'); if ~isnan(bestM) % We got a solution M = bestM; inliers = bestinliers; else M = []; inliers = []; error('ransac was unable to find a useful solution'); end
github
jianxiongxiao/ProfXkit-master
gaussfilt.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/gaussfilt.m
892
utf_8
266e718eee73f61a8bc07650565a1692
% GAUSSFILT - Small wrapper function for convenient Gaussian filtering % % Usage: smim = gaussfilt(im, sigma) % % Arguments: im - Image to be smoothed. % sigma - Standard deviation of Gaussian filter. % % Returns: smim - Smoothed image. % % See also: INTEGGAUSSFILT % Peter Kovesi % Centre for Explortion Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % March 2010 function smim = gaussfilt(im, sigma) assert(ndims(im) == 2, 'Image must be greyscale'); % If needed convert im to double if ~strcmp(class(im),'double') im = double(im); end sze = ceil(6*sigma); if ~mod(sze,2) % Ensure filter size is odd sze = sze+1; end sze = max(sze,1); % and make sure it is at least 1 h = fspecial('gaussian', [sze sze], sigma); smim = filter2(h, im);
github
jianxiongxiao/ProfXkit-master
derivative5.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/derivative5.m
4,808
utf_8
989b39a3f681a8cad7375573fa1a7a0f
% DERIVATIVE5 - 5-Tap 1st and 2nd discrete derivatives % % This function computes 1st and 2nd derivatives of an image using the 5-tap % coefficients given by Farid and Simoncelli. The results are significantly % more accurate than MATLAB's GRADIENT function on edges that are at angles % other than vertical or horizontal. This in turn improves gradient orientation % estimation enormously. If you are after extreme accuracy try using DERIVATIVE7. % % Usage: [gx, gy, gxx, gyy, gxy] = derivative5(im, derivative specifiers) % % Arguments: % im - Image to compute derivatives from. % derivative specifiers - A comma separated list of character strings % that can be any of 'x', 'y', 'xx', 'yy' or 'xy' % These can be in any order, the order of the % computed output arguments will match the order % of the derivative specifier strings. % Returns: % Function returns requested derivatives which can be: % gx, gy - 1st derivative in x and y % gxx, gyy - 2nd derivative in x and y % gxy - 1st derivative in y of 1st derivative in x % % Examples: % Just compute 1st derivatives in x and y % [gx, gy] = derivative5(im, 'x', 'y'); % % Compute 2nd derivative in x, 1st derivative in y and 2nd derivative in y % [gxx, gy, gyy] = derivative5(im, 'xx', 'y', 'yy') % % See also: DERIVATIVE7 % Reference: Hany Farid and Eero Simoncelli "Differentiation of Discrete % Multi-Dimensional Signals" IEEE Trans. Image Processing. 13(4): 496-508 (2004) % Copyright (c) 2010 Peter Kovesi % Centre for Exploration Targeting % The University of Western Australia % http://www.csse.uwa.edu.au/~pk/research/matlabfns/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % % April 2010 function varargout = derivative5(im, varargin) varargin = varargin(:); varargout = cell(size(varargin)); % Check if we are just computing 1st derivatives. If so use the % interpolant and derivative filters optimized for 1st derivatives, else % use 2nd derivative filters and interpolant coefficients. % Detection is done by seeing if any of the derivative specifier % arguments is longer than 1 char, this implies 2nd derivative needed. secondDeriv = false; for n = 1:length(varargin) if length(varargin{n}) > 1 secondDeriv = true; break end end if ~secondDeriv % 5 tap 1st derivative cofficients. These are optimal if you are just % seeking the 1st deriavtives p = [0.037659 0.249153 0.426375 0.249153 0.037659]; d1 =[0.109604 0.276691 0.000000 -0.276691 -0.109604]; else % 5-tap 2nd derivative coefficients. The associated 1st derivative % coefficients are not quite as optimal as the ones above but are % consistent with the 2nd derivative interpolator p and thus are % appropriate to use if you are after both 1st and 2nd derivatives. p = [0.030320 0.249724 0.439911 0.249724 0.030320]; d1 = [0.104550 0.292315 0.000000 -0.292315 -0.104550]; d2 = [0.232905 0.002668 -0.471147 0.002668 0.232905]; end % Compute derivatives. Note that in the 1st call below MATLAB's conv2 % function performs a 1D convolution down the columns using p then a 1D % convolution along the rows using d1. etc etc. gx = false; for n = 1:length(varargin) if strcmpi('x', varargin{n}) varargout{n} = conv2(p, d1, im, 'same'); gx = true; % Record that gx is available for gxy if needed gxn = n; elseif strcmpi('y', varargin{n}) varargout{n} = conv2(d1, p, im, 'same'); elseif strcmpi('xx', varargin{n}) varargout{n} = conv2(p, d2, im, 'same'); elseif strcmpi('yy', varargin{n}) varargout{n} = conv2(d2, p, im, 'same'); elseif strcmpi('xy', varargin{n}) | strcmpi('yx', varargin{n}) if gx varargout{n} = conv2(d1, p, varargout{gxn}, 'same'); else gx = conv2(p, d1, im, 'same'); varargout{n} = conv2(d1, p, gx, 'same'); end else error(sprintf('''%s'' is an unrecognized derivative option',varargin{n})); end end
github
jianxiongxiao/ProfXkit-master
quaternion2matrix.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/quaternion2matrix.m
1,413
utf_8
7296cadf62f6ca9273e726ffd7e19d95
% QUATERNION2MATRIX - Quaternion to a 4x4 homogeneous transformation matrix % % Usage: T = quaternion2matrix(Q) % % Argument: Q - a quaternion in the form [w xi yj zk] % Returns: T - 4x4 Homogeneous rotation matrix % % See also MATRIX2QUATERNION, NEWQUATERNION, QUATERNIONROTATE % Copyright (c) 2008 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. function T = quaternion2matrix(Q) Q = Q/norm(Q); % Ensure Q has unit norm % Set up convenience variables w = Q(1); x = Q(2); y = Q(3); z = Q(4); w2 = w^2; x2 = x^2; y2 = y^2; z2 = z^2; xy = x*y; xz = x*z; yz = y*z; wx = w*x; wy = w*y; wz = w*z; T = [w2+x2-y2-z2 , 2*(xy - wz) , 2*(wy + xz) , 0 2*(wz + xy) , w2-x2+y2-z2 , 2*(yz - wx) , 0 2*(xz - wy) , 2*(wx + yz) , w2-x2-y2+z2 , 0 0 , 0 , 0 , 1];
github
jianxiongxiao/ProfXkit-master
matchbymonogenicphase.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/matchbymonogenicphase.m
9,328
utf_8
e63225faedcf391fb6411d27d71a208e
% MATCHBYMONOGENICPHASE - match image feature points using monogenic phase data % % Function generates putative matches between previously detected % feature points in two images by looking for points that have minimal % differences in monogenic phase data within windows surrounding each point. % Only points that correlate most strongly with each other in *both* % directions are returned. This is a simple-minded N^2 comparison. % % This matcher performs rather well relative to normalised greyscale % correlation. Typically there are more putative matches found and fewer % outliers. There is a greater computational cost in the pre-filtering stage % but potentially the matching stage is much faster as each pixel is effectively % encoded with only 3 bits. (Though this potential speed is not realized in this % implementation) % % Usage: [m1,m2] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ... % nscale, minWaveLength, mult, sigmaOnf) % % Arguments: % im1, im2 - Images containing points that we wish to match. % p1, p2 - Coordinates of feature pointed detected in im1 and % im2 respectively using a corner detector (say Harris % or phasecong2). p1 and p2 are [2xnpts] arrays though % p1 and p2 are not expected to have the same number % of points. The first row of p1 and p2 gives the row % coordinate of each feature point, the second row % gives the column of each point. % w - Window size (in pixels) over which the phase bit codes % around each feature point are matched. This should % be an odd number. % dmax - Maximum search radius for matching points. Used to % improve speed when there is little disparity between % images. Even setting it to a generous value of 1/4 of % the image size gives a useful speedup. % nscale - Number of filter scales. % minWaveLength - Wavelength of smallest scale filter. % mult - Scaling factor between successive filters. % sigmaOnf - Ratio of the standard deviation of the Gaussian % describing the log Gabor filter's transfer function in % the frequency domain to the filter center frequency. % % % Returns: % m1, m2 - Coordinates of points selected from p1 and p2 % respectively such that (putatively) m1(:,i) matches % m2(:,i). m1 and m2 are [2xnpts] arrays defining the % points in each of the images in the form [row;col]. % % % I have had good success with the folowing parameters: % % w = 11; Window size for correlation matching, 7 or greater % seems fine. % dmax = 50; % nscale = 1; Just one scale can give very good results. Adding % another scale doubles computation % minWaveLength = 10; % mult = 4; This is irrelevant if only one scale is used. If you do % use more than one scale try values in the range 2-4. % sigmaOnf = .2; This results in a *very* large bandwidth filter. A % large bandwidth seems to be very important in the % matching performance. % % See Also: MATCHBYCORRELATION, MONOFILT % Copyright (c) 2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % May 2005 - Original version adapted from matchbycorrelation.m function [m1,m2,cormat] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ... nscale, minWaveLength, mult, sigmaOnf) orientWrap = 0; [f1, h1f1, h2f1, A1] = ... monofilt(im1, nscale, minWaveLength, mult, sigmaOnf, orientWrap); [f2, h1f2, h2f2, A2] = ... monofilt(im2, nscale, minWaveLength, mult, sigmaOnf, orientWrap); % Normalise filter outputs to unit vectors (should also have masking for % unreliable filter outputs) for s = 1:nscale % f1{s} = f1{s}./A1{s}; f2{s} = f2{s}./A2{s}; % h1f1{s} = h1f1{s}./A1{s}; h1f2{s} = h1f2{s}./A2{s}; % h2f1{s} = h2f1{s}./A1{s}; h2f2{s} = h2f2{s}./A2{s}; % Try quantizing oriented phase vector to 8 octants to see what % effect this has (Performance seems to be reduced only slightly) f1{s} = sign(f1{s}); f2{s} = sign(f2{s}); h1f1{s} = sign(h1f1{s}); h1f2{s} = sign(h1f2{s}); h2f1{s} = sign(h2f1{s}); h2f2{s} = sign(h2f2{s}); end % Generate correlation matrix cormat = correlationmatrix(f1, h1f1, h2f1, p1, ... f2, h1f2, h2f2, p2, w, dmax); [corrows,corcols] = size(cormat); % Find max along rows give strongest match in p2 for each p1 [mp2forp1, colp2forp1] = max(cormat,[],2); % Find max down cols give strongest match in p1 for each p2 [mp1forp2, rowp1forp2] = max(cormat,[],1); % Now find matches that were consistent in both directions p1ind = zeros(1,length(p1)); % Arrays for storing matched indices p2ind = zeros(1,length(p2)); indcount = 0; for n = 1:corrows if rowp1forp2(colp2forp1(n)) == n % consistent both ways indcount = indcount + 1; p1ind(indcount) = n; p2ind(indcount) = colp2forp1(n); end end % Trim arrays of indices of matched points p1ind = p1ind(1:indcount); p2ind = p2ind(1:indcount); % Extract matched points from original arrays m1 = p1(:,p1ind); m2 = p2(:,p2ind); %------------------------------------------------------------------------- % Function that does the work. This function builds a 'correlation' matrix % that holds the correlation strength of every point relative to every other % point. While this seems a bit wasteful we need all this data if we want % to find pairs of points that correlate maximally in both directions. function cormat = correlationmatrix(f1, h1f1, h2f1, p1, ... f2, h1f2, h2f2, p2, w, dmax) if mod(w, 2) == 0 | w < 3 error('Window size should be odd and >= 3'); end r = (w-1)/2; % 'radius' of correlation window [rows1, npts1] = size(p1); [rows2, npts2] = size(p2); if rows1 ~= 2 | rows2 ~= 2 error('Feature points must be specified in 2xN arrays'); end % Reorganize monogenic phase data into a 4D matrices for convenience [im1rows,im1cols] = size(f1{1}); [im2rows,im2cols] = size(f2{1}); nscale = length(f1); phase1 = zeros(im1rows,im1cols,nscale,3); phase2 = zeros(im2rows,im2cols,nscale,3); for s = 1:nscale phase1(:,:,s,1) = f1{s}; phase1(:,:,s,2) = h1f1{s}; phase1(:,:,s,3) = h2f1{s}; phase2(:,:,s,1) = f2{s}; phase2(:,:,s,2) = h1f2{s}; phase2(:,:,s,3) = h2f2{s}; end % Initialize correlation matrix values to -infinity cormat = repmat(-inf, npts1, npts2); % For every feature point in the first image extract a window of data % and correlate with a window corresponding to every feature point in % the other image. Any feature point less than distance 'r' from the % boundary of an image is not considered. % Find indices of points that are distance 'r' or greater from % boundary on image1 and image2; n1ind = find(p1(1,:)>r & p1(1,:)<im1rows+1-r & ... p1(2,:)>r & p1(2,:)<im1cols+1-r); n2ind = find(p2(1,:)>r & p2(1,:)<im2rows+1-r & ... p2(2,:)>r & p2(2,:)<im2cols+1-r); for n1 = n1ind % Identify the indices of points in p2 that we need to consider. if dmax == inf n2indmod = n2ind; % We have to consider all of n2ind else % Compute distances from p1(:,n1) to all available p2. p1pad = repmat(p1(:,n1),1,length(n2ind)); dists2 = sum((p1pad-p2(:,n2ind)).^2); % Find indices of points in p2 that are within distance dmax of % p1(:,n1) n2indmod = n2ind(find(dists2 < dmax^2)); end % Generate window in 1st image w1 = phase1(p1(1,n1)-r:p1(1,n1)+r, p1(2,n1)-r:p1(2,n1)+r, :, :); for n2 = n2indmod % Generate window in 2nd image w2 = phase2(p2(1,n2)-r:p2(1,n2)+r, p2(2,n2)-r:p2(2,n2)+r, :, :); % Compute dot product as correlation measure cormat(n1,n2) = w1(:)'*w2(:); % *** Need to add mask stuff end end
github
jianxiongxiao/ProfXkit-master
normalise2dpts.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/normalise2dpts.m
2,361
utf_8
2b9d94a3681186006a3fd47a45faf939
% NORMALISE2DPTS - normalises 2D homogeneous points % % Function translates and normalises a set of 2D homogeneous points % so that their centroid is at the origin and their mean distance from % the origin is sqrt(2). This process typically improves the % conditioning of any equations used to solve homographies, fundamental % matrices etc. % % Usage: [newpts, T] = normalise2dpts(pts) % % Argument: % pts - 3xN array of 2D homogeneous coordinates % % Returns: % newpts - 3xN array of transformed 2D homogeneous coordinates. The % scaling parameter is normalised to 1 unless the point is at % infinity. % T - The 3x3 transformation matrix, newpts = T*pts % % If there are some points at infinity the normalisation transform % is calculated using just the finite points. Being a scaling and % translating transform this will not affect the points at infinity. % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % May 2003 - Original version % February 2004 - Modified to deal with points at infinity. % December 2008 - meandist calculation modified to work with Octave 3.0.1 % (thanks to Ron Parr) function [newpts, T] = normalise2dpts(pts) if size(pts,1) ~= 3 error('pts must be 3xN'); end % Find the indices of the points that are not at infinity finiteind = find(abs(pts(3,:)) > eps); if length(finiteind) ~= size(pts,2) warning('Some points are at infinity'); end % For the finite points ensure homogeneous coords have scale of 1 pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind); pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind); pts(3,finiteind) = 1; c = mean(pts(1:2,finiteind)')'; % Centroid of finite points newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid. newp(2,finiteind) = pts(2,finiteind)-c(2); dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2); meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1 scale = sqrt(2)/meandist; T = [scale 0 -scale*c(1) 0 scale -scale*c(2) 0 0 1 ]; newpts = T*pts;
github
jianxiongxiao/ProfXkit-master
hcross.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/hcross.m
919
utf_8
dbb3f3d4ef79e25ca3000ea976409e0c
% HCROSS - Homogeneous cross product, result normalised to s = 1. % % Function to form cross product between two points, or lines, % in homogeneous coodinates. The result is normalised to lie % in the scale = 1 plane. % % Usage: c = hcross(a,b) % % Copyright (c) 2000-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % April 2000 function c = hcross(a,b) c = cross(a,b); c = c/c(3);
github
jianxiongxiao/ProfXkit-master
matchbycorrelation.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/peter/matchbycorrelation.m
7,076
utf_8
12d7e8d4ad6e140c94444ddc3682d518
% MATCHBYCORRELATION - match image feature points by correlation % % Function generates putative matches between previously detected % feature points in two images by looking for points that are maximally % correlated with each other within windows surrounding each point. % Only points that correlate most strongly with each other in *both* % directions are returned. % This is a simple-minded N^2 comparison. % % Usage: [m1, m2, p1ind, p2ind, cormat] = ... % matchbycorrelation(im1, p1, im2, p2, w, dmax) % % Arguments: % im1, im2 - Images containing points that we wish to match. % p1, p2 - Coordinates of feature pointed detected in im1 and % im2 respectively using a corner detector (say Harris % or phasecong2). p1 and p2 are [2xnpts] arrays though % p1 and p2 are not expected to have the same number % of points. The first row of p1 and p2 gives the row % coordinate of each feature point, the second row % gives the column of each point. % w - Window size (in pixels) over which the correlation % around each feature point is performed. This should % be an odd number. % dmax - (Optional) Maximum search radius for matching % points. Used to improve speed when there is little % disparity between images. Even setting it to a generous % value of 1/4 of the image size gives a useful % speedup. If this parameter is omitted it defaults to Inf. % % % Returns: % m1, m2 - Coordinates of points selected from p1 and p2 % respectively such that (putatively) m1(:,i) matches % m2(:,i). m1 and m2 are [2xnpts] arrays defining the % points in each of the images in the form [row;col]. % p1ind, p2ind - Indices of points in p1 and p2 that form a match. Thus, % m1 = p1(:,p1ind) and m2 = p2(:,p2ind) % cormat - Correlation matrix; rows correspond to points in p1, % columns correspond to points in p2 % Copyright (c) 2004-2009 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % February 2004 - Original version % May 2004 - Speed improvements + constraint on search radius for % additional speed % August 2004 - Vectorized distance calculation for more speed % (thanks to Daniel Wedge) % December 2009 - Added return of indices of matching points from original % point arrays function [m1, m2, p1ind, p2ind, cormat] = ... matchbycorrelation(im1, p1, im2, p2, w, dmax) if nargin == 5 dmax = Inf; end im1 = double(im1); im2 = double(im2); % Subtract image smoothed with an averaging filter of size wXw from % each of the images. This compensates for brightness differences in % each image. Doing it now allows faster correlation calculation. im1 = im1 - filter2(fspecial('average',w),im1); im2 = im2 - filter2(fspecial('average',w),im2); % Generate correlation matrix cormat = correlatiomatrix(im1, p1, im2, p2, w, dmax); [corrows,corcols] = size(cormat); % Find max along rows give strongest match in p2 for each p1 [mp2forp1, colp2forp1] = max(cormat,[],2); % Find max down cols give strongest match in p1 for each p2 [mp1forp2, rowp1forp2] = max(cormat,[],1); % Now find matches that were consistent in both directions p1ind = zeros(1,length(p1)); % Arrays for storing matched indices p2ind = zeros(1,length(p2)); indcount = 0; for n = 1:corrows if rowp1forp2(colp2forp1(n)) == n % consistent both ways indcount = indcount + 1; p1ind(indcount) = n; p2ind(indcount) = colp2forp1(n); end end % Trim arrays of indices of matched points p1ind = p1ind(1:indcount); p2ind = p2ind(1:indcount); % Extract matched points from original arrays m1 = p1(:,p1ind); m2 = p2(:,p2ind); %------------------------------------------------------------------------- % Function that does the work. This function builds a correlation matrix % that holds the correlation strength of every point relative to every % other point. While this seems a bit wasteful we need all this data if % we want to find pairs of points that correlate maximally in both % directions. % % This code assumes im1 and im2 have zero mean. This speeds the % calculation of the normalised correlation measure. function cormat = correlatiomatrix(im1, p1, im2, p2, w, dmax) if mod(w, 2) == 0 error('Window size should be odd'); end [rows1, npts1] = size(p1); [rows2, npts2] = size(p2); % Initialize correlation matrix values to -infinty cormat = -ones(npts1,npts2)*Inf; if rows1 ~= 2 | rows2 ~= 2 error('Feature points must be specified in 2xN arrays'); end [im1rows, im1cols] = size(im1); [im2rows, im2cols] = size(im2); r = (w-1)/2; % 'radius' of correlation window % For every feature point in the first image extract a window of data % and correlate with a window corresponding to every feature point in % the other image. Any feature point less than distance 'r' from the % boundary of an image is not considered. % Find indices of points that are distance 'r' or greater from % boundary on image1 and image2; n1ind = find(p1(1,:)>r & p1(1,:)<im1rows+1-r & ... p1(2,:)>r & p1(2,:)<im1cols+1-r); n2ind = find(p2(1,:)>r & p2(1,:)<im2rows+1-r & ... p2(2,:)>r & p2(2,:)<im2cols+1-r); for n1 = n1ind % Generate window in 1st image w1 = im1(p1(1,n1)-r:p1(1,n1)+r, p1(2,n1)-r:p1(2,n1)+r); % Pre-normalise w1 to a unit vector. w1 = w1./sqrt(sum(sum(w1.*w1))); % Identify the indices of points in p2 that we need to consider. if dmax == inf n2indmod = n2ind; % We have to consider all of n2ind else % Compute distances from p1(:,n1) to all available p2. p1pad = repmat(p1(:,n1),1,length(n2ind)); dists2 = sum((p1pad-p2(:,n2ind)).^2); % Find indices of points in p2 that are within distance dmax of % p1(:,n1) n2indmod = n2ind(find(dists2 < dmax^2)); end % Calculate noralised correlation measure. Note this gives % significantly better matches than the unnormalised one. for n2 = n2indmod % Generate window in 2nd image w2 = im2(p2(1,n2)-r:p2(1,n2)+r, p2(2,n2)-r:p2(2,n2)+r); cormat(n1,n2) = sum(sum(w1.*w2))/sqrt(sum(sum(w2.*w2))); end end
github
jianxiongxiao/ProfXkit-master
icp.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/icp/icp.m
19,013
utf_8
08b226a4c6ddc02c96cb999b6f8dc8fe
function [TR, TT, ER, maxD, t] = icp(q,p,varargin) % this is modified version of the original version % % Perform the Iterative Closest Point algorithm on three dimensional point % clouds. % % [TR, TT] = icp(q,p) returns the rotation matrix TR and translation % vector TT that minimizes the distances from (TR * p + TT) to q. % p is a 3xm matrix and q is a 3xn matrix. % % [TR, TT] = icp(q,p,k) forces the algorithm to make k iterations % exactly. The default is 10 iterations. % % [TR, TT, ER] = icp(q,p,k) also returns the RMS of errors for k % iterations in a (k+1)x1 vector. ER(0) is the initial error. % % [TR, TT, ER, t] = icp(q,p,k) also returns the calculation times per % iteration in a (k+1)x1 vector. t(0) is the time consumed for preprocessing. % % Additional settings may be provided in a parameter list: % % Boundary % {[]} | 1x? vector % If EdgeRejection is set, a vector can be provided that indexes into % q and specifies which points of q are on the boundary. % % EdgeRejection % {false} | true % If EdgeRejection is true, point matches to edge vertices of q are % ignored. Requires that boundary points of q are specified using % Boundary or that a triangulation matrix for q is provided. % % Extrapolation % {false} | true % If Extrapolation is true, the iteration direction will be evaluated % and extrapolated if possible using the method outlined by % Besl and McKay 1992. % % Matching % bruteForce | Delaunay | {kDtree} % Specifies how point matching should be done. % bruteForce is usually the slowest and kDtree is the fastest. % Note that the kDtree option is depends on the Statistics Toolbox % v. 7.3 or higher. % % Minimize % {point} | plane | lmaPoint % Defines whether point to point or point to plane minimization % should be performed. point is based on the SVD approach and is % usually the fastest. plane will often yield higher accuracy. It % uses linearized angles and requires surface normals for all points % in q. Calculation of surface normals requires substantial pre % proccessing. % The option lmaPoint does point to point minimization using the non % linear least squares Levenberg Marquardt algorithm. Results are % generally the same as in points, but computation time may differ. % % Normals % {[]} | n x 3 matrix % A matrix of normals for the n points in q might be provided. % Normals of q are used for point to plane minimization. % Else normals will be found through a PCA of the 4 nearest % neighbors. % % ReturnAll % {false} | true % Determines whether R and T should be returned for all iterations % or only for the last one. If this option is set to true, R will be % a 3x3x(k+1) matrix and T will be a 3x1x(k+1) matrix. % % Triangulation % {[]} | ? x 3 matrix % A triangulation matrix for the points in q can be provided, % enabling EdgeRejection. The elements should index into q, defining % point triples that act together as triangles. % % Verbose % {false} | true % Enables extrapolation output in the Command Window. % % Weight % {@(match)ones(1,m)} | Function handle % For point or plane minimization, a function handle to a weighting % function can be provided. The weighting function will be called % with one argument, a 1xm vector that specifies point pairs by % indexing into q. The weighting function should return a 1xm vector % of weights for every point pair. % % WorstRejection % {0} | scalar in ]0; 1[ % Reject a given percentage of the worst point pairs, based on their % Euclidean distance. % % Martin Kjer and Jakob Wilm, Technical University of Denmark, 2012 % Use the inputParser class to validate input arguments. inp = inputParser; inp.addRequired('q', @(x)isreal(x) && size(x,1) == 3); inp.addRequired('p', @(x)isreal(x) && size(x,1) == 3); inp.addOptional('iter', 10, @(x)x > 0 && x < 10^5); inp.addParamValue('Boundary', [], @(x)size(x,1) == 1); inp.addParamValue('EdgeRejection', false, @(x)islogical(x)); inp.addParamValue('Extrapolation', false, @(x)islogical(x)); validMatching = {'bruteForce','Delaunay','kDtree'}; inp.addParamValue('Matching', 'kDtree', @(x)any(strcmpi(x,validMatching))); validMinimize = {'point','plane','lmapoint'}; inp.addParamValue('Minimize', 'point', @(x)any(strcmpi(x,validMinimize))); inp.addParamValue('Normals', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('NormalsData', [], @(x)isreal(x) && size(x,1) == 3); inp.addParamValue('ReturnAll', false, @(x)islogical(x)); inp.addParamValue('Triangulation', [], @(x)isreal(x) && size(x,2) == 3); inp.addParamValue('Verbose', false, @(x)islogical(x)); inp.addParamValue('Weight', @(x)ones(1,length(x)), @(x)isa(x,'function_handle')); inp.addParamValue('WorstRejection', 0, @(x)isscalar(x) && x > 0 && x < 1); inp.addParamValue('SmartRejection', 0, @(x)isscalar(x) && x > 0); inp.parse(q,p,varargin{:}); arg = inp.Results; clear('inp'); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Actual implementation % Allocate vector for RMS of errors in every iteration. t = zeros(arg.iter+1,1); % Start timer tic; Np = size(p,2); % Transformed data point cloud pt = p; % Allocate vector for RMS of errors in every iteration. ER = zeros(arg.iter+1,1); maxD = zeros(arg.iter,1); % Initialize temporary transform vector and matrix. T = zeros(3,1); R = eye(3,3); % Initialize total transform vector(s) and rotation matric(es). TT = zeros(3,1, arg.iter+1); TR = repmat(eye(3,3), [1,1, arg.iter+1]); % If Minimize == 'plane', normals are needed if (strcmp(arg.Minimize, 'plane') && isempty(arg.Normals)) arg.Normals = lsqnormest(q,4); end % If Matching == 'Delaunay', a triangulation is needed if strcmp(arg.Matching, 'Delaunay') DT = DelaunayTri(transpose(q)); end % If Matching == 'kDtree', a kD tree should be built (req. Stat. TB >= 7.3) if strcmp(arg.Matching, 'kDtree') kdOBJ = KDTreeSearcher(transpose(q)); end % If edge vertices should be rejected, find edge vertices if arg.EdgeRejection if isempty(arg.Boundary) bdr = find_bound(q, arg.Triangulation); else bdr = arg.Boundary; end end if arg.Extrapolation % Initialize total transform vector (quaternion ; translation vec.) qq = [ones(1,arg.iter+1);zeros(6,arg.iter+1)]; % Allocate vector for direction change and change angle. dq = zeros(7,arg.iter+1); theta = zeros(1,arg.iter+1); end t(1) = toc; % Go into main iteration loop for k=1:arg.iter % Do matching switch arg.Matching case 'bruteForce' [match mindist] = match_bruteForce(q,pt); case 'Delaunay' [match mindist] = match_Delaunay(q,pt,DT); case 'kDtree' [match mindist] = match_kDtree(q,pt,kdOBJ); end % If matches to edge vertices should be rejected if arg.EdgeRejection p_idx = not(ismember(match, bdr)); q_idx = match(p_idx); mindist = mindist(p_idx); else p_idx = true(1, Np); q_idx = match; end if k==1 && arg.SmartRejection arg.WorstRejection = sum(mindist > (median(mindist)* arg.SmartRejection))/ length(mindist); fprintf('ICP: Median=%f Threshold=%f WorstRejection=%f\n', median(mindist),median(mindist)* arg.SmartRejection,arg.WorstRejection); % vis %{ figure hist(mindist,0:0.01/10:max(mindist)); hold on; plot(median(mindist),0,'g*'); plot(median(mindist)* arg.SmartRejection,0,'r*'); %} end % If worst matches should be rejected if arg.WorstRejection edge = round((1-arg.WorstRejection)*sum(p_idx)); pairs = find(p_idx); [~, idx] = sort(mindist); p_idx(pairs(idx(edge:end))) = false; q_idx = match(p_idx); mindist = mindist(p_idx); end maxD(k) = max(mindist); if k == 1 ER(k) = sqrt(sum(mindist.^2)/length(mindist)); end switch arg.Minimize case 'point' % Determine weight vector weights = arg.Weight(match); [R,T] = eq_point(q(:,q_idx),pt(:,p_idx), weights(p_idx)); case 'plane' weights = arg.Weight(match); [R,T] = eq_plane(q(:,q_idx),pt(:,p_idx),arg.Normals(:,q_idx),weights(p_idx)); case 'lmaPoint' [R,T] = eq_lmaPoint(q(:,q_idx),pt(:,p_idx)); end % Add to the total transformation TR(:,:,k+1) = R*TR(:,:,k); TT(:,:,k+1) = R*TT(:,:,k)+T; % Apply last transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Root mean of objective function ER(k+1) = rms_error(q(:,q_idx), pt(:,p_idx)); % If Extrapolation, we might be able to move quicker if arg.Extrapolation qq(:,k+1) = [rmat2quat(TR(:,:,k+1));TT(:,:,k+1)]; dq(:,k+1) = qq(:,k+1) - qq(:,k); theta(k+1) = (180/pi)*acos(dot(dq(:,k),dq(:,k+1))/(norm(dq(:,k))*norm(dq(:,k+1)))); if arg.Verbose disp(['Direction change ' num2str(theta(k+1)) ' degree in iteration ' num2str(k)]); end if k>2 && theta(k+1) < 10 && theta(k) < 10 d = [ER(k+1), ER(k), ER(k-1)]; v = [0, -norm(dq(:,k+1)), -norm(dq(:,k))-norm(dq(:,k+1))]; vmax = 25 * norm(dq(:,k+1)); dv = extrapolate(v,d,vmax); if dv ~= 0 q_mark = qq(:,k+1) + dv * dq(:,k+1)/norm(dq(:,k+1)); q_mark(1:4) = q_mark(1:4)/norm(q_mark(1:4)); qq(:,k+1) = q_mark; TR(:,:,k+1) = quat2rmat(qq(1:4,k+1)); TT(:,:,k+1) = qq(5:7,k+1); % Reapply total transformation pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np); % Recalculate root mean of objective function % Note this is costly and only for fun! switch arg.Matching case 'bruteForce' [~, mindist] = match_bruteForce(q,pt); case 'Delaunay' [~, mindist] = match_Delaunay(q,pt,DT); case 'kDtree' [~, mindist] = match_kDtree(q,pt,kdOBJ); end ER(k+1) = sqrt(sum(mindist.^2)/length(mindist)); end end end t(k+1) = toc; end if not(arg.ReturnAll) TR = TR(:,:,end); TT = TT(:,:,end); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_bruteForce(q, p) m = size(p,2); n = size(q,2); match = zeros(1,m); mindist = zeros(1,m); for ki=1:m d=zeros(1,n); for ti=1:3 d=d+(q(ti,:)-p(ti,ki)).^2; end [mindist(ki),match(ki)]=min(d); end mindist = sqrt(mindist); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_Delaunay(q, p, DT) match = transpose(nearestNeighbor(DT, transpose(p))); mindist = sqrt(sum((p-q(:,match)).^2,1)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [match mindist] = match_kDtree(~, p, kdOBJ) [match mindist] = knnsearch(kdOBJ,transpose(p)); match = transpose(match); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_point(q,p,weights) m = size(p,2); n = size(q,2); % normalize weights weights = weights ./ sum(weights); % find data centroid and deviations from centroid q_bar = q * transpose(weights); q_mark = q - repmat(q_bar, 1, n); % Apply weights q_mark = q_mark .* repmat(weights, 3, 1); % find data centroid and deviations from centroid p_bar = p * transpose(weights); p_mark = p - repmat(p_bar, 1, m); % Apply weights %p_mark = p_mark .* repmat(weights, 3, 1); N = p_mark*transpose(q_mark); % taking points of q in matched order [U,~,V] = svd(N); % singular value decomposition R = V*diag([1 1 det(U*V')])*transpose(U); T = q_bar - R*p_bar; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_plane(q,p,n,weights) n = n .* repmat(weights,3,1); c = cross(p,n); cn = vertcat(c,n); C = cn*transpose(cn); b = - [sum(sum((p-q).*repmat(cn(1,:),3,1).*n)); sum(sum((p-q).*repmat(cn(2,:),3,1).*n)); sum(sum((p-q).*repmat(cn(3,:),3,1).*n)); sum(sum((p-q).*repmat(cn(4,:),3,1).*n)); sum(sum((p-q).*repmat(cn(5,:),3,1).*n)); sum(sum((p-q).*repmat(cn(6,:),3,1).*n))]; X = C\b; cx = cos(X(1)); cy = cos(X(2)); cz = cos(X(3)); sx = sin(X(1)); sy = sin(X(2)); sz = sin(X(3)); R = [cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz; cy*sz cx*cz+sx*sy*sz cx*sy*sz-cz*sx; -sy cy*sx cx*cy]; T = X(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [R,T] = eq_lmaPoint(q,p) Rx = @(a)[1 0 0; 0 cos(a) -sin(a); 0 sin(a) cos(a)]; Ry = @(b)[cos(b) 0 sin(b); 0 1 0; -sin(b) 0 cos(b)]; Rz = @(g)[cos(g) -sin(g) 0; sin(g) cos(g) 0; 0 0 1]; Rot = @(x)Rx(x(1))*Ry(x(2))*Rz(x(3)); myfun = @(x,xdata)Rot(x(1:3))*xdata+repmat(x(4:6),1,length(xdata)); options = optimset('Algorithm', 'levenberg-marquardt'); x = lsqcurvefit(myfun, zeros(6,1), p, q, [], [], options); R = Rot(x(1:3)); T = x(4:6); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Extrapolation in quaternion space. Details are found in: % % Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes. % IEEE Transactions on pattern analysis and machine intelligence, 239?256. function [dv] = extrapolate(v,d,vmax) p1 = polyfit(v,d,1); % linear fit p2 = polyfit(v,d,2); % parabolic fit v1 = -p1(2)/p1(1); % linear zero crossing v2 = -p2(2)/(2*p2(1)); % polynomial top point if issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1]) disp('Parabolic update!'); dv = v2; elseif issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])... || (v2 < 0 && issorted([0 v1 vmax])) disp('Line based update!'); dv = v1; elseif v1 > vmax && v2 > vmax disp('Maximum update!'); dv = vmax; else disp('No extrapolation!'); dv = 0; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Determine the RMS error between two point equally sized point clouds with % point correspondance. % ER = rms_error(p1,p2) where p1 and p2 are 3xn matrices. function ER = rms_error(p1,p2) dsq = sum(power(p1 - p2, 2),1); ER = sqrt(mean(dsq)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (orthogonal) rotation matrices R to (unit) quaternion % representations % % Input: A 3x3xn matrix of rotation matrices % Output: A 4xn matrix of n corresponding quaternions % % http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion function quaternion = rmat2quat(R) Qxx = R(1,1,:); Qxy = R(1,2,:); Qxz = R(1,3,:); Qyx = R(2,1,:); Qyy = R(2,2,:); Qyz = R(2,3,:); Qzx = R(3,1,:); Qzy = R(3,2,:); Qzz = R(3,3,:); w = 0.5 * sqrt(1+Qxx+Qyy+Qzz); x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz); y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz); z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz); quaternion = reshape([w;x;y;z],4,[]); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Converts (unit) quaternion representations to (orthogonal) rotation matrices R % % Input: A 4xn matrix of n quaternions % Output: A 3x3xn matrix of corresponding rotation matrices % % http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix function R = quat2rmat(quaternion) q0(1,1,:) = quaternion(1,:); qx(1,1,:) = quaternion(2,:); qy(1,1,:) = quaternion(3,:); qz(1,1,:) = quaternion(4,:); R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy; 2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx; 2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2]; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Least squares normal estimation from point clouds using PCA % % H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle. % Surface reconstruction from unorganized points. % In Proceedings of ACM Siggraph, pages 71:78, 1992. % % p should be a matrix containing the horizontally concatenated column % vectors with points. k is a scalar indicating how many neighbors the % normal estimation is based upon. % % Note that for large point sets, the function performs significantly % faster if Statistics Toolbox >= v. 7.3 is installed. % % Jakob Wilm 2010 function n = lsqnormest(p, k) m = size(p,2); n = zeros(3,m); v = ver('stats'); if str2double(v.Version) >= 7.5 neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1)); else neighbors = k_nearest_neighbors(p, p, k+1); end for i = 1:m x = p(:,neighbors(2:end, i)); p_bar = 1/k * sum(x,2); P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P %P = 2*cov(x); [V,D] = eig(P); [~, idx] = min(diag(D)); % choses the smallest eigenvalue n(:,i) = V(:,idx); % returns the corresponding eigenvector end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Program to find the k - nearest neighbors (kNN) within a set of points. % Distance metric used: Euclidean distance % % Note that this function makes repetitive use of min(), which seems to be % more efficient than sort() for k < 30. function [neighborIds neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k) numDataPoints = size(dataMatrix,2); numQueryPoints = size(queryMatrix,2); neighborIds = zeros(k,numQueryPoints); neighborDistances = zeros(k,numQueryPoints); D = size(dataMatrix, 1); %dimensionality of points for i=1:numQueryPoints d=zeros(1,numDataPoints); for t=1:D % this is to avoid slow repmat() d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2; end for j=1:k [s,t] = min(d); neighborIds(j,i)=t; neighborDistances(j,i)=sqrt(s); d(t) = NaN; % remove found number from d end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Boundary point determination. Given a set of 3D points and a % corresponding triangle representation, returns those point indices that % define the border/edge of the surface. function bound = find_bound(pts, poly) %Correcting polygon indices and converting datatype poly = double(poly); pts = double(pts); %Calculating freeboundary points: TR = TriRep(poly, pts(1,:)', pts(2,:)', pts(3,:)'); FF = freeBoundary(TR); %Output bound = FF(:,1); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
jianxiongxiao/ProfXkit-master
vl_compile.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/vl_compile.m
5,060
utf_8
978f5189bb9b2a16db3368891f79aaa6
function vl_compile(compiler) % VL_COMPILE Compile VLFeat MEX files % VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command % works only under Windows and is used to re-build problematic % binaries. The preferred method of compiling VLFeat on both UNIX % and Windows is through the provided Makefiles. % % VL_COMPILE() only compiles the MEX files and assumes that the % VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has % already been built. This file is built by the Makefiles. % % By default VL_COMPILE() assumes that Visual C++ is the active % MATLAB compiler. VL_COMPILE('lcc') assumes that the active % compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does % not seem to be able to compile the latest versions of VLFeat due % to bugs in the support of 64-bit integers. Therefore it is % recommended to use Visual C++ instead. % % See also: VL_NOPREFIX(), VL_HELP(). % Authors: Andrea Vedadli, Jonghyun Choi % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin < 1, compiler = 'visualc' ; end switch lower(compiler) case 'visualc' fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ; useLcc = false ; case 'lcc' fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ; warning('LCC may fail to compile VLFeat. See help vl_compile.') ; useLcc = true ; otherwise error('Unknown compiler ''%s''.', compiler) end vlDir = vl_root ; toolboxDir = fullfile(vlDir, 'toolbox') ; switch computer case 'PCWIN' fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename); mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ; binwDir = fullfile(vlDir, 'bin', 'win32') ; case 'PCWIN64' fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename); mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ; binwDir = fullfile(vlDir, 'bin', 'win64') ; otherwise error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ; end impLibPath = fullfile(binwDir, 'vl.lib') ; libDir = fullfile(binwDir, 'vl.dll') ; mkd(mexwDir) ; % find the subdirectories of toolbox that we should process subDirs = dir(toolboxDir) ; subDirs = subDirs([subDirs.isdir]) ; discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ; keep = cellfun('isempty', discard) ; subDirs = subDirs(keep) ; subDirs = {subDirs.name} ; % Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if ~exist(fullfile(binwDir, 'vl.dll')) error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ... fullfile(binwDir, 'vl.dll')) ; end tmp = dir(fullfile(binwDir, '*.dll')) ; supportFileNames = {tmp.name} ; for fi = 1:length(supportFileNames) name = supportFileNames{fi} ; cp(fullfile(binwDir, name), ... fullfile(mexwDir, name) ) ; end % Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ if useLcc lccImpLibDir = fullfile(mexwDir, 'lcc') ; lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ; lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ; lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ; mkd(lccImpLibDir) ; cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ; cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ; fprintf('Running:\n> %s\n', cmd) ; curPath = pwd ; try cd(lccImpLibDir) ; [d,w] = system(cmd) ; if d, error(w); end cd(curPath) ; catch cd(curPath) ; error(lasterr) ; end end % Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ for i = 1:length(subDirs) thisDir = fullfile(toolboxDir, subDirs{i}) ; fileNames = ls(fullfile(thisDir, '*.c')); for f = 1:size(fileNames,1) fileName = fileNames(f, :) ; sp = strfind(fileName, ' '); if length(sp) > 0, fileName = fileName(1:sp-1); end filePath = fullfile(thisDir, fileName); fprintf('MEX %s\n', filePath); dot = strfind(fileName, '.'); mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']); if exist(mexFile) delete(mexFile) end cmd = {['-I' toolboxDir], ... ['-I' vlDir], ... '-O', ... '-outdir', mexwDir, ... filePath } ; if useLcc cmd{end+1} = lccImpLibPath ; else cmd{end+1} = impLibPath ; end mex(cmd{:}) ; end end % -------------------------------------------------------------------- function cp(src,dst) % -------------------------------------------------------------------- if ~exist(dst,'file') fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ; copyfile(src,dst) ; end % -------------------------------------------------------------------- function mkd(dst) % -------------------------------------------------------------------- if ~exist(dst, 'dir') fprintf('Creating directory ''%s''.', dst) ; mkdir(dst) ; end
github
jianxiongxiao/ProfXkit-master
vl_noprefix.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/vl_noprefix.m
1,875
utf_8
97d8755f0ba139ac1304bc423d3d86d3
function vl_noprefix % VL_NOPREFIX Create a prefix-less version of VLFeat commands % VL_NOPREFIX() creats prefix-less stubs for VLFeat functions % (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs % are included in the VLFeat binary distribution anyways. Moreover, % on UNIX platforms, the stubs are generally constructed by the % Makefile. % % See also: VL_COMPILE(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). root = fileparts(which(mfilename)) ; list = listMFilesX(root); outDir = fullfile(root, 'noprefix') ; if ~exist(outDir, 'dir') mkdir(outDir) ; end for li = 1:length(list) name = list(li).name(1:end-2) ; % remove .m nname = name(4:end) ; % remove vl_ stubPath = fullfile(outDir, [nname '.m']) ; fout = fopen(stubPath, 'w') ; fprintf('Creating stub %s for %s\n', stubPath, nname) ; fprintf(fout, 'function varargout = %s(varargin)\n', nname) ; fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ; fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ; fclose(fout) ; end end function list = listMFilesX(root) list = struct('name', {}, 'path', {}) ; files = dir(root) ; for fi = 1:length(files) name = files(fi).name ; if files(fi).isdir if any(regexp(name, '^(\.|\.\.|noprefix)$')) continue ; else tmp = listMFilesX(fullfile(root, name)) ; list = [list, tmp] ; end end if any(regexp(name, '^vl_(demo|test).*m$')) continue ; elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$')) continue ; elseif any(regexp(name, '\.m$')) list(end+1) = struct(... 'name', {name}, ... 'path', {fullfile(root, name)}) ; end end end
github
jianxiongxiao/ProfXkit-master
vl_pegasos.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/misc/vl_pegasos.m
2,837
utf_8
d5e0915c439ece94eb5597a07090b67d
% VL_PEGASOS [deprecated] % VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead. function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin) % Verbose not supported if (sum(strcmpi('Verbose',varargin))) varargin(find(strcmpi('Verbose',varargin),1))=[]; fprintf('Option VERBOSE is no longer supported.\n'); end % DiagnosticCallRef not supported if (sum(strcmpi('DiagnosticCallRef',varargin))) varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[]; varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[]; fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n'); end % different default value for MaxIterations if (sum(strcmpi('MaxIterations',varargin)) == 0) varargin{end+1} = 'MaxIterations'; varargin{end+1} = ceil(10/LAMBDA); end % different default value for BiasMultiplier if (sum(strcmpi('BiasMultiplier',varargin)) == 0) varargin{end+1} = 'BiasMultiplier'; varargin{end+1} = 0; end % parameters for vl_maketrainingset setvarargin = {}; if (sum(strcmpi('HOMKERMAP',varargin))) setvarargin{end+1} = 'HOMKERMAP'; setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1}; varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[]; varargin(find(strcmpi('HOMKERMAP',varargin),1))=[]; end if (sum(strcmpi('KChi2',varargin))) setvarargin{end+1} = 'KChi2'; varargin(find(strcmpi('KChi2',varargin),1))=[]; end if (sum(strcmpi('KINTERS',varargin))) setvarargin{end+1} = 'KINTERS'; varargin(find(strcmpi('KINTERS',varargin),1))=[]; end if (sum(strcmpi('KL1',varargin))) setvarargin{end+1} = 'KL1'; varargin(find(strcmpi('KL1',varargin),1))=[]; end if (sum(strcmpi('KJS',varargin))) setvarargin{end+1} = 'KJS'; varargin(find(strcmpi('KJS',varargin),1))=[]; end if (sum(strcmpi('Period',varargin))) setvarargin{end+1} = 'Period'; setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1}; varargin(find(strcmpi('Period',varargin),1)+1)=[]; varargin(find(strcmpi('Period',varargin),1))=[]; end if (sum(strcmpi('Window',varargin))) setvarargin{end+1} = 'Window'; setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1}; varargin(find(strcmpi('Window',varargin),1)+1)=[]; varargin(find(strcmpi('Window',varargin),1))=[]; end if (sum(strcmpi('Gamma',varargin))) setvarargin{end+1} = 'Gamma'; setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1}; varargin(find(strcmpi('Gamma',varargin),1)+1)=[]; varargin(find(strcmpi('Gamma',varargin),1))=[]; end setvarargin{:} DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:}); DATA [w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:}); fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n'); end
github
jianxiongxiao/ProfXkit-master
vl_svmpegasos.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/misc/vl_svmpegasos.m
1,178
utf_8
009c2a2b87a375d529ed1a4dbe3af59f
% VL_SVMPEGASOS [deprecated] % VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead. function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin) % Verbose not supported if (sum(strcmpi('Verbose',varargin))) varargin(find(strcmpi('Verbose',varargin),1))=[]; fprintf('Option VERBOSE is no longer supported.\n'); end % DiagnosticCallRef not supported if (sum(strcmpi('DiagnosticCallRef',varargin))) varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[]; varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[]; fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n'); end % different default value for MaxIterations if (sum(strcmpi('MaxIterations',varargin)) == 0) varargin{end+1} = 'MaxIterations'; varargin{end+1} = ceil(10/LAMBDA); end % different default value for BiasMultiplier if (sum(strcmpi('BiasMultiplier',varargin)) == 0) varargin{end+1} = 'BiasMultiplier'; varargin{end+1} = 0; end [w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:}); fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n'); end
github
jianxiongxiao/ProfXkit-master
vl_override.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/misc/vl_override.m
4,654
utf_8
e233d2ecaeb68f56034a976060c594c5
function config = vl_override(config,update,varargin) % VL_OVERRIDE Override structure subset % CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds % of the structure UPDATE to the corresponding fields of the % struture CONFIG. % % Usually CONFIG is interpreted as a list of paramters with their % default values and UPDATE as a list of new paramete values. % % VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i) % UPDATE has a field not found in CONFIG, or (ii) non-leaf values of % CONFIG are overwritten. % % VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found % in CONFIG instead of copying them. % % VL_OVERRIDE(..., 'CaseI') matches field names in a % case-insensitive manner. % % Remark:: % Fields are copied at the deepest possible level. For instance, % if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the % structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with % fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the % structure A.B=4, then the field A.B is copied, and VL_OVERRIDE() % returns the structure A.B=4 (specifying 'Warn' would warn about % the fact that the substructure B.C1, B.C2 is being deleted). % % Remark:: % Two fields are matched if they correspond exactly. Specifically, % two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B % match if, and only if, (i) A and B have the same dimensions, % (ii) IA == IB, and (iii) FA == FB. % % See also: VL_ARGPARSE(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). warn = false ; skip = false ; err = false ; casei = false ; if length(varargin) == 1 & ~ischar(varargin{1}) % legacy warn = 1 ; end if ~warn & length(varargin) > 0 for i=1:length(varargin) switch lower(varargin{i}) case 'warn' warn = true ; case 'skip' skip = true ; case 'err' err = true ; case 'argparse' argparse = true ; case 'casei' casei = true ; otherwise error(sprintf('Unknown option ''%s''.',varargin{i})) ; end end end % if CONFIG is not a struct array just copy UPDATE verbatim if ~isstruct(config) config = update ; return ; end % if CONFIG is a struct array but UPDATE is not, no match can be % established and we simply copy UPDATE verbatim if ~isstruct(update) config = update ; return ; end % if CONFIG and UPDATE are both struct arrays, but have different % dimensions then nom atch can be established and we simply copy % UPDATE verbatim if numel(update) ~= numel(config) config = update ; return ; end % if CONFIG and UPDATE are both struct arrays of the same % dimension, we override recursively each field for idx=1:numel(update) fields = fieldnames(update) ; for i = 1:length(fields) updateFieldName = fields{i} ; if casei configFieldName = findFieldI(config, updateFieldName) ; else configFieldName = findField(config, updateFieldName) ; end if ~isempty(configFieldName) config(idx).(configFieldName) = ... vl_override(config(idx).(configFieldName), ... update(idx).(updateFieldName)) ; else if warn warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ... updateFieldName)) ; end if err error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ... updateFieldName)) ; end if skip if warn warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ... updateFieldName)) ; end continue ; end config(idx).(updateFieldName) = update(idx).(updateFieldName) ; end end end % -------------------------------------------------------------------- function field = findFieldI(S, matchField) % -------------------------------------------------------------------- field = '' ; fieldNames = fieldnames(S) ; for fi=1:length(fieldNames) if strcmpi(fieldNames{fi}, matchField) field = fieldNames{fi} ; end end % -------------------------------------------------------------------- function field = findField(S, matchField) % -------------------------------------------------------------------- field = '' ; fieldNames = fieldnames(S) ; for fi=1:length(fieldNames) if strcmp(fieldNames{fi}, matchField) field = fieldNames{fi} ; end end
github
jianxiongxiao/ProfXkit-master
vl_quickvis.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/quickshift/vl_quickvis.m
3,696
utf_8
27f199dad4c5b9c192a5dd3abc59f9da
function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts) % VL_QUICKVIS Create an edge image from a Quickshift segmentation. % IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge % stability image from a Quickshift segmentation. RATIO controls the tradeoff % between color consistency and spatial consistency (See VL_QUICKSEG) and % KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG, % VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which % increase the density. % % VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at % most MAXCUTS segmentations. The edges between regions in each of these % segmentations are labeled in IEDGE, where the label corresponds to the % largest DIST which preserves the edge. % % [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also % returns the DIST thresholds that were chosen. % % IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS % specified % % [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) % also returns the MAP and GAPS from VL_QUICKSHIFT. % % See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin == 4 dists = maxdist; maxdist = max(dists); [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist); else [Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist); dists = unique(floor(gaps(:))); dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh if length(dists) > maxcuts ind = round(linspace(1,length(dists), maxcuts)); dists = dists(ind); end end [Iedge dists] = mapvis(map, gaps, dists); function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts) % MAPVIS Create an edge image from a Quickshift segmentation. % IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge % stability image from a Quickshift segmentation. MAXDIST is the maximum % distance between neighbors which increase the density. % % MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most % MAXCUTS segmentations. The edges between regions in each of these % segmentations are labeled in IEDGE, where the label corresponds to the % largest DIST which preserves the edge. % % [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST % thresholds that were chosen. % % IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified % % See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG if nargin == 3 dists = maxdist; maxdist = max(dists); else dists = unique(floor(gaps(:))); dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh % throw away min region size instead of maxdist? ind = find(dists < maxdist); dists = dists(ind); if length(dists) > maxcuts ind = round(linspace(1,length(dists), maxcuts)); dists = dists(ind); end end Iedge = zeros(size(map)); for i = 1:length(dists) s = find(gaps >= dists(i)); mapdist = map; mapdist(s) = s; [mapped labels] = vl_flatmap(mapdist); fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped))) borders = getborders(mapped); Iedge(borders) = dists(i); %Iedge(borders) = Iedge(borders) + 1; %Iedge(borders) = i; end %%%%%%%%% GETBORDERS function borders = getborders(map) dx = conv2(map, [-1 1], 'same'); dy = conv2(map, [-1 1]', 'same'); borders = find(dx ~= 0 | dy ~= 0);
github
jianxiongxiao/ProfXkit-master
vl_demo_aib.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/demo/vl_demo_aib.m
2,928
utf_8
590c6db09451ea608d87bfd094662cac
function vl_demo_aib % VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB) D = 4 ; K = 20 ; randn('state',0) ; rand('state',0) ; X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ; X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ; X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ; figure(1) ; clf ; hold on ; vl_plotframe(X1,'color','r') ; vl_plotframe(X2,'color','g') ; vl_plotframe(X3,'color','b') ; axis equal ; xlim([-4 4]); ylim([-4 4]); axis off ; rectangle('position',D*[-1 -1 2 2]) vl_demo_print('aib_basic_data', .6) ; C = 1:K*K ; Pcx = zeros(3,K*K) ; f1 = quantize(X1,D,K) ; f2 = quantize(X2,D,K) ; f3 = quantize(X3,D,K) ; Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ; Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ; Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ; Pcx = Pcx / sum(Pcx(:)) ; [parents, cost] = vl_aib(Pcx) ; cutsize = [K*K, 10, 3, 2, 1] ; for i=1:length(cutsize) [cut,map,short] = vl_aibcut(parents, cutsize(i)) ; parents_cut(short > 0) = parents(short(short > 0)) ; C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ; figure(i+1) ; clf ; plotquantization(D,K,C) ; hold on ; %plottree(D,K,parents_cut) ; axis equal ; axis off ; title(sprintf('%d clusters', cutsize(i))) ; vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ; end % -------------------------------------------------------------------- function f = quantize(X,D,K) % -------------------------------------------------------------------- d = 2*D / K ; j = round((X(1,:) + D) / d) ; i = round((X(2,:) + D) / d) ; j = max(min(j,K),1) ; i = max(min(i,K),1) ; f = sub2ind([K K],i,j) ; % -------------------------------------------------------------------- function [i,j] = plotquantization(D,K,C) % -------------------------------------------------------------------- hold on ; cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ; d = 2*D / K ; for i=0:K-1 for j=0:K-1 patch(d*(j+[0 1 1 0])-D, ... d*(i+[0 0 1 1])-D, ... cl(C(j*K+i+1),:)) ; end end % -------------------------------------------------------------------- function h = plottree(D,K,parents) % -------------------------------------------------------------------- d = 2*D / K ; C = zeros(2,2*K*K-1)+NaN ; N = zeros(1,2*K*K-1) ; for i=0:K-1 for j=0:K-1 C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ; N(:,j*K+i+1) = 1 ; end end for i=1:length(parents) p = parents(i) ; if p==0, continue ; end; if all(isnan(C(:,i))), continue; end if all(isnan(C(:,p))) C(:,p) = C(:,i) / N(i) ; else C(:,p) = C(:,p) + C(:,i) / N(i) ; end N(p) = N(p) + 1 ; end C(1,:) = C(1,:) ./ N ; C(2,:) = C(2,:) ./ N ; xt = zeros(3, 2*length(parents)-1)+NaN ; yt = zeros(3, 2*length(parents)-1)+NaN ; for i=1:length(parents) p = parents(i) ; if p==0, continue ; end; xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ; yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ; end h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
github
jianxiongxiao/ProfXkit-master
vl_demo_alldist.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/demo/vl_demo_alldist.m
5,460
utf_8
6d008a64d93445b9d7199b55d58db7eb
function vl_demo_alldist % numRepetitions = 3 ; numDimensions = 1000 ; numSamplesRange = [300] ; settingsRange = {{'alldist2', 'double', 'l2', }, ... {'alldist', 'double', 'l2', 'nosimd'}, ... {'alldist', 'double', 'l2' }, ... {'alldist2', 'single', 'l2', }, ... {'alldist', 'single', 'l2', 'nosimd'}, ... {'alldist', 'single', 'l2' }, ... {'alldist2', 'double', 'l1', }, ... {'alldist', 'double', 'l1', 'nosimd'}, ... {'alldist', 'double', 'l1' }, ... {'alldist2', 'single', 'l1', }, ... {'alldist', 'single', 'l1', 'nosimd'}, ... {'alldist', 'single', 'l1' }, ... {'alldist2', 'double', 'chi2', }, ... {'alldist', 'double', 'chi2', 'nosimd'}, ... {'alldist', 'double', 'chi2' }, ... {'alldist2', 'single', 'chi2', }, ... {'alldist', 'single', 'chi2', 'nosimd'}, ... {'alldist', 'single', 'chi2' }, ... {'alldist2', 'double', 'hell', }, ... {'alldist', 'double', 'hell', 'nosimd'}, ... {'alldist', 'double', 'hell' }, ... {'alldist2', 'single', 'hell', }, ... {'alldist', 'single', 'hell', 'nosimd'}, ... {'alldist', 'single', 'hell' }, ... {'alldist2', 'double', 'kl2', }, ... {'alldist', 'double', 'kl2', 'nosimd'}, ... {'alldist', 'double', 'kl2' }, ... {'alldist2', 'single', 'kl2', }, ... {'alldist', 'single', 'kl2', 'nosimd'}, ... {'alldist', 'single', 'kl2' }, ... {'alldist2', 'double', 'kl1', }, ... {'alldist', 'double', 'kl1', 'nosimd'}, ... {'alldist', 'double', 'kl1' }, ... {'alldist2', 'single', 'kl1', }, ... {'alldist', 'single', 'kl1', 'nosimd'}, ... {'alldist', 'single', 'kl1' }, ... {'alldist2', 'double', 'kchi2', }, ... {'alldist', 'double', 'kchi2', 'nosimd'}, ... {'alldist', 'double', 'kchi2' }, ... {'alldist2', 'single', 'kchi2', }, ... {'alldist', 'single', 'kchi2', 'nosimd'}, ... {'alldist', 'single', 'kchi2' }, ... {'alldist2', 'double', 'khell', }, ... {'alldist', 'double', 'khell', 'nosimd'}, ... {'alldist', 'double', 'khell' }, ... {'alldist2', 'single', 'khell', }, ... {'alldist', 'single', 'khell', 'nosimd'}, ... {'alldist', 'single', 'khell' }, ... } ; %settingsRange = settingsRange(end-5:end) ; styles = {} ; for marker={'x','+','.','*','o'} for color={'r','g','b','k','y'} styles{end+1} = {'color', char(color), 'marker', char(marker)} ; end end for ni=1:length(numSamplesRange) for ti=1:length(settingsRange) tocs = [] ; for ri=1:numRepetitions rand('state',ri) ; randn('state',ri) ; numSamples = numSamplesRange(ni) ; settings = settingsRange{ti} ; [tocs(end+1), D] = run_experiment(numDimensions, ... numSamples, ... settings) ; end means(ni,ti) = mean(tocs) ; stds(ni,ti) = std(tocs) ; if mod(ti-1,3) == 0 D0 = D ; else err = max(abs(D(:)-D0(:))) ; fprintf('err %f\n', err) ; if err > 1, keyboard ; end end end end if 0 figure(1) ; clf ; hold on ; numStyles = length(styles) ; for ti=1:length(settingsRange) si = mod(ti - 1, numStyles) + 1 ; h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ; leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ; errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ; end end for ti=1:length(settingsRange) leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ; end figure(1) ; clf ; barh(means(end,:)) ; set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ; xlabel('Time [s]') ; function [elaps, D] = run_experiment(numDimensions, numSamples, settings) distType = 'l2' ; algType = 'alldist' ; classType = 'double' ; useSimd = true ; for si=1:length(settings) arg = settings{si} ; switch arg case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'} distType = arg ; case {'alldist', 'alldist2'} algType = arg ; case {'single', 'double'} classType = arg ; case 'simd' useSimd = true ; case 'nosimd' useSimd = false ; otherwise assert(false) ; end end X = rand(numDimensions, numSamples) ; X(X < .3) = 0 ; switch classType case 'double' case 'single' X = single(X) ; end vl_simdctrl(double(useSimd)) ; switch algType case 'alldist' tic ; D = vl_alldist(X, distType) ; elaps = toc ; case 'alldist2' tic ; D = vl_alldist2(X, distType) ; elaps = toc ; end
github
jianxiongxiao/ProfXkit-master
vl_demo_svm.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/demo/vl_demo_svm.m
1,235
utf_8
7cf6b3504e4fc2cbd10ff3fec6e331a7
% VL_DEMO_SVM Demo: SVM: 2D linear learning function vl_demo_svm y=[];X=[]; % Load training data X and their labels y load('vl_demo_svm_data.mat') Xp = X(:,y==1); Xn = X(:,y==-1); figure plot(Xn(1,:),Xn(2,:),'*r') hold on plot(Xp(1,:),Xp(2,:),'*b') axis equal ; vl_demo_print('svm_training') ; % Parameters lambda = 0.01 ; % Regularization parameter maxIter = 1000 ; % Maximum number of iterations energy = [] ; % Diagnostic function function diagnostics(svm) energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ; end % Training the SVM energy = [] ; [w b info] = vl_svmtrain(X, y, lambda,... 'MaxNumIterations',maxIter,... 'DiagnosticFunction',@diagnostics,... 'DiagnosticFrequency',1) % Visualisation eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)]; line = ezplot(eq, [-0.9 0.9 -0.9 0.9]); set(line, 'Color', [0 0.8 0],'linewidth', 2); vl_demo_print('svm_training_result') ; figure hold on plot(energy(1,:),'--b') ; plot(energy(2,:),'-.g') ; plot(energy(3,:),'r') ; legend('Primal objective','Dual objective','Duality gap') xlabel('Diagnostics iteration') ylabel('Energy') vl_demo_print('svm_energy') ; end
github
jianxiongxiao/ProfXkit-master
vl_demo_kdtree_sift.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/demo/vl_demo_kdtree_sift.m
6,832
utf_8
e676f80ac330a351f0110533c6ebba89
function vl_demo_kdtree_sift % VL_DEMO_KDTREE_SIFT % Demonstrates the use of a kd-tree forest to match SIFT % features. If FLANN is present, this function runs a comparison % against it. % AUTORIGHS rand('state',0) ; randn('state',0); do_median = 0 ; do_mean = 1 ; % try to setup flann if ~exist('flann_search', 'file') if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ; end end do_flann = exist('nearest_neighbors') == 3 ; if ~do_flann warning('FLANN not found. Comparison disabled.') ; end maxNumComparisonsRange = [1 10 50 100 200 300 400] ; numTreesRange = [1 2 5 10] ; % get data (SIFT features) im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ; im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ; im1 = single(rgb2gray(im1)) ; im2 = single(rgb2gray(im2)) ; [f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ; [f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ; % add some noise to make matches unique d1 = single(d1) + rand(size(d1)) ; d2 = single(d2) + rand(size(d2)) ; % match exhaustively to get the ground truth elapsedDirect = tic ; D = vl_alldist(d1,d2) ; [drop, best] = min(D, [], 1) ; elapsedDirect = toc(elapsedDirect) ; for ti=1:length(numTreesRange) for vi=1:length(maxNumComparisonsRange) v = maxNumComparisonsRange(vi) ; t = numTreesRange(ti) ; if do_median tic ; kdtree = vl_kdtreebuild(d1, ... 'verbose', ... 'thresholdmethod', 'median', ... 'numtrees', t) ; [i, d] = vl_kdtreequery(kdtree, d1, d2, ... 'verbose', ... 'maxcomparisons',v) ; elapsedKD_median(vi,ti) = toc ; errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ; errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ; end if do_mean tic ; kdtree = vl_kdtreebuild(d1, ... 'verbose', ... 'thresholdmethod', 'mean', ... 'numtrees', t) ; %kdtree = readflann(kdtree, '/tmp/flann.txt') ; %checkx(kdtree, d1, 1, 1) ; [i, d] = vl_kdtreequery(kdtree, d1, d2, ... 'verbose', ... 'maxcomparisons', v) ; elapsedKD_mean(vi,ti) = toc ; errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ; errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ; end if do_flann tic ; [i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ... 'trees', t, ... 'checks', v)); ifla = i ; elapsedKD_flann(vi,ti) = toc; errors_flann(vi,ti) = sum(i ~= best) / length(best) ; errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ; end end end figure(1) ; clf ; leg = {} ; hnd = [] ; sty = {{'color','r'},{'color','g'},... {'color','b'},{'color','c'},... {'color','k'}} ; for ti=1:length(numTreesRange) s = sty{mod(ti,length(sty))+1} ; if do_median h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h1 ; end if do_mean h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h2 ; end if do_flann h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ; leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h3 ; end end set([hnd], 'linewidth', 2) ; xlabel('speedup over linear search (log times)') ; ylabel('percentage of incorrect matches (%)') ; h=legend(hnd, leg{:}, 'location', 'southeast') ; set(h,'fontsize',8) ; grid on ; axis square ; vl_demo_print('kdtree_sift_incorrect',.6) ; figure(2) ; clf ; leg = {} ; hnd = [] ; for ti=1:length(numTreesRange) s = sty{mod(ti,length(sty))+1} ; if do_median h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h1 ; end if do_mean h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ; leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h2 ; end if do_flann h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ; leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ; hnd(end+1) = h3 ; end end set([hnd], 'linewidth', 2) ; xlabel('speedup over linear search (log times)') ; ylabel('relative overestimation of minmium distannce (%)') ; h=legend(hnd, leg{:}, 'location', 'southeast') ; set(h,'fontsize',8) ; grid on ; axis square ; vl_demo_print('kdtree_sift_distortion',.6) ; % -------------------------------------------------------------------- function checkx(kdtree, X, t, n, mib, mab) % -------------------------------------------------------------------- if nargin <= 4 mib = -inf * ones(size(X,1),1) ; mab = +inf * ones(size(X,1),1) ; end lc = kdtree.trees(t).nodes.lowerChild(n) ; uc = kdtree.trees(t).nodes.upperChild(n) ; if lc < 0 for i=-lc:-uc-1 di = kdtree.trees(t).dataIndex(i) ; if any(X(:,di) > mab) error('a') ; end if any(X(:,di) < mib) error('b') ; end end return end i = kdtree.trees(t).nodes.splitDimension(n) ; v = kdtree.trees(t).nodes.splitThreshold(n) ; mab_ = mab ; mab_(i) = min(mab(i), v) ; checkx(kdtree, X, t, lc, mib, mab_) ; mib_ = mib ; mib_(i) = max(mib(i), v) ; checkx(kdtree, X, t, uc, mib_, mab) ; % -------------------------------------------------------------------- function kdtree = readflann(kdtree, path) % -------------------------------------------------------------------- data = textread(path)' ; for i=1:size(data,2) nodeIds = data(1,:) ; ni = find(nodeIds == data(1,i)) ; if ~isnan(data(2,i)) % internal node li = find(nodeIds == data(4,i)) ; ri = find(nodeIds == data(5,i)) ; kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ; kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ; kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ; kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ; else di = data(3,i) + 1 ; kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ; kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ; end kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ; end
github
jianxiongxiao/ProfXkit-master
vl_impattern.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/imop/vl_impattern.m
6,876
utf_8
1716a4d107f0186be3d11c647bc628ce
function im = vl_impattern(varargin) % VL_IMPATTERN Generate an image from a stock pattern % IM=VLPATTERN(NAME) returns an instance of the specified % pattern. These stock patterns are useful for testing algoirthms. % % All generated patterns are returned as an image of class % DOUBLE. Both gray-scale and colour images have range in [0,1]. % % VL_IMPATTERN() without arguments shows a gallery of the stock % patterns. The following patterns are supported: % % Wedge:: % The image of a wedge. % % Cone:: % The image of a cone. % % SmoothChecker:: % A checkerboard with Gaussian filtering on top. Use the % option-value pair 'sigma', SIGMA to specify the standard % deviation of the smoothing and the pair 'step', STEP to specfity % the checker size in pixels. % % ThreeDotsSquare:: % A pattern with three small dots and two squares. % % UniformNoise:: % Random i.i.d. noise. % % Blobs: % Gaussian blobs of various sizes and anisotropies. % % Blobs1: % Gaussian blobs of various orientations and anisotropies. % % Blob: % One Gaussian blob. Use the option-value pairs 'sigma', % 'orientation', and 'anisotropy' to specify the respective % parameters. 'sigma' is the scalar standard deviation of an % isotropic blob (the image domain is the rectangle % [-1,1]^2). 'orientation' is the clockwise rotation (as the Y % axis points downards). 'anisotropy' (>= 1) is the ratio of the % the largest over the smallest axis of the blob (the smallest % axis length is set by 'sigma'). Set 'cut' to TRUE to cut half % half of the blob. % % A stock image:: % Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'. % % All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but % the stock images, the default size is [128,128]. % Author: Andrea Vedaldi % Copyright (C) 2012 Andrea Vedaldi. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin > 0 pattern=varargin{1} ; varargin=varargin(2:end) ; else pattern = 'gallery' ; end patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ... 'blob', 'blobs', 'blobs1', ... 'box', 'roofs1', 'roofs2', 'river1', 'river2'} ; % spooling switch lower(pattern) case 'wedge', im = wedge(varargin) ; case 'cone', im = cone(varargin) ; case 'smoothchecker', im = smoothChecker(varargin) ; case 'threedotssquare', im = threeDotSquare(varargin) ; case 'uniformnoise', im = uniformNoise(varargin) ; case 'blob', im = blob(varargin) ; case 'blobs', im = blobs(varargin) ; case 'blobs1', im = blobs1(varargin) ; case {'box','roofs1','roofs2','river1','river2','spots'} im = stockImage(pattern, varargin) ; case 'gallery' clf ; num = numel(patterns) ; for p = 1:num vl_tightsubplot(num,p,'box','outer') ; imagesc(vl_impattern(patterns{p}),[0 1]) ; axis image off ; title(patterns{p}) ; end colormap gray ; return ; otherwise error('Unknown patter ''%s''.', pattern) ; end if nargout == 0 clf ; imagesc(im) ; hold on ; colormap gray ; axis image off ; title(pattern) ; clear im ; end function [u,v,opts,args] = commonOpts(args) opts.size = [128 128] ; [opts,args] = vl_argparse(opts, args) ; ur = linspace(-1,1,opts.size(2)) ; vr = linspace(-1,1,opts.size(1)) ; [u,v] = meshgrid(ur,vr); function im = wedge(args) [u,v,opts,args] = commonOpts(args) ; im = abs(u) + abs(v) > (1/4) ; im(v < 0) = 0 ; function im = cone(args) [u,v,opts,args] = commonOpts(args) ; im = sqrt(u.^2+v.^2) ; im = im / max(im(:)) ; function im = smoothChecker(args) opts.size = [128 128] ; opts.step = 16 ; opts.sigma = 2 ; opts = vl_argparse(opts, args) ; [u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ; im = xor((mod(u,opts.step*2) < opts.step),... (mod(v,opts.step*2) < opts.step)) ; im = double(im) ; im = vl_imsmooth(im, opts.sigma) ; function im = threeDotSquare(args) [u,v,opts,args] = commonOpts(args) ; im = ones(size(u)) ; im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ; im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ; [drop,i] = min(abs(v(:,1))) ; [drop,j1] = min(abs(u(1,:)-1/6)) ; [drop,j2] = min(abs(u(1,:))) ; [drop,j3] = min(abs(u(1,:)+1/6)) ; im(i,j1) = 0 ; im(i,j2) = 0 ; im(i,j3) = 0 ; function im = blobs(args) [u,v,opts,args] = commonOpts(args) ; im = zeros(size(u)) ; num = 5 ; square = 2 / num ; sigma = square / 2 / 3 ; scales = logspace(log10(0.5), log10(1), num) ; skews = linspace(1,2,num) ; for i=1:num for j=1:num cy = (i-1) * square + square/2 - 1; cx = (j-1) * square + square/2 - 1; A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ; C = inv(A'*A) ; x = u - cx ; y = v - cy ; im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ; end end im = im / max(im(:)) ; function im = blob(args) [u,v,opts,args] = commonOpts(args) ; opts.sigma = 0.15 ; opts.anisotropy = .5 ; opts.orientation = 2/3 * pi ; opts.cut = false ; opts = vl_argparse(opts, args) ; im = zeros(size(u)) ; th = opts.orientation ; R = [cos(th) -sin(th) ; sin(th) cos(th)] ; A = opts.sigma * R * diag([opts.anisotropy 1]) ; T = [0;0] ; [x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ; im = exp(-0.5 *(x.^2 + y.^2)) ; if opts.cut im = im .* double(x > 0) ; end function im = blobs1(args) [u,v,opts,args] = commonOpts(args) ; opts.number = 5 ; opts.sigma = [] ; opts = vl_argparse(opts, args) ; im = zeros(size(u)) ; square = 2 / opts.number ; num = opts.number ; if isempty(opts.sigma) sigma = 1/6 * square ; else sigma = opts.sigma * square ; end rotations = linspace(0,pi,num+1) ; rotations(end) = [] ; skews = linspace(1,2,num) ; for i=1:num for j=1:num cy = (i-1) * square + square/2 - 1; cx = (j-1) * square + square/2 - 1; th = rotations(i) ; R = [cos(th) -sin(th); sin(th) cos(th)] ; A = sigma * R * diag([1 1/skews(j)]) ; C = inv(A*A') ; x = u - cx ; y = v - cy ; im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ; end end im = im / max(im(:)) ; function im = uniformNoise(args) opts.size = [128 128] ; opts.seed = 1 ; opts = vl_argparse(opts, args) ; state = vl_twister('state') ; vl_twister('state',opts.seed) ; im = vl_twister(opts.size([2 1])) ; vl_twister('state',state) ; function im = stockImage(pattern,args) opts.size = [] ; opts = vl_argparse(opts, args) ; switch pattern case 'river1', path='river1.jpg' ; case 'river2', path='river2.jpg' ; case 'roofs1', path='roofs1.jpg' ; case 'roofs2', path='roofs2.jpg' ; case 'box', path='box.pgm' ; case 'spots', path='spots.jpg' ; end im = imread(fullfile(vl_root,'data',path)) ; im = im2double(im) ; if ~isempty(opts.size) im = imresize(im, opts.size) ; im = max(im,0) ; im = min(im,1) ; end
github
jianxiongxiao/ProfXkit-master
vl_tpsu.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/imop/vl_tpsu.m
1,755
utf_8
09f36e1a707c069b375eb2817d0e5f13
function [U,dU,delta]=vl_tpsu(X,Y) % VL_TPSU Compute the U matrix of a thin-plate spline transformation % U=VL_TPSU(X,Y) returns the matrix % % [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ] % [ ] % [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ] % % where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is % the opposite -r^2 log(r^2) of the radial basis function of the % thin plate spline specified by X and Y. % % [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with % respect to the parameters Y. The derivatives are arranged in a % Mx2xN array, one layer per column of U. % % See also: VL_TPS(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if exist('tpsumx') U = tpsumx(X,Y) ; else M=size(X,2) ; N=size(Y,2) ; % Faster than repmat, but still fairly slow r2 = ... (X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ... (X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ; U = - rb(r2) ; end if nargout > 1 M=size(X,2) ; N=size(Y,2) ; dx = X( ones(N,1), :)' - Y( ones(1,M), :) ; dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ; r2 = (dx.^2 + dy.^2) ; r = sqrt(r2) ; coeff = drb(r)./(r+eps) ; dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ; end % The radial basis function function y = rb(r2) y = zeros(size(r2)) ; sel = find(r2 ~= 0) ; y(sel) = - r2(sel) .* log(r2(sel)) ; % The derivative of the radial basis function function y = drb(r) y = zeros(size(r)) ; sel = find(r ~= 0) ; y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
github
jianxiongxiao/ProfXkit-master
vl_xyz2lab.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/imop/vl_xyz2lab.m
1,570
utf_8
09f95a6f9ae19c22486ec1157357f0e3
function J=vl_xyz2lab(I,il) % VL_XYZ2LAB Convert XYZ color space to LAB % J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format. % % VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55, % D65, D75, D93. The default illuminatn is E. % % See also: VL_XYZ2LUV(), VL_HELP(). % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). if nargin < 2 il='E' ; end switch lower(il) case 'a' xw = 0.4476 ; yw = 0.4074 ; case 'b' xw = 0.3324 ; yw = 0.3474 ; case 'c' xw = 0.3101 ; yw = 0.3162 ; case 'e' xw = 1/3 ; yw = 1/3 ; case 'd50' xw = 0.3457 ; yw = 0.3585 ; case 'd55' xw = 0.3324 ; yw = 0.3474 ; case 'd65' xw = 0.312713 ; yw = 0.329016 ; case 'd75' xw = 0.299 ; yw = 0.3149 ; case 'd93' xw = 0.2848 ; yw = 0.2932 ; end J=zeros(size(I)) ; % Reference white Yw = 1.0 ; Xw = xw/yw ; Zw = (1-xw-yw)/yw * Yw ; % XYZ components X = I(:,:,1) ; Y = I(:,:,2) ; Z = I(:,:,3) ; x = X/Xw ; y = Y/Yw ; z = Z/Zw ; L = 116 * f(y) - 16 ; a = 500*(f(x) - f(y)) ; b = 200*(f(y) - f(z)) ; J = cat(3,L,a,b) ; % -------------------------------------------------------------------- function b=f(a) % -------------------------------------------------------------------- sp = find(a > 0.00856) ; sm = find(a <= 0.00856) ; k = 903.3 ; b=zeros(size(a)) ; b(sp) = a(sp).^(1/3) ; b(sm) = (k*a(sm) + 16)/116 ;
github
jianxiongxiao/ProfXkit-master
vl_test_gmm.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_gmm.m
1,332
utf_8
76782cae6c98781c6c38d4cbf5549d94
function results = vl_test_gmm(varargin) % VL_TEST_GMM % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). vl_test_init ; end function s = setup() randn('state',0) ; s.X = randn(128, 1000) ; end function test_multithreading(s) dataTypes = {'single','double'} ; for dataType = dataTypes conversion = str2func(char(dataType)) ; X = conversion(s.X) ; vl_twister('state',0) ; vl_threads(0) ; [means, covariances, priors, ll, posteriors] = ... vl_gmm(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Initialization', 'rand') ; vl_twister('state',0) ; vl_threads(1) ; [means_, covariances_, priors_, ll_, posteriors_] = ... vl_gmm(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Initialization', 'rand') ; vl_assert_almost_equal(means, means_, 1e-2) ; vl_assert_almost_equal(covariances, covariances_, 1e-2) ; vl_assert_almost_equal(priors, priors_, 1e-2) ; vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ; vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ; end end
github
jianxiongxiao/ProfXkit-master
vl_test_twister.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_twister.m
1,251
utf_8
2bfb5a30cbd6df6ac80c66b73f8646da
function results = vl_test_twister(varargin) % VL_TEST_TWISTER vl_test_init ; function test_illegal_args() vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ; vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ; vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ; function test_seed_by_scalar() rand('twister',1) ; a = rand ; vl_twister('state',1) ; b = vl_twister ; vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ; function test_get_set_state() rand('twister',1) ; a = rand('twister') ; vl_twister('state',1) ; b = vl_twister('state') ; vl_assert_equal(a,b,'read state') ; a(1) = a(1) + 1 ; vl_twister('state',a) ; b = vl_twister('state') ; vl_assert_equal(a,b,'set state') ; function test_multi_dimensions() b = rand('twister') ; rand('twister',b) ; vl_twister('state',b) ; a=rand([1 2 3 4 5]) ; b=vl_twister([1 2 3 4 5]) ; vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ; function test_multi_multi_args() rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ; vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ; vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ; function test_square() rand('twister',1) ; a=rand(10) ; vl_twister('state',1) ; b=vl_twister(10) ; vl_assert_equal(a,b,'VL_TWISTER(N)') ;
github
jianxiongxiao/ProfXkit-master
vl_test_kdtree.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_kdtree.m
2,449
utf_8
9d7ad2b435a88c22084b38e5eb5f9eb9
function results = vl_test_kdtree(varargin) % VL_TEST_KDTREE vl_test_init ; function s = setup() randn('state',0) ; s.X = single(randn(10, 1000)) ; s.Q = single(randn(10, 10)) ; function test_nearest(s) for tmethod = {'median', 'mean'} for type = {@single, @double} conv = type{1} ; tmethod = char(tmethod) ; X = conv(s.X) ; Q = conv(s.Q) ; tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ; [nn, d2] = vl_kdtreequery(tree, X, Q) ; D2 = vl_alldist2(X, Q, 'l2') ; [d2_, nn_] = min(D2) ; vl_assert_equal(... nn,uint32(nn_),... 'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ; vl_assert_almost_equal(... d2,d2_,... 'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ; end end function test_nearests(s) numNeighbors = 7 ; tree = vl_kdtreebuild(s.X) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; vl_assert_equal(nn,uint32(nn_)) ; vl_assert_almost_equal(d2,d2_) ; function test_ann(s) vl_twister('state', 1) ; numNeighbors = 7 ; maxComparisons = numNeighbors * 50 ; tree = vl_kdtreebuild(s.X) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors, ... 'maxComparisons', maxComparisons) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; for i=1:size(s.Q,2) overlap = numel(intersect(nn(:,i), nn_(:,i))) / ... numel(union(nn(:,i), nn_(:,i))) ; assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ; end function test_ann_forest(s) vl_twister('state', 1) ; numNeighbors = 7 ; maxComparisons = numNeighbors * 25 ; numTrees = 5 ; tree = vl_kdtreebuild(s.X, 'numTrees', 5) ; [nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ... 'numNeighbors', numNeighbors, ... 'maxComparisons', maxComparisons) ; D2 = vl_alldist2(s.X, s.Q, 'l2') ; [d2_, nn_] = sort(D2) ; d2_ = d2_(1:numNeighbors, :) ; nn_ = nn_(1:numNeighbors, :) ; for i=1:size(s.Q,2) overlap = numel(intersect(nn(:,i), nn_(:,i))) / ... numel(union(nn(:,i), nn_(:,i))) ; assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ; end
github
jianxiongxiao/ProfXkit-master
vl_test_imwbackward.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_imwbackward.m
514
utf_8
33baa0784c8f6f785a2951d7f1b49199
function results = vl_test_imwbackward(varargin) % VL_TEST_IMWBACKWARD vl_test_init ; function s = setup() s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; function test_identity(s) xr = 1:size(s.I,2) ; yr = 1:size(s.I,1) ; [x,y] = meshgrid(xr,yr) ; vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ; function test_invalid_args(s) xr = 1:size(s.I,2) ; yr = 1:size(s.I,1) ; [x,y] = meshgrid(xr,yr) ; vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
github
jianxiongxiao/ProfXkit-master
vl_test_alphanum.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_alphanum.m
1,624
utf_8
2da2b768c2d0f86d699b8f31614aa424
function results = vl_test_alphanum(varargin) % VL_TEST_ALPHANUM vl_test_init ; function s = setup() s.strings = ... {'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ; s.sortedStrings = ... {'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ; function test_basic(s) sorted = vl_alphanum(s.strings) ; assert(isequal(sorted,s.sortedStrings)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_printsize.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_printsize.m
1,447
utf_8
0f0b6437c648b7a2e1310900262bd765
function results = vl_test_printsize(varargin) % VL_TEST_PRINTSIZE vl_test_init ; function s = setup() s.fig = figure(1) ; s.usletter = [8.5, 11] ; % inches s.a4 = [8.26772, 11.6929] ; clf(s.fig) ; plot(1:10) ; function teardown(s) close(s.fig) ; function test_basic(s) for sigma = [1 0.5 0.2] vl_printsize(s.fig, sigma) ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ; vl_assert_almost_equal(pos(1), 0, 1e-4) ; vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ; end function test_papertype(s) vl_printsize(s.fig, 1, 'papertype', 'a4') ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ; function test_margin(s) m = 0.5 ; vl_printsize(s.fig, 1, 'margin', m) ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ; vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ; function test_reference(s) sigma = 1 ; vl_printsize(s.fig, 1, 'reference', 'vertical') ; set(1, 'PaperUnits', 'inches') ; siz = get(1, 'PaperSize') ; pos = get(1, 'PaperPosition') ; vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ; vl_assert_almost_equal(pos(2), 0, 1e-4) ; vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
github
jianxiongxiao/ProfXkit-master
vl_test_cummax.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_cummax.m
762
utf_8
3dddb5736dfffacdd94b156e67cb9c14
function results = vl_test_cummax(varargin) % VL_TEST_CUMMAX vl_test_init ; function test_basic() vl_assert_almost_equal(... vl_cummax(1), 1) ; vl_assert_almost_equal(... vl_cummax([1 2 3 4], 2), [1 2 3 4]) ; function test_multidim() a = [1 2 3 4 3 2 1] ; b = [1 2 3 4 4 4 4] ; for k=1:6 dims = ones(1,6) ; dims(k) = numel(a) ; a = reshape(a, dims) ; b = reshape(b, dims) ; vl_assert_almost_equal(... vl_cummax(a, k), b) ; end function test_storage_classes() types = {@double, @single, @int64, @uint64, ... @int32, @uint32, @int16, @uint16, ... @int8, @uint8} ; for a = types a = a{1} ; for b = types b = b{1} ; vl_assert_almost_equal(... vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ; end end
github
jianxiongxiao/ProfXkit-master
vl_test_imintegral.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_imintegral.m
1,429
utf_8
4750f04ab0ac9fc4f55df2c8583e5498
function results = vl_test_imintegral(varargin) % VL_TEST_IMINTEGRAL vl_test_init ; function state = setup() state.I = ones(5,6) ; state.correct = [ 1 2 3 4 5 6 ; 2 4 6 8 10 12 ; 3 6 9 12 15 18 ; 4 8 12 16 20 24 ; 5 10 15 20 25 30 ; ] ; function test_matlab_equivalent(s) vl_assert_equal(slow_imintegral(s.I), s.correct) ; function test_basic(s) vl_assert_equal(vl_imintegral(s.I), s.correct) ; function test_multi_dimensional(s) vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ... repmat(s.correct, [1 1 3])) ; function test_random(s) numTests = 50 ; for i = 1:numTests I = rand(5) ; vl_assert_almost_equal(vl_imintegral(s.I), ... slow_imintegral(s.I)) ; end function test_datatypes(s) vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ; vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ; vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ; vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ; vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ; function integral = slow_imintegral(I) integral = zeros(size(I)); for k = 1:size(I,3) for r = 1:size(I,1) for c = 1:size(I,2) integral(r,c,k) = sum(sum(I(1:r,1:c,k))); end end end
github
jianxiongxiao/ProfXkit-master
vl_test_sift.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_sift.m
1,318
utf_8
806c61f9db9f2ebb1d649c9bfcf3dc0a
function results = vl_test_sift(varargin) % VL_TEST_SIFT vl_test_init ; function s = setup() s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ; [s.ubc.f, s.ubc.d] = ... vl_ubcread(fullfile(vl_root,'data','box.sift')) ; function test_ubc_descriptor(s) err = [] ; [f, d] = vl_sift(s.I,... 'firstoctave', -1, ... 'frames', s.ubc.f) ; D2 = vl_alldist(f, s.ubc.f) ; [drop, perm] = min(D2) ; f = f(:,perm) ; d = d(:,perm) ; error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ... / mean(sqrt(sum(single(s.ubc.d).^2))) ; assert(error < 0.1, ... 'sift descriptor did not produce desctiptors similar to UBC ones') ; function test_ubc_detector(s) [f, d] = vl_sift(s.I,... 'firstoctave', -1, ... 'peakthresh', .01, ... 'edgethresh', 10) ; s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ; f(4,:) = mod(f(4,:), 2*pi) ; % scale the components so that 1 pixel erro in x,y,z is equal to a % 10-th of angle. S = diag([1 1 1 20/pi]); D2 = vl_alldist(S * s.ubc.f, S * f) ; [d2,perm] = sort(min(D2)) ; error = sqrt(d2) ; quant80 = round(.8 * size(f,2)) ; % check for less than one pixel error at 80% quantile assert(error(quant80) < 1, ... 'sift detector did not produce enough keypoints similar to UBC ones') ;
github
jianxiongxiao/ProfXkit-master
vl_test_binsum.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_binsum.m
1,301
utf_8
5bbd389cbc4d997e413d809fe4efda6d
function results = vl_test_binsum(varargin) % VL_TEST_BINSUM vl_test_init ; function test_three_args() vl_assert_almost_equal(... vl_binsum([0 0], 1, 2), [0 1]) ; vl_assert_almost_equal(... vl_binsum([1 7], -1, 1), [0 7]) ; vl_assert_almost_equal(... vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ; function test_four_args() vl_assert_almost_equal(... vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ; vl_assert_almost_equal(... vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ; function test_3d_one() Z = zeros(3,3,3) ; B = 3*ones(3,1,3) ; R = Z ; R(:,3,:) = 17 ; vl_assert_almost_equal(... vl_binsum(Z, 17, B, 2), R) ; function test_3d_two() Z = zeros(3,3,3) ; B = 3*ones(3,3,1) ; X = zeros(3,3,1) ; X(:,:,1) = 17 ; R = Z ; R(:,:,3) = 17 ; vl_assert_almost_equal(... vl_binsum(Z, X, B, 3), R) ; function test_storage_classes() types = {@double, @single, @int64, @uint64, ... @int32, @uint32, @int16, @uint16, ... @int8, @uint8} ; for a = types a = a{1} ; for b = types b = b{1} ; vl_assert_almost_equal(... vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ; end end
github
jianxiongxiao/ProfXkit-master
vl_test_lbp.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_lbp.m
1,056
utf_8
3b5cca50109af84014e56a4280a3352a
function results = vl_test_lbp(varargin) % VL_TEST_TWISTER vl_test_init ; function test_one_on() I = {} ; I{1} = [0 0 0 ; 0 0 1 ; 0 0 0] ; I{2} = [0 0 0 ; 0 0 0 ; 0 0 1] ; I{3} = [0 0 0 ; 0 0 0 ; 0 1 0] ; I{4} = [0 0 0 ; 0 0 0 ; 1 0 0] ; I{5} = [0 0 0 ; 1 0 0 ; 0 0 0] ; I{6} = [1 0 0 ; 0 0 0 ; 0 0 0] ; I{7} = [0 1 0 ; 0 0 0 ; 0 0 0] ; I{8} = [0 0 1 ; 0 0 0 ; 0 0 0] ; for j=0:7 h = vl_lbp(single(I{j+1}), 3) ; h = find(squeeze(h)) ; vl_assert_equal(h, j * 7 + 1) ; end function test_two_on() I = {} ; I{1} = [0 0 0 ; 0 0 1 ; 0 0 1] ; I{2} = [0 0 0 ; 0 0 0 ; 0 1 1] ; I{3} = [0 0 0 ; 0 0 0 ; 1 1 0] ; I{4} = [0 0 0 ; 1 0 0 ; 1 0 0] ; I{5} = [1 0 0 ; 1 0 0 ; 0 0 0] ; I{6} = [1 1 0 ; 0 0 0 ; 0 0 0] ; I{7} = [0 1 1 ; 0 0 0 ; 0 0 0] ; I{8} = [0 0 1 ; 0 0 1 ; 0 0 0] ; for j=0:7 h = vl_lbp(single(I{j+1}), 3) ; h = find(squeeze(h)) ; vl_assert_equal(h, j * 7 + 2) ; end function test_fliplr() randn('state',0) ; I = randn(256,256,1,'single') ; f = vl_lbp(fliplr(I), 8) ; f_ = vl_lbpfliplr(vl_lbp(I, 8)) ; vl_assert_almost_equal(f,f_,1e-3) ;
github
jianxiongxiao/ProfXkit-master
vl_test_colsubset.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_colsubset.m
828
utf_8
be0c080007445b36333b863326fb0f15
function results = vl_test_colsubset(varargin) % VL_TEST_COLSUBSET vl_test_init ; function s = setup() s.x = [5 2 3 6 4 7 1 9 8 0] ; function test_beginning(s) vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ; vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ; function test_ending(s) vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ; vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ; function test_largest(s) vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ; vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ; function test_smallest(s) vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ; vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ; function test_random(s) assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
github
jianxiongxiao/ProfXkit-master
vl_test_alldist.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_alldist.m
2,373
utf_8
9ea1a36c97fe715dfa2b8693876808ff
function results = vl_test_alldist(varargin) % VL_TEST_ALLDIST vl_test_init ; function s = setup() vl_twister('state', 0) ; s.X = 3.1 * vl_twister(10,10) ; s.Y = 4.7 * vl_twister(10,7) ; function test_null_args(s) vl_assert_equal(... vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ... zeros(12,0)) ; vl_assert_equal(... vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ... zeros(0,0)) ; vl_assert_equal(... vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ... zeros(0,12)) ; vl_assert_equal(... vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ... zeros(15,12)) ; function test_self(s) vl_assert_almost_equal(... vl_alldist(s.X, 'kl2'), ... makedist(@(x,y) x*y, s.X, s.X), ... 1e-6) ; function test_distances(s) dists = {'chi2', 'l2', 'l1', 'hell', 'js', ... 'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ; distsEquiv = { ... @(x,y) (x-y)^2 / (x + y), ... @(x,y) (x-y)^2, ... @(x,y) abs(x-y), ... @(x,y) (sqrt(x) - sqrt(y))^2, ... @(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ... @(x,y) 2 * (x*y) / (x + y), ... @(x,y) x*y, ... @(x,y) min(x,y), ... @(x,y) sqrt(x.*y), ... @(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ; types = {'single', 'double'} ; for simd = [0 1] for d = 1:length(dists) for t = 1:length(types) vl_simdctrl(simd) ; X = feval(str2func(types{t}), s.X) ; Y = feval(str2func(types{t}), s.Y) ; vl_assert_almost_equal(... vl_alldist(X,Y,dists{d}), ... makedist(distsEquiv{d},X,Y), ... 1e-4, ... 'alldist failed for dist=%s type=%s simd=%d', ... dists{d}, ... types{t}, ... simd) ; end end end function test_distance_kernel_pairs(s) dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ; for d = 1:length(dists) dist = char(dists{d}) ; X = s.X ; Y = s.Y ; ker = ['k' dist] ; kxx = vl_alldist(X,X,ker) ; kyy = vl_alldist(Y,Y,ker) ; kxy = vl_alldist(X,Y,ker) ; kxx = repmat(diag(kxx), 1, size(s.Y,2)) ; kyy = repmat(diag(kyy), 1, size(s.X,1))' ; d2 = vl_alldist(X,Y,dist) ; vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ; end function D = makedist(cmp,X,Y) [d,m] = size(X) ; [d,n] = size(Y) ; D = zeros(m,n) ; for i = 1:m for j = 1:n acc = 0 ; for k = 1:d acc = acc + cmp(X(k,i),Y(k,j)) ; end D(i,j) = acc ; end end conv = str2func(class(X)) ; D = conv(D) ;
github
jianxiongxiao/ProfXkit-master
vl_test_ihashsum.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_ihashsum.m
581
utf_8
edc283062469af62056b0782b171f5fc
function results = vl_test_ihashsum(varargin) % VL_TEST_IHASHSUM vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(round(16*rand(2,100))) ; sel = find(all(s.data==0)) ; s.data(1,sel)=1 ; function test_hash(s) D = size(s.data,1) ; K = 5 ; h = zeros(1,K,'uint32') ; id = zeros(D,K,'uint8'); next = zeros(1,K,'uint32') ; [h,id,next] = vl_ihashsum(h,id,next,K,s.data) ; sel = vl_ihashfind(id,next,K,s.data) ; count = double(h(sel)) ; [drop,i,j] = unique(s.data','rows') ; for k=1:size(s.data,2) count_(k) = sum(j == j(k)) ; end vl_assert_equal(count,count_) ;
github
jianxiongxiao/ProfXkit-master
vl_test_grad.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_grad.m
434
utf_8
4d03eb33a6a4f68659f868da95930ffb
function results = vl_test_grad(varargin) % VL_TEST_GRAD vl_test_init ; function s = setup() s.I = rand(150,253) ; s.I_small = rand(2,2) ; function test_equiv(s) vl_assert_equal(gradient(s.I), vl_grad(s.I)) ; function test_equiv_small(s) vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ; function test_equiv_forward(s) Ix = diff(s.I,2,1) ; Iy = diff(s.I,2,1) ; vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_whistc.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_whistc.m
1,384
utf_8
81c446d35c82957659840ab2a579ec2c
function results = vl_test_whistc(varargin) % VL_TEST_WHISTC vl_test_init ; function test_acc() x = ones(1, 10) ; e = 1 ; o = 1:10 ; vl_assert_equal(vl_whistc(x, o, e), 55) ; function test_basic() x = 1:10 ; e = 1:10 ; o = ones(1, 10) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; x = linspace(-1,11,100) ; o = ones(size(x)) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; function test_multidim() x = rand(10, 20, 30) ; e = linspace(0,1,10) ; o = ones(size(x)) ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ; vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ; vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ; function test_nan() x = rand(10, 20, 30) ; e = linspace(0,1,10) ; o = ones(size(x)) ; x(1:7:end) = NaN ; vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ; vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ; vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ; vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ; function test_no_edges() x = rand(10, 20, 30) ; o = ones(size(x)) ; vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ; vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ; vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ; vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ; vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_roc.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_roc.m
1,019
utf_8
9b2ae71c9dc3eda0fc54c65d55054d0c
function results = vl_test_roc(varargin) % VL_TEST_ROC vl_test_init ; function s = setup() s.scores0 = [5 4 3 2 1] ; s.scores1 = [5 3 4 2 1] ; s.labels = [1 1 -1 -1 -1] ; function test_perfect_tptn(s) [tpr,tnr] = vl_roc(s.labels,s.scores0) ; vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ; function test_perfect_metrics(s) [tpr,tnr,info] = vl_roc(s.labels,s.scores0) ; vl_assert_almost_equal(info.eer, 0) ; vl_assert_almost_equal(info.auc, 1) ; function test_swap1_tptn(s) [tpr,tnr] = vl_roc(s.labels,s.scores1) ; vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ; function test_swap1_tptn_stable(s) [tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ; vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ; vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ; function test_swap1_metrics(s) [tpr,tnr,info] = vl_roc(s.labels,s.scores1) ; vl_assert_almost_equal(info.eer, 1/3) ; vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_dsift.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_dsift.m
2,048
utf_8
fbbfb16d5a21936c1862d9551f657ccc
function results = vl_test_dsift(varargin) % VL_TEST_DSIFT vl_test_init ; function s = setup() I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; s.I = rgb2gray(single(I)) ; function test_fast_slow(s) binSize = 4 ; % bin size in pixels magnif = 3 ; % bin size / keypoint scale scale = binSize / magnif ; windowSize = 5 ; [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors') ; [f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors', ... 'fast') ; error = std(d_(:) - d(:)) / std(d(:)) ; assert(error < 0.1, 'dsift fast approximation not close') ; function test_sift(s) binSize = 4 ; % bin size in pixels magnif = 3 ; % bin size / keypoint scale scale = binSize / magnif ; windowSizeRange = [1 1.2 5] ; for wi = 1:length(windowSizeRange) windowSize = windowSizeRange(wi) ; [f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ... 'size', binSize, ... 'step', 10, ... 'bounds', [20,20,210,140], ... 'windowsize', windowSize, ... 'floatdescriptors') ; numKeys = size(f, 2) ; f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ; [f_, d_] = vl_sift(s.I, ... 'magnif', magnif, ... 'frames', f_, ... 'firstoctave', -1, ... 'levels', 5, ... 'floatdescriptors', ... 'windowsize', windowSize) ; error = std(d_(:) - d(:)) / std(d(:)) ; assert(error < 0.1, 'dsift and sift equivalence') ; end
github
jianxiongxiao/ProfXkit-master
vl_test_alldist2.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_alldist2.m
2,284
utf_8
89a787e3d83516653ae8d99c808b9d67
function results = vl_test_alldist2(varargin) % VL_TEST_ALLDIST vl_test_init ; % TODO: test integer classes function s = setup() vl_twister('state', 0) ; s.X = 3.1 * vl_twister(10,10) ; s.Y = 4.7 * vl_twister(10,7) ; function test_null_args(s) vl_assert_equal(... vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ... zeros(12,0)) ; vl_assert_equal(... vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ... zeros(0,0)) ; vl_assert_equal(... vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ... zeros(0,12)) ; vl_assert_equal(... vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ... zeros(15,12)) ; function test_self(s) vl_assert_almost_equal(... vl_alldist2(s.X, 'kl2'), ... makedist(@(x,y) x*y, s.X, s.X), ... 1e-6) ; function test_distances(s) dists = {'chi2', 'l2', 'l1', 'hell', ... 'kchi2', 'kl2', 'kl1', 'khell'} ; distsEquiv = { ... @(x,y) (x-y)^2 / (x + y), ... @(x,y) (x-y)^2, ... @(x,y) abs(x-y), ... @(x,y) (sqrt(x) - sqrt(y))^2, ... @(x,y) 2 * (x*y) / (x + y), ... @(x,y) x*y, ... @(x,y) min(x,y), ... @(x,y) sqrt(x.*y)}; types = {'single', 'double', 'sparse'} ; for simd = [0 1] for d = 1:length(dists) for t = 1:length(types) vl_simdctrl(simd) ; X = feval(str2func(types{t}), s.X) ; Y = feval(str2func(types{t}), s.Y) ; a = vl_alldist2(X,Y,dists{d}) ; b = makedist(distsEquiv{d},X,Y) ; vl_assert_almost_equal(a,b, ... 1e-4, ... 'alldist failed for dist=%s type=%s simd=%d', ... dists{d}, ... types{t}, ... simd) ; end end end function test_distance_kernel_pairs(s) dists = {'chi2', 'l2', 'l1', 'hell'} ; for d = 1:length(dists) dist = char(dists{d}) ; X = s.X ; Y = s.Y ; ker = ['k' dist] ; kxx = vl_alldist2(X,X,ker) ; kyy = vl_alldist2(Y,Y,ker) ; kxy = vl_alldist2(X,Y,ker) ; kxx = repmat(diag(kxx), 1, size(s.Y,2)) ; kyy = repmat(diag(kyy), 1, size(s.X,1))' ; d2 = vl_alldist2(X,Y,dist) ; vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ; end function D = makedist(cmp,X,Y) [d,m] = size(X) ; [d,n] = size(Y) ; D = zeros(m,n) ; for i = 1:m for j = 1:n acc = 0 ; for k = 1:d acc = acc + cmp(X(k,i),Y(k,j)) ; end D(i,j) = acc ; end end conv = str2func(class(X)) ; D = conv(D) ;
github
jianxiongxiao/ProfXkit-master
vl_test_fisher.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_fisher.m
1,703
utf_8
41b28dce7f0d0ae5cb6abd942acbef56
function results = vl_test_fisher(varargin) % VL_TEST_FISHER vl_test_init ; function s = setup() randn('state',0) ; dimension = 5 ; numData = 21 ; numComponents = 3 ; s.x = randn(dimension,numData) ; s.mu = randn(dimension,numComponents) ; s.sigma2 = ones(dimension,numComponents) ; s.prior = ones(1,numComponents) ; s.prior = s.prior / sum(s.prior) ; function test_basic(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_norm(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_sqrt(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function test_improved(s) phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ; vl_assert_almost_equal(phi, phi_, 1e-10) ; function enc = simple_fisher(x, mu, sigma2, pri) sigma = sqrt(sigma2) ; for i = 1:size(mu,2) delta{i} = bsxfun(@times, bsxfun(@minus, x, mu(:,i)), 1./sigma(:,i)) ; q(i,:) = log(pri(i)) - 0.5 * log(sigma2(i)) - 0.5 * sum(delta{i}.^2,1) ; end q = exp(bsxfun(@minus, q, max(q,[],1))) ; q = bsxfun(@times, q, 1 ./ sum(q,1)) ; n = size(x,2) ; for i = 1:size(mu,2) u{i} = delta{i} * q(i,:)' / n / sqrt(pri(i)) ; v{i} = (delta{i}.^2 - 1) * q(i,:)' / n / sqrt(2*pri(i)) ; end enc = cat(1, u{:}, v{:}) ;
github
jianxiongxiao/ProfXkit-master
vl_test_imsmooth.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_imsmooth.m
1,837
utf_8
718235242cad61c9804ba5e881c22f59
function results = vl_test_imsmooth(varargin) % VL_TEST_IMSMOOTH vl_test_init ; function s = setup() I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; I = max(min(vl_imdown(I),1),0) ; s.I = single(I) ; function test_pad_by_continuity(s) % Convolving a constant signal padded with continuity does not change % the signal. I = ones(3) ; for ker = {'triangular', 'gaussian'} ker = char(ker) ; J = vl_imsmooth(I, 2, ... 'kernel', ker, ... 'padding', 'continuity') ; vl_assert_almost_equal(J, I, 1e-4, ... 'padding by continutiy with kernel = %s', ker) ; end function test_kernels(s) for ker = {'triangular', 'gaussian'} ker = char(ker) ; for type = {@single, @double} for simd = [0 1] for sigma = [1 2 7] for step = [1 2 3] vl_simdctrl(simd) ; conv = type{1} ; g = equivalent_kernel(ker, sigma) ; J = vl_imsmooth(conv(s.I), sigma, ... 'kernel', ker, ... 'padding', 'zero', ... 'subsample', step) ; J_ = conv(convolve(s.I, g, step)) ; vl_assert_almost_equal(J, J_, 1e-4, ... 'kernel=%s sigma=%f step=%d simd=%d', ... ker, sigma, step, simd) ; end end end end end function g = equivalent_kernel(ker, sigma) switch ker case 'gaussian' W = ceil(4*sigma) ; g = exp(-.5*((-W:W)/(sigma+eps)).^2) ; case 'triangular' W = max(round(sigma),1) ; g = W - abs(-W+1:W-1) ; end g = g / sum(g) ; function I = convolve(I, g, step) if strcmp(class(I),'single') g = single(g) ; else g = double(g) ; end for k=1:size(I,3) I(:,:,k) = conv2(g,g,I(:,:,k),'same'); end I = I(1:step:end,1:step:end,:) ;
github
jianxiongxiao/ProfXkit-master
vl_test_svmtrain.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_svmtrain.m
4,277
utf_8
071b7c66191a22e8236fda16752b27aa
function results = vl_test_svmtrain(varargin) % VL_TEST_SVMTRAIN vl_test_init ; end function s = setup() randn('state',0) ; Np = 10 ; Nn = 10 ; xp = diag([1 3])*randn(2, Np) ; xn = diag([1 3])*randn(2, Nn) ; xp(1,:) = xp(1,:) + 2 + 1 ; xn(1,:) = xn(1,:) - 2 + 1 ; s.x = [xp xn] ; s.y = [ones(1,Np) -ones(1,Nn)] ; s.lambda = 0.01 ; s.biasMultiplier = 10 ; if 0 figure(1) ; clf; vl_plotframe(xp, 'g') ; hold on ; vl_plotframe(xn, 'r') ; axis equal ; grid on ; end % Run LibSVM as an accuate solver to compare results with. Note that % LibSVM optimizes a slightly different cost function due to the way % the bias is handled. % [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ; s.w = [1.180762951236242; 0.098366470721632] ; s.b = -1.540018443946204 ; s.obj = obj(s, s.w, s.b) ; end function test_sgd_basic(s) for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ... 'Solver', 'sgd', ... 'BiasMultiplier', s.biasMultiplier, ... 'BiasLearningRate', 1/s.biasMultiplier, ... 'MaxNumIterations', 1e5, ... 'Epsilon', 1e-3) ; % there are no absolute guarantees on the objective gap, but % the heuristic SGD uses as stopping criterion seems reasonable % within a factor 10 at least. o = obj(s, w, b) ; gap = o - s.obj ; vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ; assert(gap <= 1e-2) ; end end function test_sdca_basic(s) for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; [w b info] = vl_svmtrain(s.x, s.y, s.lambda, ... 'Solver', 'sdca', ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e5, ... 'Epsilon', 1e-3) ; % the gap with the accurate solver cannot be % greater than the duality gap. o = obj(s, w, b) ; gap = o - s.obj ; vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ; assert(gap <= 1e-3) ; end end function test_weights(s) for algo = {'sgd', 'sdca'} for conv = {@single, @double} conv = conv{1} ; vl_twister('state',0) ; numRepeats = 10 ; pos = find(s.y > 0) ; neg = find(s.y < 0) ; weights = ones(1, numel(s.y)) ; weights(pos) = numRepeats ; % simulate weighting by repeating positives [w b info] = vl_svmtrain(... s.x(:, [repmat(pos,1,numRepeats) neg]), ... s.y(:, [repmat(pos,1,numRepeats) neg]), ... s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ... 'Solver', 'sdca', ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e6, ... 'Epsilon', 1e-4) ; % apply weigthing [w_ b_ info_] = vl_svmtrain(... s.x, ... s.y, ... s.lambda, ... 'Solver', char(algo), ... 'BiasMultiplier', s.biasMultiplier, ... 'MaxNumIterations', 1e6, ... 'Epsilon', 1e-4, ... 'Weights', weights) ; vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ; end end end function test_homkermap(s) for solver = {'sgd', 'sdca'} for conv = {@single,@double} conv = conv{1} ; dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ; vl_twister('state',0) ; [w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ; x_hom = vl_homkermap(conv(s.x), 1) ; vl_twister('state',0) ; [w b] = vl_svmtrain(x_hom, s.y, s.lambda) ; vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ; end end end function [w,b] = accurate_solver(X, y, lambda, biasMultiplier) addpath opt/libsvm/matlab/ N = size(X,2) ; model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ; w = X(:,model.SVs) * model.sv_coef ; b = - model.rho ; format long ; disp('model w:') disp(w) disp('bias b:') disp(b) end function o = obj(s, w, b) o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ; end
github
jianxiongxiao/ProfXkit-master
vl_test_phow.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_phow.m
549
utf_8
f761a3bb218af855986263c67b2da411
function results = vl_test_phow(varargin) % VL_TEST_PHOPW vl_test_init ; function s = setup() s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ; s.I = single(s.I) ; function test_gray(s) [f,d] = vl_phow(s.I, 'color', 'gray') ; assert(size(d,1) == 128) ; function test_rgb(s) [f,d] = vl_phow(s.I, 'color', 'rgb') ; assert(size(d,1) == 128*3) ; function test_hsv(s) [f,d] = vl_phow(s.I, 'color', 'hsv') ; assert(size(d,1) == 128*3) ; function test_opponent(s) [f,d] = vl_phow(s.I, 'color', 'opponent') ; assert(size(d,1) == 128*3) ;
github
jianxiongxiao/ProfXkit-master
vl_test_kmeans.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_kmeans.m
3,632
utf_8
719f7fca81e19eed5cc45c2ca251aad0
function results = vl_test_kmeans(varargin) % VL_TEST_KMEANS % Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson. % All rights reserved. % % This file is part of the VLFeat library and is made available under % the terms of the BSD license (see the COPYING file). vl_test_init ; function s = setup() randn('state',0) ; s.X = randn(128, 100) ; function test_basic(s) [centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ; [centers_, assignments_, en_] = simpleKMeans(s.X, 10) ; assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ; function test_algorithms(s) distances = {'l1', 'l2'} ; dataTypes = {'single','double'} ; for dataType = dataTypes for distance = distances distance = char(distance) ; conversion = str2func(char(dataType)) ; X = conversion(s.X) ; vl_twister('state',0) ; [centers, assignments, en] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'Lloyd', ... 'Distance', distance) ; vl_twister('state',0) ; [centers_, assignments_, en_] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'Elkan', ... 'Distance', distance) ; vl_twister('state',0) ; [centers__, assignments__, en__] = vl_kmeans(X, 10, ... 'NumRepetitions', 1, ... 'MaxNumIterations', 10, ... 'Algorithm', 'ANN', ... 'Distance', distance, ... 'NumTrees', 3, ... 'MaxNumComparisons',0) ; vl_assert_almost_equal(centers, centers_, 1e-5) ; vl_assert_almost_equal(assignments, assignments_, 1e-5) ; vl_assert_almost_equal(en, en_, 1e-5) ; vl_assert_almost_equal(centers, centers__, 1e-5) ; vl_assert_almost_equal(assignments, assignments__, 1e-5) ; vl_assert_almost_equal(en, en__, 1e-5) ; vl_assert_almost_equal(centers_, centers__, 1e-5) ; vl_assert_almost_equal(assignments_, assignments__, 1e-5) ; vl_assert_almost_equal(en_, en__, 1e-5) ; end end function test_patterns(s) distances = {'l1', 'l2'} ; dataTypes = {'single','double'} ; for dataType = dataTypes for distance = distances distance = char(distance) ; conversion = str2func(char(dataType)) ; data = [1 1 0 0 ; 1 0 1 0] ; data = conversion(data) ; [centers, assignments, en] = vl_kmeans(data, 4, ... 'NumRepetitions', 100, ... 'Distance', distance) ; assert(isempty(setdiff(data', centers', 'rows'))) ; end end function [centers, assignments, en] = simpleKMeans(X, numCenters) [dimension, numData] = size(X) ; centers = randn(dimension, numCenters) ; for iter = 1:10 [dists, assignments] = min(vl_alldist(centers, X)) ; en = sum(dists) ; centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ; centers = vl_binsum(centers, ... [X ; ones(1,numData)], ... repmat(assignments, dimension+1, 1), 2) ; centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ; end
github
jianxiongxiao/ProfXkit-master
vl_test_hikmeans.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_hikmeans.m
463
utf_8
dc3b493646e66316184e86ff4e6138ab
function results = vl_test_hikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [tree, assign] = vl_hikmeans(s.data,3,100) ; assign_ = vl_hikmeanspush(tree, s.data) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ; assign_ = vl_hikmeanspush(tree, s.data) ; vl_assert_equal(assign,assign_) ;
github
jianxiongxiao/ProfXkit-master
vl_test_aib.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_aib.m
1,277
utf_8
78978ae54e7ebe991d136336ba4bf9c6
function results = vl_test_aib(varargin) % VL_TEST_AIB vl_test_init ; function s = setup() s = [] ; function test_basic(s) Pcx = [.3 .3 0 0 0 0 .2 .2] ; % This results in the AIB tree % % 1 - \ % 5 - \ % 2 - / \ % - 7 % 3 - \ / % 6 - / % 4 - / % % coded by the map [5 5 6 6 7 1] (1 denotes the root). [parents,cost] = vl_aib(Pcx) ; vl_assert_equal(parents, [5 5 6 6 7 7 1]) ; vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ; [cut,map,short] = vl_aibcut(parents,2) ; vl_assert_equal(cut, [5 6]) ; vl_assert_equal(map, [1 1 2 2 1 2 0]) ; vl_assert_equal(short, [5 5 6 6 5 6 7]) ; function test_cluster_null(s) Pcx = [.5 .5 0 0 0 0 0 0] ; % This results in the AIB tree % % 1 - \ % 5 % 2 - / % % 3 x % % 4 x % % If ClusterNull is specified, the values 3 and 4 % which have zero probability are merged first % % 1 ----------\ % 7 % 2 ----- \ / % 6-/ % 3 -\ / % 5 -/ % 4 -/ parents1 = vl_aib(Pcx) ; parents2 = vl_aib(Pcx,'ClusterNull') ; vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ; vl_assert_equal(parents2(3), parents2(4)) ; function x = mi(P) % mutual information P1 = sum(P,1) ; P2 = sum(P,2) ; x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
github
jianxiongxiao/ProfXkit-master
vl_test_plotbox.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_plotbox.m
414
utf_8
aa06ce4932a213fb933bbede6072b029
function results = vl_test_plotbox(varargin) % VL_TEST_PLOTBOX vl_test_init ; function test_basic(s) figure(1) ; clf ; vl_plotbox([-1 -1 1 1]') ; xlim([-2 2]) ; ylim([-2 2]) ; close(1) ; function test_multiple(s) figure(1) ; clf ; randn('state', 0) ; vl_plotbox(randn(4,10)) ; close(1) ; function test_style(s) figure(1) ; clf ; randn('state', 0) ; vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ; close(1) ;
github
jianxiongxiao/ProfXkit-master
vl_test_imarray.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_imarray.m
795
utf_8
c5e6a5aa8c2e63e248814f5bd89832a8
function results = vl_test_imarray(varargin) % VL_TEST_IMARRAY vl_test_init ; function test_movie_rgb(s) A = rand(23,15,3,4) ; B = vl_imarray(A,'movie',true) ; function test_movie_indexed(s) cmap = get(0,'DefaultFigureColormap') ; A = uint8(size(cmap,1)*rand(23,15,4)) ; A = min(A,size(cmap,1)-1) ; B = vl_imarray(A,'movie',true) ; function test_movie_gray_indexed(s) A = uint8(255*rand(23,15,4)) ; B = vl_imarray(A,'movie',true,'cmap',gray(256)) ; for k=1:size(A,3) vl_assert_equal(squeeze(A(:,:,k)), ... frame2im(B(k))) ; end function test_basic(s) M = 3 ; N = 4 ; width = 32 ; height = 15 ; for i=1:M for j=1:N A{i,j} = rand(width,height) ; end end A1 = A'; A1 = cat(3,A1{:}) ; A2 = cell2mat(A) ; B = vl_imarray(A1, 'layout', [M N]) ; vl_assert_equal(A2,B) ;
github
jianxiongxiao/ProfXkit-master
vl_test_homkermap.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_homkermap.m
1,903
utf_8
c157052bf4213793a961bde1f73fb307
function results = vl_test_homkermap(varargin) % VL_TEST_HOMKERMAP vl_test_init ; function check_ker(ker, n, window, period) args = {n, ker, 'window', window} ; if nargin > 3 args = {args{:}, 'period', period} ; end x = [-1 -.5 0 .5 1] ; y = linspace(0,2,100) ; for conv = {@single, @double} x = feval(conv{1}, x) ; y = feval(conv{1}, y) ; sx = sign(x) ; sy = sign(y) ; psix = vl_homkermap(x, args{:}) ; psiy = vl_homkermap(y, args{:}) ; k = vl_alldist(psix,psiy,'kl2') ; k_ = (sx'*sy) .* vl_alldist(sx.*x,sy.*y,ker) ; vl_assert_almost_equal(k, k_, 2e-2) ; end function test_uniform_kchi2(), check_ker('kchi2', 3, 'uniform', 15) ; function test_uniform_kjs(), check_ker('kjs', 3, 'uniform', 15) ; function test_uniform_kl1(), check_ker('kl1', 29, 'uniform', 15) ; function test_rect_kchi2(), check_ker('kchi2', 3, 'rectangular', 15) ; function test_rect_kjs(), check_ker('kjs', 3, 'rectangular', 15) ; function test_rect_kl1(), check_ker('kl1', 29, 'rectangular', 10) ; function test_auto_uniform_kchi2(),check_ker('kchi2', 3, 'uniform') ; function test_auto_uniform_kjs(), check_ker('kjs', 3, 'uniform') ; function test_auto_uniform_kl1(), check_ker('kl1', 25, 'uniform') ; function test_auto_rect_kchi2(), check_ker('kchi2', 3, 'rectangular') ; function test_auto_rect_kjs(), check_ker('kjs', 3, 'rectangular') ; function test_auto_rect_kl1(), check_ker('kl1', 25, 'rectangular') ; function test_gamma() x = linspace(0,1,20) ; for gamma = linspace(.2,2,10) k = vl_alldist(x, 'kchi2') .* (x'*x + 1e-12).^((gamma-1)/2) ; psix = vl_homkermap(x, 3, 'kchi2', 'gamma', gamma) ; assert(norm(k - psix'*psix) < 1e-2) ; end function test_negative() x = linspace(-1,1,20) ; k = vl_alldist(abs(x), 'kchi2') .* (sign(x)'*sign(x)) ; psix = vl_homkermap(x, 3, 'kchi2') ; assert(norm(k - psix'*psix) < 1e-2) ;
github
jianxiongxiao/ProfXkit-master
vl_test_slic.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_slic.m
200
utf_8
12a6465e3ef5b4bcfd7303cd8a9229d4
function results = vl_test_slic(varargin) % VL_TEST_SLIC vl_test_init ; function s = setup() s.im = im2single(vl_impattern('roofs1')) ; function test_slic(s) segmentation = vl_slic(s.im, 10, 0.1) ;
github
jianxiongxiao/ProfXkit-master
vl_test_ikmeans.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_ikmeans.m
466
utf_8
1ee2f647ac0035ed0d704a0cd615b040
function results = vl_test_ikmeans(varargin) % VL_TEST_IKMEANS vl_test_init ; function s = setup() rand('state',0) ; s.data = uint8(rand(2,1000) * 255) ; function test_basic(s) [centers, assign] = vl_ikmeans(s.data,100) ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ; function test_elkan(s) [centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ; assign_ = vl_ikmeanspush(s.data, centers) ; vl_assert_equal(assign,assign_) ;
github
jianxiongxiao/ProfXkit-master
vl_test_mser.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_mser.m
242
utf_8
1ad33563b0c86542a2978ee94e0f4a39
function results = vl_test_mser(varargin) % VL_TEST_MSER vl_test_init ; function s = setup() s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ; function test_mser(s) [regions,frames] = vl_mser(s.im) ; mask = vl_erfill(s.im, regions(1)) ;
github
jianxiongxiao/ProfXkit-master
vl_test_inthist.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_inthist.m
811
utf_8
459027d0c54d8f197563a02ab66ef45d
function results = vl_test_inthist(varargin) % VL_TEST_INTHIST vl_test_init ; function s = setup() rand('state',0) ; s.labels = uint32(8*rand(123, 76, 3)) ; function test_basic(s) l = 10 ; hist = vl_inthist(s.labels, 'numlabels', l) ; hist_ = inthist_slow(s.labels, l) ; vl_assert_equal(double(hist),hist_) ; function test_sample(s) rand('state',0) ; boxes = 10 * rand(4,20) + .5 ; boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ; boxes = min(boxes, 10) ; boxes = uint32(boxes) ; inthist = vl_inthist(s.labels) ; hist = vl_sampleinthist(inthist, boxes) ; function hist = inthist_slow(labels, numLabels) m = size(labels,1) ; n = size(labels,2) ; l = numLabels ; b = zeros(m*n,l) ; b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ; b = reshape(b,m,n,l) ; for k=1:l hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ; end
github
jianxiongxiao/ProfXkit-master
vl_test_imdisttf.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_imdisttf.m
1,885
utf_8
ae921197988abeb984cbcdf9eaf80e77
function results = vl_test_imdisttf(varargin) % VL_TEST_DISTTF vl_test_init ; function test_basic() for conv = {@single, @double} conv = conv{1} ; I = conv([0 0 0 ; 0 -2 0 ; 0 0 0]) ; D = vl_imdisttf(I); assert(isequal(D, conv(- [0 1 0 ; 1 2 1 ; 0 1 0]))) ; I(2,2) = -3 ; [D,map] = vl_imdisttf(I) ; assert(isequal(D, conv(-1 - [0 1 0 ; 1 2 1 ; 0 1 0]))) ; assert(isequal(map, 5 * ones(3))) ; end function test_1x1() assert(isequal(1, vl_imdisttf(1))) ; function test_rand() I = rand(13,31) ; for t=1:4 param = [rand randn rand randn] ; [D0,map0] = imdisttf_equiv(I,param) ; [D,map] = vl_imdisttf(I,param) ; vl_assert_almost_equal(D,D0,1e-10) assert(isequal(map,map0)) ; end function test_param() I = zeros(3,4) ; I(1,1) = -1 ; [D,map] = vl_imdisttf(I,[1 0 1 0]); assert(isequal(-[1 0 0 0 ; 0 0 0 0 ; 0 0 0 0 ;], D)) ; D0 = -[1 .9 .6 .1 ; 0 0 0 0 ; 0 0 0 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[1 .9 .6 .1 ; .9 .8 .5 0 ; .6 .5 .2 0 ;] ; [D,map] = vl_imdisttf(I,[.1 0 .1 0]); vl_assert_almost_equal(D,D0,1e-10); D0 = -[.9 1 .9 .6 ; .8 .9 .8 .5 ; .5 .6 .5 .2 ; ] ; [D,map] = vl_imdisttf(I,[.1 1 .1 0]); vl_assert_almost_equal(D,D0,1e-10); function test_special() I = rand(13,31) -.5 ; D = vl_imdisttf(I, [0 0 1e5 0]) ; vl_assert_almost_equal(D(:,1),min(I,[],2),1e-10); D = vl_imdisttf(I, [1e5 0 0 0]) ; vl_assert_almost_equal(D(1,:),min(I,[],1),1e-10); function [D,map]=imdisttf_equiv(I,param) D = inf + zeros(size(I)) ; map = zeros(size(I)) ; ur = 1:size(D,2) ; vr = 1:size(D,1) ; [u,v] = meshgrid(ur,vr) ; for v_=vr for u_=ur E = I(v_,u_) + ... param(1) * (u - u_ - param(2)).^2 + ... param(3) * (v - v_ - param(4)).^2 ; map(E < D) = sub2ind(size(I),v_,u_) ; D = min(D,E) ; end end
github
jianxiongxiao/ProfXkit-master
vl_test_vlad.m
.m
ProfXkit-master/align2RGBD/align2RGBD/lib/vlfeat/toolbox/xtest/vl_test_vlad.m
1,977
utf_8
d3797288d6edb1d445b890db3780c8ce
function results = vl_test_vlad(varargin) % VL_TEST_VLAD vl_test_init ; function s = setup() randn('state',0) ; s.x = randn(128,256) ; s.mu = randn(128,16) ; assignments = rand(16, 256) ; s.assignments = bsxfun(@times, assignments, 1 ./ sum(assignments,1)) ; function test_basic (s) x = [1, 2, 3] ; mu = [0, 0, 0] ; assignments = eye(3) ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 2 3]') ; mu = [0, 1, 2] ; phi = vl_vlad(x, mu, assignments, 'unnormalized') ; vl_assert_equal(phi, [1 1 1]') ; phi = vl_vlad([x x], mu, [assignments assignments], 'unnormalized') ; vl_assert_equal(phi, [2 2 2]') ; function test_rand (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized') ; vl_assert_equal(phi, phi_) ; function test_norm (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments) ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_sqrt (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = sign(phi_) .* sqrt(abs(phi_)) ; phi_ = phi_ / norm(phi_) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'squareroot') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_individual (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sqrt(sum(phi_.^2))) ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizecomponents') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function test_mass (s) phi_ = simple_vlad(s.x, s.mu, s.assignments) ; phi_ = reshape(phi_, size(s.x,1), []) ; phi_ = bsxfun(@times, phi_, 1 ./ sum(s.assignments,2)') ; phi_ = phi_(:) ; phi = vl_vlad(s.x, s.mu, s.assignments, 'unnormalized', 'normalizemass') ; vl_assert_almost_equal(phi, phi_, 1e-4) ; function enc = simple_vlad(x, mu, assign) for i = 1:size(assign,1) enc{i} = x * assign(i,:)' - sum(assign(i,:)) * mu(:,i) ; end enc = cat(1, enc{:}) ;