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_pr.m
|
.m
|
ProfXkit-master/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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/align2RGBD/align2RGBD/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
|
parseXMLstring.m
|
.m
|
ProfXkit-master/MatlabTurkTool/parseXMLstring.m
| 7,033 |
utf_8
|
7de86ff84d643a943e5ec4bc4a3cf2cb
|
function object = parseXMLstring(str)
fname = [tempname '.xml'];
fp = fopen(fname,'w');
fprintf(fp,'%s',str);
fclose(fp);
object = xml2struct(fname);
delete(fname);
end
% downloaded from http://www.mathworks.com/matlabcentral/fileexchange/28518-xml2struct
function [ s ] = xml2struct( file )
%Convert xml file into a MATLAB structure
% [ s ] = xml2struct( file )
%
% A file containing:
% <XMLname attrib1="Some value">
% <Element>Some text</Element>
% <DifferentElement attrib2="2">Some more text</Element>
% <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement>
% </XMLname>
%
% Will produce:
% s.XMLname.Attributes.attrib1 = "Some value";
% s.XMLname.Element.Text = "Some text";
% s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2";
% s.XMLname.DifferentElement{1}.Text = "Some more text";
% s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2";
% s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1";
% s.XMLname.DifferentElement{2}.Text = "Even more text";
%
% Please note that the following characters are substituted
% '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_'
%
% Written by W. Falkena, ASTI, TUDelft, 21-08-2010
% Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011
% Added CDATA support by I. Smirnov, 20-3-2012
%
% Modified by X. Mo, University of Wisconsin, 12-5-2012
if (nargin < 1)
clc;
help xml2struct
return
end
if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl')
% input is a java xml object
xDoc = file;
else
%check for existance
if (exist(file,'file') == 0)
%Perhaps the xml extension was omitted from the file name. Add the
%extension and try again.
if (isempty(strfind(file,'.xml')))
file = [file '.xml'];
end
if (exist(file,'file') == 0)
error(['The file ' file ' could not be found']);
end
end
%read the xml file
xDoc = xmlread(file);
end
%parse xDoc into a MATLAB structure
s = parseChildNodes(xDoc);
end
% ----- Subfunction parseChildNodes -----
function [children,ptext,textflag] = parseChildNodes(theNode)
% Recurse over node children.
children = struct;
ptext = struct; textflag = 'Text';
if hasChildNodes(theNode)
childNodes = getChildNodes(theNode);
numChildNodes = getLength(childNodes);
for count = 1:numChildNodes
theChild = item(childNodes,count-1);
[text,name,attr,childs,textflag] = getNodeData(theChild);
if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section'))
%XML allows the same elements to be defined multiple times,
%put each in a different cell
if (isfield(children,name))
if (~iscell(children.(name)))
%put existsing element into cell format
children.(name) = {children.(name)};
end
index = length(children.(name))+1;
%add new element
children.(name){index} = childs;
if(~isempty(fieldnames(text)))
children.(name){index} = text;
end
if(~isempty(attr))
children.(name){index}.('Attributes') = attr;
end
else
%add previously unknown (new) element to the structure
children.(name) = childs;
if(~isempty(text) && ~isempty(fieldnames(text)))
children.(name) = text;
end
if(~isempty(attr))
children.(name).('Attributes') = attr;
end
end
else
ptextflag = 'Text';
if (strcmp(name, '#cdata_dash_section'))
ptextflag = 'CDATA';
elseif (strcmp(name, '#comment'))
ptextflag = 'Comment';
end
%this is the text in an element (i.e., the parentNode)
if (~isempty(regexprep(text.(textflag),'[\s]*','')))
if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag)))
ptext.(ptextflag) = text.(textflag);
else
%what to do when element data is as follows:
%<element>Text <!--Comment--> More text</element>
%put the text in different cells:
% if (~iscell(ptext)) ptext = {ptext}; end
% ptext{length(ptext)+1} = text;
%just append the text
ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)];
end
end
end
end
end
end
% ----- Subfunction getNodeData -----
function [text,name,attr,childs,textflag] = getNodeData(theNode)
% Create structure of node info.
%make sure name is allowed as structure name
name = toCharArray(getNodeName(theNode))';
name = strrep(name, '-', '_dash_');
name = strrep(name, ':', '_colon_');
name = strrep(name, '.', '_dot_');
attr = parseAttributes(theNode);
if (isempty(fieldnames(attr)))
attr = [];
end
%parse child nodes
[childs,text,textflag] = parseChildNodes(theNode);
if (isempty(fieldnames(childs)) && isempty(fieldnames(text)))
%get the data of any childless nodes
% faster than if any(strcmp(methods(theNode), 'getData'))
% no need to try-catch (?)
% faster than text = char(getData(theNode));
text.(textflag) = toCharArray(getTextContent(theNode))';
end
end
% ----- Subfunction parseAttributes -----
function attributes = parseAttributes(theNode)
% Create attributes structure.
attributes = struct;
if hasAttributes(theNode)
theAttributes = getAttributes(theNode);
numAttributes = getLength(theAttributes);
for count = 1:numAttributes
%attrib = item(theAttributes,count-1);
%attr_name = regexprep(char(getName(attrib)),'[-:.]','_');
%attributes.(attr_name) = char(getValue(attrib));
%Suggestion of Adrian Wanner
str = toCharArray(toString(item(theAttributes,count-1)))';
k = strfind(str,'=');
attr_name = str(1:(k(1)-1));
attr_name = strrep(attr_name, '-', '_dash_');
attr_name = strrep(attr_name, ':', '_colon_');
attr_name = strrep(attr_name, '.', '_dot_');
attributes.(attr_name) = str((k(1)+2):(end-1));
end
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
HMACencode.m
|
.m
|
ProfXkit-master/MatlabTurkTool/HMACencode.m
| 879 |
utf_8
|
208b549fd6a8159bbf99373ddf26346f
|
function encodedHMAC = HMACencode(str,key)
%encodedHMAC = urlEncode(doHMAC_SHA1(str, key));
encodedHMAC = doHMAC_SHA1(str, key);
end
function signStr = doHMAC_SHA1(str, key)
import java.net.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import org.apache.commons.codec.binary.*
algorithm = 'HmacSHA1';
keyStr = java.lang.String(key);
key = SecretKeySpec(keyStr.getBytes(), algorithm);
mac = Mac.getInstance(algorithm);
mac.init(key);
toSignStr = java.lang.String(str);
bytes = toSignStr.getBytes();
signStr = java.lang.String(Base64.encodeBase64(mac.doFinal(bytes)));
signStr = (signStr.toCharArray())';
signStr = strrep(signStr, '\n', '');
signStr = strrep(signStr, '\r', '');
end
function encodedStr = urlEncode(str)
import java.net.*;
encoded = URLEncoder.encode(str, 'UTF-8');
encodedStr = (encoded.toCharArray())';
encodedStr = strrep(encodedStr, '+', '%20');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
queryFlickrApi.m
|
.m
|
ProfXkit-master/querySearchEngine/queryFlickrApi.m
| 5,548 |
utf_8
|
0ca6a2d4afe92bd519260dfb228ddeba
|
function result = queryFlickrApi(original_keywords)
% example usage: result = queryFlickrApi();
% information: see flickr api page: https://www.flickr.com/services/api/
% https://www.flickr.com/services/api/explore/flickr.photos.search
if ~exist('original_keywords','var')
original_keywords = 'living room';
end
apiURL = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=d10c081d41108144231911c96fcfe4c9&text=%s&page=%d&per_page=500';
%urlPhoto = 'http://farm%s.static.flickr.com/%s/%s_%s_b.jpg';
%sprintf(urlPhoto,farm_id,server_id,photo_id,secret_id);
query = urlencode(original_keywords);
query = regexprep(query,'%E2%80%8B',''); %<- strange bug
result = [];
page = 1;
pageCnt = 1;
while true
link = sprintf(apiURL,query,page);
strXML = urlread(link);
if page==1
str = strXML;
pos = findstr(str,'pages="');
if isempty(pos)
break;
else
str = str(pos(1)+length('pages="'):end);
pos = findstr(str,'"');
str = str(1:pos(1)-1);
pageCnt = str2num(str);
if pageCnt==0
break;
end
%if pageCnt > 200 && (length(findstr(original_keywords,' '))+1)==1
% pageCnt = 11;
%end
% http://www.flickr.com/groups/api/discuss/72157600679839291/
% you cannot get more than 5k images from flickr
if pageCnt >11
pageCnt = 11;
end
end
end
resultNow = parseFlickr(strXML, original_keywords);
result = [result; resultNow];
%{
fname = [tempname '.xml'];
fp = fopen(fname,'w');
fprintf(fp,'%s',strXML);
fclose(fp);
outObj = readFlickrObj(fname, original_keywords);
delete(fname);
%}
if page >=pageCnt
break;
end
page = page+1;
end
function result = parseFlickr(strXML, keywords)
ids = regexp(strXML,'(<photo id=")[^"]+(")','match');
owners = regexp(strXML,'(owner=")[^"]+(")','match');
secrets = regexp(strXML,'(secret=")[^"]+(")','match');
servers = regexp(strXML,'(server=")[^"]+(")','match');
farms = regexp(strXML,'(farm=")[^"]+(")','match');
titles = regexp(strXML,'(title=")[^"]*(")','match');
%ispublic = regexp(strXML,'(ispublic=")[^"]+(")','match');
%isfriend = regexp(strXML,'(isfriend=")[^"]+(")','match');
%isfamily = regexp(strXML,'(isfamily=")[^"]+(")','match');
urlPhoto = 'http://farm%s.static.flickr.com/%s/%s_%s_b.jpg';
result = cell(length(ids),2);
for i=1:length(ids)
id = regexp(ids{i},'"','split'); id = id{2};
owner = regexp(owners{i},'"','split'); owner = owner{2};
secret = regexp(secrets{i},'"','split'); secret = secret{2};
server = regexp(servers{i},'"','split'); server = server{2};
farm = regexp(farms{i},'"','split'); farm = farm{2};
title = regexp(titles{i},'"','split'); title = title{2};
url = sprintf(urlPhoto,farm,server,id,secret);
info = [ '{' ...
'"keywrods": "' strrep(strrep(strrep(keywords,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"url": "' url '", ' ...
'"id": "' id '", ' ...
'"owner": "' owner '", ' ...
'"secret": "' secret '", ' ...
'"server": "' server '", ' ...
'"farm": "' farm '", ' ...
'"title": "' title '" }'];
result{i,1} = info;
result{i,2} = url;
end
%{
function download(url, fname)
downloadTemplate = 'wget --tries=2 --timeout=5 "%s" --user-agent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6" -O "%s"';
cmd = sprintf(downloadTemplate, url, fname);
system(cmd);
%}
%{
function fileStr = file2string(fname)
fileStr = '';
fid = fopen(fname,'r');
tline = fgetl(fid);
while ischar(tline)
fileStr = [fileStr sprintf('\n') tline];
tline = fgetl(fid);
end
fclose(fid);
%}
%{
function outObj = readFlickrObj(inFname, keywords)
urlPhoto = 'http://farm%s.static.flickr.com/%s/%s_%s_b.jpg';
xDoc = xmlread(inFname);
allImages = xDoc.getElementsByTagName('photo');
for k = 0:allImages.getLength-1
thisImage = allImages.item(k);
id = char(thisImage.getAttribute('id'));
owner = char(thisImage.getAttribute('owner'));
secret = char(thisImage.getAttribute('secret'));
server = char(thisImage.getAttribute('server'));
farm = char(thisImage.getAttribute('farm'));
title = char(thisImage.getAttribute('title'));
url = sprintf(urlPhoto,farm,server,id,secret);
urlEscape = strrep(strrep(url,'\','\\'),'''','\''');
info = ['{"id": "' strrep(strrep(strrep(id,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"owner": "' strrep(strrep(strrep(owner,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"secret": "' strrep(strrep(strrep(secret,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"server": "' strrep(strrep(strrep(server,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"farm": "' strrep(strrep(strrep(farm,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"keywrods": "' strrep(strrep(strrep(keywords,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"engine": "' 'flickr' '", ' ...
'"url": "' urlEscape '", ' ...
'"title": "' strrep(strrep(strrep(title,'\','\\'),'"','\"'),'''','\''') '"}'];
cnt = size(outObj,1);
cnt = cnt + 1;
outObj{cnt,1} = urlEscape;
outObj{cnt,2} = info;
outObj{cnt,3} = 'flickr';
end
%}
|
github
|
jianxiongxiao/ProfXkit-master
|
readFlickrObj.m
|
.m
|
ProfXkit-master/querySearchEngine/queryFlickrOld/readFlickrObj.m
| 1,754 |
utf_8
|
aa38ea7ca02068e6a36e93ef86852df9
|
% this function will read a Bing download xml file and covert it
% into mysql batch command file
function outObj = readFlickrObj(inFname, outObj, topic_mid, keywords)
urlPhoto = 'http://farm%s.static.flickr.com/%s/%s_%s_b.jpg';
xDoc = xmlread(inFname);
allImages = xDoc.getElementsByTagName('photo');
for k = 0:allImages.getLength-1
thisImage = allImages.item(k);
id = char(thisImage.getAttribute('id'));
owner = char(thisImage.getAttribute('owner'));
secret = char(thisImage.getAttribute('secret'));
server = char(thisImage.getAttribute('server'));
farm = char(thisImage.getAttribute('farm'));
title = char(thisImage.getAttribute('title'));
url = sprintf(urlPhoto,farm,server,id,secret);
urlEscape = strrep(strrep(url,'\','\\'),'''','\''');
info = ['{"id": "' strrep(strrep(strrep(id,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"owner": "' strrep(strrep(strrep(owner,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"secret": "' strrep(strrep(strrep(secret,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"server": "' strrep(strrep(strrep(server,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"farm": "' strrep(strrep(strrep(farm,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"keywrods": "' strrep(strrep(strrep(keywords,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"mid": "' strrep(strrep(strrep(topic_mid,'\','\\'),'"','\"'),'''','\''') '", ' ...
'"engine": "' 'flickr' '", ' ...
'"url": "' urlEscape '", ' ...
'"title": "' strrep(strrep(strrep(title,'\','\\'),'"','\"'),'''','\''') '"}'];
cnt = size(outObj,1);
cnt = cnt + 1;
outObj{cnt,1} = urlEscape;
outObj{cnt,2} = info;
outObj{cnt,3} = 'flickr';
end
|
github
|
jianxiongxiao/ProfXkit-master
|
readGoogleObj.m
|
.m
|
ProfXkit-master/querySearchEngine/queryGoogleCpp/readGoogleObj.m
| 2,356 |
utf_8
|
d9abab20fdf480157d1218866b5fb270
|
% this function will read a google download html file and covert it
% into mysql batch command file
%{
<a href="/imgres?imgurl=http://schools.archchicago.org/images/highschools/18.jpg&imgrefurl=http://schools.archchicago.org/schools/schoollistcity.aspx&h=266&w=324&sz=18&tbnid=o2GpciHX-BLS1M:&tbnh=97&tbnw=118&prev=/search%3Fq%3DSt%2BLawrence%2BHigh%2BSchool%26tbm%3Disch%26tbo%3Du&zoom=1&q=St+Lawrence+High+School&hl=en&usg=__rJUTw9RaoQnXQDkaKqPEJ7j_K9g=&sa=X&ei=Bl-DTuTXGOa80AGCuKCqAQ&ved=0CAMQ9QEwAA"><img src="data:image/gif;base64,R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" alt="" align=middle border=1 height=97 id=imgthumb1 class="imgthumb1" title="http://schools.archchicago.org/schools/schoollistcity.aspx" style="display:-moz-inline-box;height:97px;margin:3px 3px 3px 3px;padding:0px 0px;width:118px" width=118></a>
%}
function outObj = readGoogleObj(googleFname, outObj, topic_mid, keywords)
inFP = fopen(googleFname, 'r');
myStr = '';
tline = fgetl(inFP);
while ischar(tline)
myStr = [myStr tline];
tline = fgetl(inFP);
end
% googleReg = '(title=")[^"]+(")';
googleReg = '(<a href="/imgres\?imgurl=)[^"]+(&imgrefurl=)';
linkReg = '(&imgrefurl=)[^"]+(&h=)';
tbnidReg = '(&tbnid=)[^"]+(&tbnh=)';
urls = regexp(myStr,googleReg,'match');
refurls = regexp(myStr,linkReg,'match');
tbns = regexp(myStr,tbnidReg,'match');
for i=1:length(urls)
% disp([num2str(i) ': ' urls{i}(25:end-15)]);
url = urls{i}(25:end-15);
tbn = tbns{i}(12:end-10);
refurl = refurls{i}(16:end-7);
urlEscape = strrep(strrep(url,'\','\\'),'''','\''');
info = ['{"tbnid": "' strrep(strrep(strrep(tbn,'\','\\'),'"','\"'),'''','\''') ...
'", "keywrods": "' strrep(strrep(strrep(keywords,'\','\\'),'"','\"'),'''','\''') ...
'", "mid": "' strrep(strrep(strrep(topic_mid,'\','\\'),'"','\"'),'''','\''') ...
'", "engine": "' 'google' ...
'", "url": "' urlEscape ...
'", "refurl": "' strrep(strrep(strrep(refurl,'\','\\'),'"','\"'),'''','\''') '"}'];
cnt = size(outObj,1);
cnt = cnt + 1;
outObj{cnt,1} = urlEscape;
outObj{cnt,2} = info;
outObj{cnt,3} = 'google';
end
fclose(inFP);
% image google cache: http://t0.gstatic.com/images?q=tbn:CxufgEqJNk3pXM:
|
github
|
jianxiongxiao/ProfXkit-master
|
drawCamera.m
|
.m
|
ProfXkit-master/drawCamera/drawCamera.m
| 1,492 |
utf_8
|
1fb3a23e9903c4d7fd994aa0863b8563
|
function drawCamera()
close all
addpath ../icosahedron2sphere
points = icosahedron2sphere(1);
points = points(points(:,3)>=0,:);
%{
plot3(points(:,1),points(:,2),points(:,3),'.')
title(sprintf('Level %d with %d points',1,size(points,1)))
axis equal
axis tight
xlabel('x');
ylabel('y');
zlabel('z');
%}
aspect_ratio = 4/3;
focal_length = 0.12;
h_fov = 54.4/180*pi;
w = tan(h_fov/2)*focal_length;
h = w/aspect_ratio;
camera=[...
0 -w +w +w -w
0 -h -h +h +h
0 focal_length focal_length focal_length focal_length];
%plotCamera(camera);
for i=1:size(points,1)
center_ray = -points(i,:);
projLen = sqrt(center_ray(1)^2+center_ray(2)^2);
height = -projLen^2 / center_ray(3);
upVector = [center_ray(1) center_ray(2) height];
upVector = upVector /norm(upVector);
%sinTheta = center_ray(3);
leftVector = cross(center_ray,upVector);
leftVector = leftVector/norm(leftVector);
R = [leftVector' upVector' center_ray'];
currentCamera = R * camera + repmat(points(i,:)',1,5);
plotCamera(currentCamera);
end
axis equal
axis([-1 1 -1 1 -1 1]);
xlabel('x');
ylabel('y');
zlabel('z');
function plotCamera(camera)
%mid_ray = 1;
%side_rays = 1.2;
% frame
plot3(camera(1,[2 3 4 5 2]),camera(2,[2 3 4 5 2]),camera(3,[2 3 4 5 2]),'-k'); hold on;
% side rays
for i=2:5
plot3(camera(1,[1 i]),camera(2,[1 i]),camera(3,[1 i]),'-k'); hold on;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
transformPointCloud.m
|
.m
|
ProfXkit-master/RenderPCcamera/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
|
transformPointCloud.m
|
.m
|
ProfXkit-master/WarpDepthMesh/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
|
bilateralFilter.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/bilateralFilter.m
| 7,891 |
utf_8
|
456ce9778b227be5bc1eb6ed3b34ed36
|
%
% output = bilateralFilter( data, edge, ...
% edgeMin, edgeMax, ...
% sigmaSpatial, sigmaRange, ...
% samplingSpatial, samplingRange )
%
% Bilateral and Cross-Bilateral Filter using the Bilateral Grid.
%
% Bilaterally filters the image 'data' using the edges in the image 'edge'.
% If 'data' == 'edge', then it the standard bilateral filter.
% Otherwise, it is the 'cross' or 'joint' bilateral filter.
% For convenience, you can also pass in [] for 'edge' for the normal
% bilateral filter.
%
% Note that for the cross bilateral filter, data does not need to be
% defined everywhere. Undefined values can be set to 'NaN'. However, edge
% *does* need to be defined everywhere.
%
% data and edge should be of the greyscale, double-precision floating point
% matrices of the same size (i.e. they should be [ height x width ])
%
% data is the only required argument
%
% edgeMin and edgeMax specifies the min and max values of 'edge' (or 'data'
% for the normal bilateral filter) and is useful when the input is in a
% range that's not between 0 and 1. For instance, if you are filtering the
% L channel of an image that ranges between 0 and 100, set edgeMin to 0 and
% edgeMax to 100.
%
% edgeMin defaults to min( edge( : ) ) and edgeMax defaults to max( edge( : ) ).
% This is probably *not* what you want, since the input may not span the
% entire range.
%
% sigmaSpatial and sigmaRange specifies the standard deviation of the space
% and range gaussians, respectively.
% sigmaSpatial defaults to min( width, height ) / 16
% sigmaRange defaults to ( edgeMax - edgeMin ) / 10.
%
% samplingSpatial and samplingRange specifies the amount of downsampling
% used for the approximation. Higher values use less memory but are also
% less accurate. The default and recommended values are:
%
% samplingSpatial = sigmaSpatial
% samplingRange = sigmaRange
%
%
% Copyright (c) <2007> <Jiawen Chen, Sylvain Paris, and Fredo Durand>
%
% 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, including without limitation the rights
% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
% copies of the Software, and to permit persons to whom the Software is
% furnished to do so, 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, EXPRESS OR
% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
% THE SOFTWARE.
%
function output = bilateralFilter( data, edge, edgeMin, edgeMax, sigmaSpatial, sigmaRange, samplingSpatial, samplingRange )
if( ndims( data ) > 2 ),
error( 'data must be a greyscale image with size [ height, width ]' );
end
if( ~isa( data, 'double' ) ),
error( 'data must be of class "double"' );
end
if ~exist( 'edge', 'var' ),
edge = data;
elseif isempty( edge ),
edge = data;
end
if( ndims( edge ) > 2 ),
error( 'edge must be a greyscale image with size [ height, width ]' );
end
if( ~isa( edge, 'double' ) ),
error( 'edge must be of class "double"' );
end
inputHeight = size( data, 1 );
inputWidth = size( data, 2 );
if ~exist( 'edgeMin', 'var' ),
edgeMin = min( edge( : ) );
%warning( 'edgeMin not set! Defaulting to: %f\n', edgeMin );
end
if ~exist( 'edgeMax', 'var' ),
edgeMax = max( edge( : ) );
%warning( 'edgeMax not set! Defaulting to: %f\n', edgeMax );
end
edgeDelta = edgeMax - edgeMin;
if ~exist( 'sigmaSpatial', 'var' ),
%sigmaSpatial = min( inputWidth, inputHeight ) / 16;
sigmaSpatial = min( inputWidth, inputHeight ) / 64;
fprintf( 'Using default sigmaSpatial of: %f\n', sigmaSpatial );
end
if ~exist( 'sigmaRange', 'var' ),
%sigmaRange = 0.1 * edgeDelta;
sigmaRange = 0.025 * edgeDelta;
fprintf( 'Using default sigmaRange of: %f\n', sigmaRange );
end
if ~exist( 'samplingSpatial', 'var' ),
samplingSpatial = sigmaSpatial;
end
if ~exist( 'samplingRange', 'var' ),
samplingRange = sigmaRange;
end
if size( data ) ~= size( edge ),
error( 'data and edge must be of the same size' );
end
% parameters
derivedSigmaSpatial = sigmaSpatial / samplingSpatial;
derivedSigmaRange = sigmaRange / samplingRange;
paddingXY = floor( 2 * derivedSigmaSpatial ) + 1;
paddingZ = floor( 2 * derivedSigmaRange ) + 1;
% allocate 3D grid
downsampledWidth = floor( ( inputWidth - 1 ) / samplingSpatial ) + 1 + 2 * paddingXY;
downsampledHeight = floor( ( inputHeight - 1 ) / samplingSpatial ) + 1 + 2 * paddingXY;
downsampledDepth = floor( edgeDelta / samplingRange ) + 1 + 2 * paddingZ;
gridData = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
gridWeights = zeros( downsampledHeight, downsampledWidth, downsampledDepth );
% compute downsampled indices
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 );
% ii =
% 0 0 0 0 0
% 1 1 1 1 1
% 2 2 2 2 2
% jj =
% 0 1 2 3 4
% 0 1 2 3 4
% 0 1 2 3 4
% so when iterating over ii( k ), jj( k )
% get: ( 0, 0 ), ( 1, 0 ), ( 2, 0 ), ... (down columns first)
di = round( ii / samplingSpatial ) + paddingXY + 1;
dj = round( jj / samplingSpatial ) + paddingXY + 1;
dz = round( ( edge - edgeMin ) / samplingRange ) + paddingZ + 1;
% perform scatter (there's probably a faster way than this)
% normally would do downsampledWeights( di, dj, dk ) = 1, but we have to
% perform a summation to do box downsampling
for k = 1 : numel( dz ),
dataZ = data( k ); % traverses the image column wise, same as di( k )
if ~isnan( dataZ ),
dik = di( k );
djk = dj( k );
dzk = dz( k );
gridData( dik, djk, dzk ) = gridData( dik, djk, dzk ) + dataZ;
gridWeights( dik, djk, dzk ) = gridWeights( dik, djk, dzk ) + 1;
end
end
% make gaussian kernel
kernelWidth = 2 * derivedSigmaSpatial + 1;
kernelHeight = kernelWidth;
kernelDepth = 2 * derivedSigmaRange + 1;
halfKernelWidth = floor( kernelWidth / 2 );
halfKernelHeight = floor( kernelHeight / 2 );
halfKernelDepth = floor( kernelDepth / 2 );
[gridX, gridY, gridZ] = meshgrid( 0 : kernelWidth - 1, 0 : kernelHeight - 1, 0 : kernelDepth - 1 );
gridX = gridX - halfKernelWidth;
gridY = gridY - halfKernelHeight;
gridZ = gridZ - halfKernelDepth;
gridRSquared = ( gridX .* gridX + gridY .* gridY ) / ( derivedSigmaSpatial * derivedSigmaSpatial ) + ( gridZ .* gridZ ) / ( derivedSigmaRange * derivedSigmaRange );
kernel = exp( -0.5 * gridRSquared );
% convolve
blurredGridData = convn( gridData, kernel, 'same' );
blurredGridWeights = convn( gridWeights, kernel, 'same' );
% divide
blurredGridWeights( blurredGridWeights == 0 ) = -2; % avoid divide by 0, won't read there anyway
normalizedBlurredGrid = blurredGridData ./ blurredGridWeights;
normalizedBlurredGrid( blurredGridWeights < -1 ) = 0; % put 0s where it's undefined
% for debugging
% blurredGridWeights( blurredGridWeights < -1 ) = 0; % put zeros back
% upsample
[ jj, ii ] = meshgrid( 0 : inputWidth - 1, 0 : inputHeight - 1 ); % meshgrid does x, then y, so output arguments need to be reversed
% no rounding
di = ( ii / samplingSpatial ) + paddingXY + 1;
dj = ( jj / samplingSpatial ) + paddingXY + 1;
dz = ( edge - edgeMin ) / samplingRange + paddingZ + 1;
% interpn takes rows, then cols, etc
% i.e. size(v,1), then size(v,2), ...
output = interpn( normalizedBlurredGrid, di, dj, dz );
|
github
|
jianxiongxiao/ProfXkit-master
|
projICP.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/projICP.m
| 4,587 |
utf_8
|
197ed7d4d038ab9947bf507d22a40379
|
function camAAr2c = projICP(camAAr2c)
global VMap;
global NMap;
global XYZcamBilateral;
global NcamBilateral;
global K;
global NMapCam;
global VMapCam;
global Vku;
for iterID = 1:10
%% data association
% transform the point cloud
VMapCam = AngleAxisRotatePoint(camAAr2c, VMap) + repmat(camAAr2c(4:6)',1,size(VMap,2));
NMapCam = AngleAxisRotatePoint(camAAr2c, NMap);
% projective association
px = round(K(1,1)*(VMapCam(1,:)./VMapCam(3,:)) + K(1,3));
py = round(K(2,2)*(VMapCam(2,:)./VMapCam(3,:)) + K(2,3));
isValid = (1<=px & px <= 640 & 1<=py & py<= 480);
VMapCam = VMapCam(:,isValid);
NMapCam = NMapCam(:,isValid);
px = px(isValid);
py = py(isValid);
ind = sub2ind([480 640],py,px);
%{
cla(subplot(6,3,12))
validMap = zeros(480,640);
validMap(ind) = 1;
imagesc(validMap);
axis equal;
axis tight;
title(sprintf('Iteration %d: init valid Map',iterID))
%}
isValid = XYZcamBilateral(640*480*2+ind)~=0;
VMapCam = VMapCam(:,isValid);
NMapCam = NMapCam(:,isValid);
ind = ind(isValid);
% outlier rejection
diffD = (VMapCam(1,:) - XYZcamBilateral(ind)).^2 + (VMapCam(2,:) - XYZcamBilateral(640*480+ind)).^2 + (VMapCam(3,:) - XYZcamBilateral(640*480*2+ind)).^2 ;
dotProdN = sum([NcamBilateral(ind); NcamBilateral(640*480+ind); NcamBilateral(640*480*2+ind)] .* NMapCam,1);
subplot(6,3,17)
validMap = zeros(480,640);
validMap(ind) = diffD;
imagesc(validMap);
axis equal;
axis tight;
title(sprintf('Iteration %d: diffD',iterID))
subplot(6,3,18)
validMap = zeros(480,640);
validMap(ind) = dotProdN;
imagesc(validMap);
axis equal;
axis tight;
title(sprintf('Iteration %d: dotProdN',iterID))
%isValid = (diffD<0.1^2) & (dotProdN > cos(pi/3));
isValid = (diffD<1^2);
VMapCam = VMapCam(:,isValid);
NMapCam = NMapCam(:,isValid);
ind = ind(isValid);
Vku = [XYZcamBilateral(ind); XYZcamBilateral(640*480+ind); XYZcamBilateral(640*480*2+ind)];
subplot(6,3,15)
validMap = zeros(480,640);
validMap(ind) = 1;
imagesc(validMap);
axis equal;
axis tight;
title(sprintf('Iteration %d: valid Map',iterID))
%% optimization
% objective function
E = sum(( Vku - VMapCam ) .* NMapCam,1);
subplot(6,3,16)
validMap = zeros(480,640);
validMap(ind) = E;
imagesc(validMap);
axis equal;
axis tight;
title(sprintf('Iteration %d: Distance Map',iterID))
fprintf('initial error: #inliers = %.2f(%d/%d), sum = %f, mean = %f, median = %f\n', sum(isValid)/length(isValid), sum(isValid), length(isValid), sum(E.^2), mean(E.^2), median(E.^2));
%options = optimset('Display','iter', 'Algorithm','levenberg-marquardt');
options = optimset('display','off','Algorithm','levenberg-marquardt');
[AA_gk, resnorm, residual, exitflag, output] = lsqnonlin(@residualFunction, [0 0 0 0 0 0],[],[],options);
camAAr2c = cameraRt2AngleAxis(concatenateCameraRt(transformCameraRt(cameraAngleAxis2Rt(AA_gk)), cameraAngleAxis2Rt(camAAr2c)));
end
end
function residuals = residualFunction(Tgk)
global NMapCam;
global VMapCam;
global Vku;
VkuTran = AngleAxisRotatePoint(Tgk, Vku) + repmat(Tgk(4:6)',1,size(Vku,2));
residuals = ( VkuTran - VMapCam ) .* NMapCam;
end
%{
% for visualization
figure
image2show = zeros(480,640);
image2show(ind) = distance(1,:);
imagesc(image2show); axis equal; axis tight;
title('Vm(1) - Vd(1)')
figure
image2show = zeros(480,640);
image2show(ind) = distance(2,:);
imagesc(image2show); axis equal; axis tight;
title('Vm(2) - Vd(2)')
figure
image2show = zeros(480,640);
image2show(ind) = distance(3,:);
imagesc(image2show); axis equal; axis tight;
title('Vm(3) - Vd(3)')
figure
image2show = zeros(480,640);
image2show(ind) = sum(distance.^2,1);
imagesc(image2show); axis equal; axis tight;
title('(Vm - Vd)^2')
figure
image2show = zeros(480,640);
image2show(ind) = sum(distance .* NMapCam,1).^2;
imagesc(image2show); axis equal; axis tight;
title('E')
%}
% coarse to fine
|
github
|
jianxiongxiao/ProfXkit-master
|
SiftFu.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SiftFu.m
| 12,329 |
utf_8
|
42b1ec7d5842dcbcf7a94ab1deddc050
|
function newDepth = SiftFu(sequenceName, frameIDs)
%{
Please cite the following paper if you use this code
Citation:
J. Xiao, A. Owens and A. Torralba
SUN3D Database: Semantic RGB-D Bundle Adjustment with Human in the Loop
Proceedings of 14th IEEE International Conference on Computer Vision (ICCV2013)
%}
addpath(genpath('SIFTransac'))
vl_setup;
global toVisualize;
toVisualize = true;
%% IO
if ~exist('sequenceName','var')
% load demo sequence
% look for all sequence name list at http://sun3d.csail.mit.edu/player/list.html
%sequenceName = 'hotel_mr/scan1';
%sequenceName = 'hotel_umd/maryland_hotel3';
%sequenceName = 'brown_bm_1/brown_bm_1';
sequenceName = 'mit_32_d428/bs4j179mmv';
end
% the root path of SUN3D
% change it to local if you downloaded the data
%SUN3Dpath = '/data/vision/torralba/sun3d/record/scene_final';
SUN3Dpath = 'http://sun3d.csail.mit.edu/data/';
% read intrinsic
global K;
K = reshape(readValuesFromTxt(fullfile(SUN3Dpath,sequenceName,'intrinsics.txt')),3,3)';
% file list
imageFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'image/'),'jpg');
depthFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'depth/'),'png');
% read time stamp
imageFrameID = zeros(1,length(imageFiles));
imageTimestamp = zeros(1,length(imageFiles));
for i=1:length(imageFiles)
id_time = sscanf(imageFiles(i).name, '%d-%d.jpg');
imageFrameID(i) = id_time(1);
imageTimestamp(i) = id_time(2);
end
depthFrameID = zeros(1,length(depthFiles));
depthTimestamp = zeros(1,length(depthFiles));
for i=1:length(depthFiles)
id_time = sscanf(depthFiles(i).name, '%d-%d.png');
depthFrameID(i) = id_time(1);
depthTimestamp(i) = id_time(2);
end
% synchronize: find a depth for each image
frameCount = length(imageFiles);
IDimage2depth = zeros(1,frameCount);
for i=1:frameCount
[~, IDimage2depth(i)]=min(abs(double(depthTimestamp)-double(imageTimestamp(i))));
end
%plot(double(imageTimestamp)-double(depthTimestamp(IDimage2depth)))
if ~exist('frameIDs','var')
frameIDs = 1:frameCount;
else
frameIDs = frameIDs(frameIDs>=1 & frameIDs<=frameCount);
end
imageFiles = imageFiles(frameIDs);
depthFiles = depthFiles(IDimage2depth(frameIDs));
%% kinect fusion
% for optimization
global VMap;
global NMap;
global CMap;
global XYZcam;
global Ncam;
global IMGcam;
%% tsdf
global voxel;
global tsdf_value;
global tsdf_weight;
global tsdf_color; tsdf_color = [];
voxel.unit = 0.01; % Kevin: 4mm = 0.004 meter. Kinect cannot go better than 3mm
voxel.mu_grid = 10; % used to be 4
voxel.size_grid = [512; 512; 1024]; % [512; 512; 512];
voxel.range(1,1) = - voxel.size_grid(1) * voxel.unit / 2;
voxel.range(1,2) = voxel.range(1,1) + (voxel.size_grid(1)-1) * voxel.unit;
voxel.range(2,1) = - voxel.size_grid(2) * voxel.unit / 2;
voxel.range(2,2) = voxel.range(2,1) + (voxel.size_grid(2)-1) * voxel.unit;
voxel.range(3,1) = -0.5; % - voxel.size_grid(3) * voxel.unit / 2;
voxel.range(3,2) = voxel.range(3,1) + (voxel.size_grid(3)-1) * voxel.unit;
voxel.mu = voxel.mu_grid * voxel.unit;
fprintf('memory = %f GB\n', prod(voxel.size_grid) * 4 / (1024*1024*1024));
fprintf('space = %.2f m x %.2f m x %.2f m ', voxel.size_grid(1) * voxel.unit, voxel.size_grid(2) * voxel.unit, voxel.size_grid(3) * voxel.unit);
fprintf('= [%.2f,%.2f] x [%.2f,%.2f] x [%.2f,%.2f]\n',voxel.range(1,1),voxel.range(1,2),voxel.range(2,1),voxel.range(2,2),voxel.range(3,1),voxel.range(3,2));
%tsdf_value = -ones([voxel.size_grid(1),voxel.size_grid(2), voxel.size_grid(3)],'single');
tsdf_value = ones([voxel.size_grid(1),voxel.size_grid(2), voxel.size_grid(3)],'single');
tsdf_weight = zeros([voxel.size_grid(1),voxel.size_grid(2), voxel.size_grid(3)],'single');
% comment out this line to avoid using color
% tsdf_color = zeros([voxel.size_grid(1),voxel.size_grid(2), voxel.size_grid(3)], 'uint32');
f = K(1,1);
global ViewFrustumC;
ViewFrustumC = [...
0 -320 -320 320 320;
0 -240 240 240 -240;
0 f f f f];
ViewFrustumC = ViewFrustumC/f * 8; % 8 meter is the furthest depth of kinect
% precompute
global raycastingDirectionC;
[pX,pY]=meshgrid(1:640,1:480);
raycastingDirectionC = [pX(:)'-K(1,3); pY(:)'-K(2,3); f*ones(1,640*480)]; % clipping at 8 meter is the furthest depth of kinect
raycastingDirectionC = raycastingDirectionC ./ repmat(sqrt(sum(raycastingDirectionC.^2,1)),3,1);
%%
useSIFT = false;
if useSIFT
MatchPairs = cell(1,length(imageFiles)-1);
end
cameraRtC2W = repmat([eye(3) zeros(3,1)], [1,1,length(imageFiles)]);
dispclim = [0 5];
for frameID = 1:length(imageFiles)
fprintf('================================ Frame %d ================================\n',frameID);
IMGcam = imageRead(fullfile(fullfile(SUN3Dpath,sequenceName,'image',imageFiles(frameID).name)));
%subplot(3,4,4)
%imagesc(IMGcam); axis equal; axis tight;
%drawnow;
%title('input color');
if frameID==1
IMGcam1 = IMGcam;
end
% read the frame
depth = depthRead(fullfile(fullfile(SUN3Dpath,sequenceName,'depth',depthFiles(frameID).name)));
XYZcam = depth2XYZcamera(K, depth);
if frameID==1
XYZcam1 = XYZcam;
end
Ncam = vertex2normal(XYZcam);
if toVisualize
if frameID==1
subplot(3,4,9)
else
subplot(3,4,1)
end
imagesc(XYZcam(:,:,3),dispclim); axis equal; axis tight
title(sprintf('Frame %d: Input Depth',frameID));
axis off
if frameID==1
subplot(3,4,10)
else
subplot(3,4,2)
end
imagesc((Ncam+1)/2); axis equal; axis tight
title(sprintf('Frame %d: Input Normal',frameID));
axis off
if frameID==1
subplot(3,4,11)
else
subplot(3,4,3)
end
raycastingDirectionW = transformRTdir(raycastingDirectionC,[eye(3) zeros(3,1)]);
DotMap = reshape(max(0,sum(-reshape(Ncam,[480*640 3])' .* raycastingDirectionW,1)),[480 640]);
imagesc(DotMap);
colormap('gray'); axis equal; axis tight
title(sprintf('Frame %d: Input Phong',frameID));
axis off
end
if frameID==1
camRtC2W = [eye(3) [0;0;0]];
else
MatchPairs{frameID-1} = align2view(1,IMGcam1,XYZcam1,frameID,IMGcam,XYZcam);
camRtC2W = MatchPairs{frameID-1}.Rt;
if size(MatchPairs{frameID-1}.matches,2)<5
disp('SIFT matching failed, ignoring this frame');
continue;
end
end
cameraRtC2W(:,:,frameID) = camRtC2W;
%% update TSDF
disp('update TSDF...');
%tic
updateTSDF(camRtC2W);
%toc
%{
%% visualizing the voxel
subplot(3,4,10)
for i=1:voxel.size_grid(3)
if min(min(min(tsdf_value(:,:,i)))) ~= max(max(max(tsdf_value(:,:,i))))
imagesc(tsdf_weight(:,:,i)'); axis equal; axis tight; xlabel('x'); ylabel('y');
title(['frame ' num2str(i) ' = depth ' num2str((i-1)*voxel.unit+voxel.range(3,1)) ' meter']);
pause(0.05);
end
end
subplot(3,4,10)
for i=1:voxel.size_grid(3)
if min(min(min(tsdf_value(:,:,i)))) ~= max(max(max(tsdf_value(:,:,i))))
imagesc(tsdf_value(:,:,i)'); axis equal; axis tight; xlabel('x'); ylabel('y');
title(['frame ' num2str(i) ' = depth ' num2str((i-1)*voxel.unit+voxel.range(3,1)) ' meter']);
pause(0.05);
end
end
%}
%% ray casting for the result
disp('ray casting');
tic
% ray casting result is in the world coordinate
[VMap,NMap,tMap,CMap] = raycastingTSDFvectorized([eye(3) [0;0;0]], [0.4 8]);
%[VMap,NMap,tMap] = raycastingTSDFdump(camRtC2WrayCasting, [0.4 8]);
toc
newDepth = reshape(VMap(3,:),480,640);
if toVisualize
subplot(3,4,5)
imagesc(newDepth,dispclim); axis equal; axis tight; axis off
title(sprintf('Fused Depth',frameID));
end
VMap = reshape(double(VMap'),480,640,3);
VMap(:,:,4) = ~isnan(VMap(:,:,1));
NMap = vertex2normal(VMap);
% normalize normal map
%NMap = NMap ./ repmat(sqrt(sum(NMap.^2,1)),3,1);
if toVisualize
subplot(3,4,6)
imagesc((NMap+1)/2); axis equal; axis tight; axis off
title(sprintf('Fused Noraml',frameID));
end
if toVisualize
subplot(3,4,7)
raycastingDirectionW = transformRTdir(raycastingDirectionC,[eye(3) zeros(3,1)]);
DotMap = reshape(max(0,sum(-reshape(NMap,[480*640 3])' .* raycastingDirectionW,1)),[480 640]);
imagesc(DotMap);
colormap('gray'); axis equal; axis tight; axis off
title(sprintf('Fused Phong',frameID));
end
if toVisualize
subplot(3,4,12)
imagesc(abs(newDepth - XYZcam1(:,:,3)),dispclim); axis equal; axis tight; axis off
title(sprintf('Difference of Depth',frameID));
drawnow;
end
%{
subplot(3,4,6)
imagesc(min(1,max(0,(reshape(NMap',[480 640 3])+1)/2))); axis equal; axis tight
title(sprintf('Frame %d: rayCasting Normal Map',frameID));
drawnow;
%figure
%visNMap = reshape(NMap',[480 640 3]);
%out = visualizeNormals(-visNMap);
%imagesc(out)
%title('rayCasting Normal Map');
subplot(3,4,7)
raycastingDirectionW = transformRTdir(raycastingDirectionC,camRtC2W);
DotMap = reshape(max(0,sum(-NMap .* raycastingDirectionW,1)),[480 640]);
imagesc(DotMap);
colormap('gray'); axis equal; axis tight
title(sprintf('Frame %d: phong shading',frameID));
drawnow;
if ~isempty(tsdf_color)
subplot(3,4,8)
imagesc(reshape(CMap',[480,640,3])/255); axis equal; axis tight;
drawnow;
title(sprintf('Frame %d: ray casting color',frameID));
end
%}
%subplot(3,4,9)
%imagesc(reshape(tMap,480,640)); axis equal; axis tight
%title(sprintf('Frame %d: rayCasting tMap',frameID));
%drawnow;
end
end
%% IO functions
function values = readValuesFromTxt(filename)
try
values = textscan(urlread(filename),'%f');
catch
fid = fopen(filename,'r');
values = textscan(fid,'%f');
fclose(fid);
end
values = values{1};
end
function XYZcamera = depth2XYZcamera(K, depth)
[x,y] = meshgrid(1:640, 1:480);
XYZcamera(:,:,1) = (x-K(1,3)).*depth/K(1,1);
XYZcamera(:,:,2) = (y-K(2,3)).*depth/K(2,2);
XYZcamera(:,:,3) = depth;
XYZcamera(:,:,4) = depth~=0;
end
function depth = depthRead(filename)
depth = imread(filename);
depth = bitor(bitshift(depth,-3), bitshift(depth,16-3));
depth = single(depth)/1000;
end
%{
% test to make sure it is correct
for i=0:65535
depth = uint16(i);
code =bitor(bitshift(depth,3),bitshift(depth,3-16));
recoverDepth = bitor(bitshift(code,-3), bitshift(code,16-3));
if (depth~=recoverDepth)
fprintf('error + %d\n',i);
end
end
%}
function image = imageRead(filename)
image = imread(filename);
end
function files = dirSmart(page, tag)
[files, status] = urldir(page, tag);
if status == 0
files = dir(fullfile(page, ['*.' tag]));
end
end
function [files, status] = urldir(page, tag)
if nargin == 1
tag = '/';
else
tag = lower(tag);
if strcmp(tag, 'dir')
tag = '/';
end
if strcmp(tag, 'img')
tag = 'jpg';
end
end
nl = length(tag);
nfiles = 0;
files = [];
% Read page
page = strrep(page, '\', '/');
[webpage, status] = urlread(page);
if status
% Parse page
j1 = findstr(lower(webpage), '<a href="');
j2 = findstr(lower(webpage), '</a>');
Nelements = length(j1);
if Nelements>0
for f = 1:Nelements
% get HREF element
chain = webpage(j1(f):j2(f));
jc = findstr(lower(chain), '">');
chain = deblank(chain(10:jc(1)-1));
% check if it is the right type
if length(chain)>length(tag)-1
if strcmp(chain(end-nl+1:end), tag)
nfiles = nfiles+1;
chain = strrep(chain, '%20', ' '); % replace space character
files(nfiles).name = chain;
files(nfiles).bytes = 1;
end
end
end
end
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
estimateRt.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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
|
ransacfitRt.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/ransacfitRt.m
| 2,778 |
utf_8
|
07e66db36ff0d62d460c90f54e34bc7b
|
% 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);
% 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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/peter/ransac.m
| 9,582 |
utf_8
|
a864f4e3ec4b4d8e18b346cf8391b28b
|
% 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,10); % at least try 20 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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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
|
vl_compile.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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_override.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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_kdtree_sift.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/demo/vl_demo_kdtree_sift.m
| 6,822 |
utf_8
|
191589ff45e0f5cdb79b1eed1b1bb906
|
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', 'a.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'b.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_tpsu.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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_twister.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/xtest/vl_test_twister.m
| 1,162 |
utf_8
|
1ae9040a416db503ad73600f081d096b
|
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()
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_square()
a=rand(10) ;
b=vl_twister(10) ;
vl_assert_equal(a,b,'VL_TWISTER(N)') ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_kdtree.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/xtest/vl_test_kdtree.m
| 2,448 |
utf_8
|
66f429ff8286089a34c193d7d3f9f016
|
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/SiftFu/SiftFu/SIFTransac/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_pegasos.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/xtest/vl_test_pegasos.m
| 2,852 |
utf_8
|
45a09a3bfefa3facd439fefbb7f1a903
|
function results = vl_test_pegasos(varargin)
% VL_TEST_KDTREE
vl_test_init ;
function s = setup()
randn('state',0) ;
s.biasMultiplier = 10 ;
s.lambda = 0.01 ;
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.w = exact_solver(s.X, s.y, s.lambda, s.biasMultiplier)
s.w = [1.181106685845652 ;
0.098478251033487 ;
-0.154057992404545 ] ;
function test_problem_1(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
w = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'NumIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'Preconditioner', conv([1 1 .1])) ;
vl_assert_almost_equal(w, conv(s.w), 0.1) ;
end
function test_continue_training(s)
for conv = {@single,@double}
conv = conv{1} ;
vl_twister('state',0) ;
w = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'NumIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier) ;
vl_twister('state',0) ;
w1 = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1, ...
'NumIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier) ;
w2 = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1501, ...
'StartingModel', w1, ...
'NumIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier) ;
vl_assert_almost_equal(w,w2,1e-7) ;
end
function test_continue_training_with_perm(s)
perm = uint32(randperm(size(s.X,2))) ;
for conv = {@single,@double}
conv = conv{1} ;
vl_twister('state',0) ;
w = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'NumIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
vl_twister('state',0) ;
w1 = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1, ...
'NumIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
w2 = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1501, ...
'StartingModel', w1, ...
'NumIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
vl_assert_almost_equal(w,w2,1e-7) ;
end
function w = exact_solver(X, y, lambda, biasMultiplier)
N = size(X,2) ;
model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 ', 1/(lambda*N))) ;
w = X(:,model.SVs) * model.sv_coef ;
w(3) = - model.rho / biasMultiplier ;
format long ;
disp('model w:')
disp(w)
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_alphanum.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_imintegral.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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_grad.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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_dsift.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_imsmooth.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_phow.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/xtest/vl_test_kmeans.m
| 2,788 |
utf_8
|
14374b7dbae832fc3509e02caf00cdf5
|
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_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_imarray.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/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/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/xtest/vl_test_slic.m
| 229 |
utf_8
|
42c827b383cca74cae2540e5da870bbf
|
function results = vl_test_slic(varargin)
% VL_TEST_SLIC
vl_test_init ;
function s = setup()
s.im = im2single(imread(fullfile(vl_root,'data','a.jpg'))) ;
function test_slic(s)
segmentation = vl_slic(s.im, 10, 0.1, 'verbose') ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_imdisttf.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_argparse.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_binsearch.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_plotframe.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/plotop/vl_plotframe.m
| 5,410 |
utf_8
|
8c48bac1c5d80dba361b67cd135103d9
|
function h=vl_plotframe(frames,varargin)
% VL_PLOTFRAME Plot feature frame
% VL_PLOTFRAME(FRAME) plots the frames FRAME. Frames are attributed
% image regions (as, for example, extracted by a feature detector). A
% frame is a vector of D=2,3,..,6 real numbers, depending on its
% class. VL_PLOTFRAME() supports the following classes:
%
% * POINTS
% + FRAME(1:2) coordinates
%
% * CIRCLES
% + FRAME(1:2) center
% + FRAME(3) radius
%
% * ORIENTED CIRCLES
% + FRAME(1:2) center
% + FRAME(3) radius
% + FRAME(4) orientation
%
% * ELLIPSES
% + FRAME(1:2) center
% + FRAME(3:5) S11, S12, S22 such that ELLIPSE = {x: x' inv(S) x = 1}.
%
% * ORIENTED ELLIPSES
% + FRAME(1:2) center
% + FRAME(3:6) stacking of A such that ELLIPSE = {A x : |x| = 1}
%
% H=VL_PLOTFRAME(...) returns the handle of the graphical object
% representing the frames.
%
% VL_PLOTFRAME(FRAMES) where FRAMES is a matrix whose column are FRAME
% vectors plots all frames simultaneously. Using this call is much
% faster than calling VL_PLOTFRAME() for each frame.
%
% VL_PLOTFRAME(FRAMES,...) passes any extra argument to the underlying
% plot function. The first optional argument can be a line
% specification string such as the one used by PLOT().
%
% See also: 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).
% number of vertices drawn for each frame
np = 40 ;
lineprop = {} ;
if length(varargin) > 0
lineprop = vl_linespec2prop(varargin{1}) ;
lineprop = {lineprop{:}, varargin{2:end}} ;
end
% --------------------------------------------------------------------
% Handle various frame classes
% --------------------------------------------------------------------
% if just a vector, make sure it is column
if(min(size(frames))==1)
frames = frames(:) ;
end
[D,K] = size(frames) ;
zero_dimensional = D==2 ;
% just points?
if zero_dimensional
h = plot(frames(1,:),frames(2,:),'g.',lineprop{:}) ;
return ;
end
% reduce all other cases to ellipses/oriented ellipses
frames = frame2oell(frames) ;
do_arrows = (D==4 || D==6) ;
% --------------------------------------------------------------------
% Draw
% --------------------------------------------------------------------
K = size(frames,2) ;
thr = linspace(0,2*pi,np) ;
% allx and ally are nan separated lists of the vertices describing the
% boundary of the frames
allx = nan*ones(1, np*K+(K-1)) ;
ally = nan*ones(1, np*K+(K-1)) ;
if do_arrows
% allxf and allyf are nan separated lists of the vertices of the
allxf = nan*ones(1, 3*K) ;
allyf = nan*ones(1, 3*K) ;
end
% vertices around a unit circle
Xp = [cos(thr) ; sin(thr) ;] ;
for k=1:K
% frame center
xc = frames(1,k) ;
yc = frames(2,k) ;
% frame matrix
A = reshape(frames(3:6,k),2,2) ;
% vertices along the boundary
X = A * Xp ;
X(1,:) = X(1,:) + xc ;
X(2,:) = X(2,:) + yc ;
% store
allx((k-1)*(np+1) + (1:np)) = X(1,:) ;
ally((k-1)*(np+1) + (1:np)) = X(2,:) ;
if do_arrows
allxf((k-1)*3 + (1:2)) = xc + [0 A(1,1)] ;
allyf((k-1)*3 + (1:2)) = yc + [0 A(2,1)] ;
end
end
if do_arrows
h = line([allx nan allxf], ...
[ally nan allyf], ...
'Color','g','LineWidth',3, ...
lineprop{:}) ;
else
h = line(allx, ally, ...
'Color','g','LineWidth',3, ...
lineprop{:}) ;
end
% --------------------------------------------------------------------
function eframes = frame2oell(frames)
% FRAMES2OELL Convert generic frame to oriented ellipse
% EFRAMES = FRAME2OELL(FRAMES) converts the frames FRAMES to
% oriented ellipses EFRAMES. This is useful because many tasks are
% almost equivalent for all kind of regions and are immediately
% reduced to the most general case.
%
% Determine the kind of frames
%
[D,K] = size(frames) ;
switch D
case 2
kind = 'point' ;
case 3
kind = 'disk' ;
case 4
kind = 'odisk' ;
case 5
kind = 'ellipse' ;
case 6
kind = 'oellipse' ;
otherwise
error(['FRAMES format is unknown']) ;
end
eframes = zeros(6,K) ;
%
% Do converison
%
switch kind
case 'point'
eframes(1:2,:) = frames(1:2,:) ;
case 'disk'
eframes(1:2,:) = frames(1:2,:) ;
eframes(3,:) = frames(3,:) ;
eframes(6,:) = frames(3,:) ;
case 'odisk'
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 'ellipse'
eframes(1:2,:) = frames(1:2,:) ;
eframes(3:6,:) = mapFromS(frames(3:5,:)) ;
case 'oellipse'
eframes = frames ;
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.
tmp = sqrt(S(3,:)) + eps ;
A(1,:) = sqrt(S(1,:).*S(3,:) - S(2,:).^2) ./ tmp ;
A(2,:) = zeros(1,length(tmp));
A(3,:) = S(2,:) ./ tmp ;
A(4,:) = tmp ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_roc.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/plotop/vl_roc.m
| 6,848 |
utf_8
|
3d7ed746da2d3f389ad56c8e36f006d7
|
function [tpr,tnr,info] = vl_roc(labels, scores, varargin)
% VL_ROC Compute ROC curve
% [TP,TN] = VL_ROC(LABELS, SCORES) computes the receiver operating
% characteristic (ROC curve). LABELS are the ground thruth labels (+1
% or -1) and SCORE is the scores assigned to them by a classifier
% (higher scores correspond to positive labels).
%
% [TP,TN] are the true positive and true negative rates for
% incereasing values of the decision threshold.
%
% Set the zero the lables of samples to ignore in the evaluation.
%
% Set to -INF the score of samples which are never retrieved. In
% this case the PR curve will have maximum recall < 1.
%
% [TP,TN,INFO] = VL_ROC(...) returns the following additional
% information:
%
% INFO.EER:: Equal error rate.
% INFO.AUC:: Area under the VL_ROC (AUC).
% INFO.UR:: Uniform prior best op point rate.
% INFO.UT:: Uniform prior best op point threhsold.
% INFO.NR:: Natural prior best op point rate.
% INFO.NT:: Natural prior best op point threshold.
%
% VL_ROC(...) with no output arguments plots the VL_ROC diagram in
% the current axis.
%
% About the ROC curve::
% Consider a classifier that predicts as positive all lables Y
% whose SCORE is not smaller than a threshold S. The ROC curve
% represents the performance of such classifier as the threshold S
% is changed. Define
%
% P = num. of positive samples,
% N = 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 from -INF to +INF. 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)).
%
% An OPERATING POINT is a point on the ROC curve corresponding to
% a certain threshold S. Each operating point corresponds to
% minimizing the empirical 01 error of the classifier for given
% prior probabilty of the labels. VL_ROC() computes the following
% operating points:
%
% Natural operating point:: Assumes P[Y=+1] = P / (P + N).
% Uniform operating point:: Assumes P[Y=+1] = 1/2.
%
% VL_ROC() acccepts the following options:
%
% Plot:: []
% Setting this option turns on plotting. Set to 'TrueNegative' or
% 'TN' to plot TP(S) (recall) vs. TN(S). Set to 'FalseNegative' or
% 'FN' to plot TP(S) (recall) vs. FP(S) = 1 - TN(S).
%
% See also: VL_PR(), 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).
opts.plot = [] ;
opts = vl_argparse(opts, varargin) ;
% make row vectors
labels = labels(:)' ;
scores = scores(:)' ;
% sort by descending scores
[scores, perm] = sort(scores, 'descend') ;
labels = labels(perm) ;
% assume that data with -INF score is never retrieved
stop = max(find(scores > -inf)) ;
% Compute number of true positives, false positives, and overall
% peositives. Note that labels==0 don't increase any of the counts.
tp = [0 cumsum(labels(1:stop) > 0)] ;
fp = [0 cumsum(labels(1:stop) < 0)] ;
p = sum(labels > 0) ;
n = sum(labels < 0) ;
% compute the rates
tpr = tp / (p + eps) ;
fpr = fp / (n + eps) ;
fnr = 1 - tpr ;
tnr = 1 - fpr ;
% --------------------------------------------------------------------
% Additional info
% --------------------------------------------------------------------
if nargout > 0 | nargout == 0
% equal error rate
i1 = max(find(tpr >= tnr)) ;
i2 = max(find(tnr >= tpr)) ;
eer = 1 - max(tnr(i1), tpr(i2)) ;
% uniform prior and natural prior operating points
[drop, upoint] = max(tpr * .5 + tnr * .5) ;
[drop, npoint] = max(tpr * p + tnr * n) ;
% uniform prior and natural prior operationg points rates and thresholds
ur = tpr(upoint) * .5 + tnr(upoint) * .5 ;
nr = tpr(npoint) * p/(p+n) + tnr(npoint) * n/(p+n) ;
scores_ = [-inf, scores] ;
ut = scores_(upoint) ;
nt = scores_(npoint) ;
% area
area = sum((tnr(1:end-1)+tnr(2:end)) .* diff(tpr))/2 ;
info.eer = eer ;
info.auc = area ;
info.ut = ut ;
info.ur = ur ;
info.nt = nt ;
info.nr = nr ;
end
% --------------------------------------------------------------------
% Plot
% --------------------------------------------------------------------
if ~isempty(opts.plot) || (nargout == 0)
if isempty(opts.plot), opts.plot = 'tn' ; end
cla ; hold on ;
switch lower(opts.plot)
case {'truenegatives', 'tn'}
plot(tnr, tpr, 'b', 'linewidth', 2) ;
spline((1-eer) * [0 1 1], (1-eer) * [1 1 0], 'r--') ;
spline(tnr(upoint) * [0 1 1], tpr(upoint) * [1 1 0], 'g--') ;
spline(tnr(npoint) * [0 1 1], tpr(npoint) * [1 1 0], 'k--') ;
spline([0 1], [1 0], 'b:', 'linewidth', 2) ;
spline([0 1], [0 1], 'y--', 'linewidth', 1) ;
xlabel('true negative rate') ;
ylabel('true positve rate (recall)') ;
case {'falsepositives', 'fp'}
plot(fpr, tpr, 'b', 'linewidth', 2) ;
spline(eer * [0 1 1], (1-eer) * [1 1 0], 'r--') ;
spline((1-tnr(upoint)) * [0 1 1], tpr(upoint) * [1 1 0], 'g--') ;
spline((1-tnr(npoint)) * [0 1 1], tpr(npoint) * [1 1 0], 'k--') ;
spline([1 0], [1 0], 'b:', 'linewidth', 2) ;
spline([1 0], [0 1], 'y--', 'linewidth', 1) ;
xlabel('false positive rate') ;
ylabel('true positve rate (recall)') ;
otherwise
error('Invalid argument %s for option PLOT.', opts.plot);
end
grid on ;
xlim([0 1]) ;
ylim([0 1]) ;
axis square ;
title(sprintf('ROC (AUC = %.3g)', area), 'interpreter', 'none') ;
legend('ROC', ...
sprintf('eer %.3g %%', 100 * eer), ...
sprintf('op. unif. %.3g %%', 100 * ur), ...
sprintf('op. nat. %.3g %%', 100 * nr), ...
'ROC rand.', 'Location', 'SouthWest') ;
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/SiftFu/SiftFu/SIFTransac/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_ubcread.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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_plotsiftdescriptor.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/sift/vl_plotsiftdescriptor.m
| 4,348 |
utf_8
|
b9a98b0c298fa249fb5fcd1314762b88
|
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) > 4)
error('F should be a 2xK, 3xK, 4xK matrix or the empty matrix');
end
if size(f,1) == 2
f = [f; 10 * ones(1, size(f,2)) ; 0 * zeros(1, size(f,2))] ;
end
if size(f,1) == 3
f = [f; 0 * zeros(1, size(f,2))] ;
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
SBP = magnif * f(3,k) ;
th=f(4,k) ;
c=cos(th) ;
s=sin(th) ;
[x,y] = render_descr(d(:,k), NBP, NBO, maxv) ;
xall = [xall SBP*(c*x-s*y)+f(1,k)] ;
yall = [yall SBP*(s*x+c*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
|
vl_test_twister.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_twister.m
| 1,166 |
utf_8
|
1e18a0b343ffe164ec9c941e18575c05
|
function vl_test_twister
% VL_TEST_TWISTER
% test seed by scalar
rand('twister',1) ; a = rand ;
vl_twister('state',1) ; b = vl_twister ;
check(a,b,'twister: seed by scalar + VL_TWISTER()') ;
% read state
rand('twister') ; a = rand('twister') ;
vl_twister('state') ; b = vl_twister('state') ;
check(a,b,'twister: read state') ;
% set state
a(1) = a(1)+1 ;
rand('twister',a) ; b = rand('twister') ;
check(a,b,'twister: set state') ;
% VL_TWISTER([M N P ...])
rand('twister',b) ;
vl_twister('state',b) ;
a=rand([1 2 3 4 5]) ;
b=vl_twister([1 2 3 4 5]) ;
check(a,b,'twister: VL_TWISTER([M N P ...])') ;
% VL_TWISTER(M, N, P ...)
a=rand(1, 2, 3, 4, 5) ;
b=vl_twister(1, 2, 3, 4, 5) ;
check(a,b,'twister: VL_TWISTER(M, N, P, ...)') ;
% VL_TWISTER(M, N, P ...)
a=rand(1, 2, 3, 4, 5) ;
b=vl_twister(1, 2, 3, 4, 5) ;
check(a,b,'twister: VL_TWISTER(M, N, P, ...)') ;
% VL_TWISTER(N)
a=rand(10) ;
b=vl_twister(10) ;
check(a,b,'twister: VL_TWISTER(N)') ;
% ---------------------------------------------------------------
function check(a,b,msg)
fprintf('test: %-40s ... ', msg) ;
if isequal(a,b)
fprintf('ok.\n') ;
else
fprintf('!!!! FAIL !!!!\n') ;
keyboard
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_imintegral.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_imintegral.m
| 1,257 |
utf_8
|
d5ad8d073e99ff451cc1b692da99ec6d
|
function vl_test_imintegral
I = ones(5,6);
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;];
if ~all(all(slow_imintegral(I) == correct))
fprintf('test_imintegral: FAIL slow ones test\n');
keyboard;
end
if ~all(all(vl_imintegral(I) == correct))
fprintf('test_imintegral: FAIL ones test\n');
keyboard;
end
I = repmat(ones(5,6), [1 1 3]);
integral = vl_imintegral(I);
if ~all(all(all(integral == repmat(correct,[1 1 3]))))
fprintf('test_imintegral: FAIL multidimensional ones test\n');
keyboard;
end
ntest = 50;
for i = 1:ntest
I = rand(5);
integral = vl_imintegral(I);
slow_integral = slow_imintegral(I);
err = abs(integral - slow_integral);
if max(err(:)) > 0.00001
fprintf('test_imintegral: FAIL random test\n');
keyboard;
end
end
fprintf('test_imintegral: passed.\n');
% The slow but obvious way
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/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_sift.m
| 1,849 |
utf_8
|
cfae71614a40aebf645eb42102ca53f3
|
function vl_test_sift
% VL_TEST_SIFT Test VL_SIFT implementation(s)
I = vl_test_pattern(101);
% run various instances of the code
[a0,b0] = vl_sift(single(I),'verbose','peaktresh',0,'levels',4) ;
[a1,b1] = cmd_sift(I,'--first-octave=0 --peak-tresh=0 --levels=4') ;
[a2,b2] = cmd_sift(I,'--first-octave=0',1) ;
[a3,b3] = vl_sift(single(I),'verbose','frames',a0) ;
figure(1) ; clf ; colormap gray ; imagesc(I) ; hold on ;
h=vl_plotsiftdescriptor(b0,a0) ; set(h,'color','g','linewidth',6) ;
h=vl_plotsiftdescriptor(b1,a1) ; set(h,'color','b','linewidth',4) ;
h=vl_plotsiftdescriptor(b2,a2) ; set(h,'color','r','linewidth',2) ;
h=vl_plotsiftdescriptor(b3,a3) ; set(h,'color','y','linewidth',1) ;
title('Same descriptor computed in four ways') ;
%disp([a0 a1 a2 a3]) ;
% --------------------------------------------------------------------
function [a,b]=cmd_sift(I,param,do_read)
% --------------------------------------------------------------------
switch mexext
case 'mexmac'
arch = 'mac/sift' ;
case 'mexmaci'
arch = 'maci/sift' ;
case 'mexglx'
arch = 'glx/sift' ;
case 'dll' ;
arch = 'w32\sift.exe' ;
end
pfx = fullfile(vl_root,'results') ;
if ~ exist(pfx, 'dir')
mkdir(pfx) ;
end
pfx_sift_cmd = fullfile(vlfeat_root,'bin',arch) ;
pfx_im = fullfile(pfx,'autotest.pgm') ;
pfx_d = fullfile(pfx,'autotest.descr') ;
pfx_f = fullfile(pfx,'autotest.frame') ;
imwrite(uint8(I), pfx_im) ;
str = [pfx_sift_cmd, ' ', param, ' ', ...
' --descriptors=', pfx_d, ...,
' --frames=', pfx_f, ...,
' -v -v ' pfx_im] ;
if (nargin > 2)
str = [str ' --read-frames=' pfx_f] ;
end
fprintf('> %s\n',str) ;
[err,msg] = system(str) ;
if (err), error(msg) ; end
fprintf(msg) ;
a = load(pfx_f,'-ASCII')' ;
b = load(pfx_d,'-ASCII')' ;
if ~isempty(a), a(1:2,:) = a(1:2,:) + 1 ; end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_binsum.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_binsum.m
| 1,030 |
utf_8
|
c69da861d697e8228e243a385f5ba545
|
function vl_test_binsum
% VL_TEST_BINSUM Test VL_BINSUM function
testh({[0 0], 1, 2}, [0 1] ) ;
testh({[1 7], -1, 1}, [0 7] ) ;
testh({[1 7], -1, [1 2 2 2 2 2 2 2]}, [0 0] ) ;
testh({eye(3), [1 1 1], [1 2 3], 1 }, 2*eye(3)) ;
testh({eye(3), [1 1 1]', [1 2 3]', 2 }, 2*eye(3)) ;
testh({eye(3), 1, [1 2 3], 1 }, 2*eye(3)) ;
testh({eye(3), 1, [1 2 3]', 2 }, 2*eye(3)) ;
Z = zeros(3,3,3) ;
B = 3*ones(3,1,3) ;
R = Z ; R(:,3,:) = 17 ;
testh({Z, 17, B, 2}, R) ;
Z = zeros(3,3,3) ;
B = 3*ones(3,3,1) ;
X = zeros(3,3,1) ; X(:,:,1) = 17 ;
R = Z ; R(:,:,3) = 17 ;
testh({Z, X, B, 3}, R) ;
function testh(args, H_)
H__ = vl_binsum(args{:}) ;
if any(any(any(H_ ~= H__)))
fprintf('H:\n') ; disp(args{1});
fprintf('X:\n') ; disp(args{2});
fprintf('B:\n') ; disp(args{3});
if length(args) > 3,
fprintf('d:\n') ; disp(args{4}) ;
end
fprintf('R computed:\n') ; disp(H__) ;
fprintf('R correct:\n') ; disp(H_) ;
error('vl_binsum regression test failed') ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_imsmooth.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_imsmooth.m
| 1,566 |
utf_8
|
27ae6791e4ca852539a031b78ae7a00b
|
function vl_test_imsmooth
I = im2double(imread('data/spots.jpg')) ;
I = max(min(imresize(I,2),1),0) ;
I = single(I) ;
global fign ;
fign = 1 ;
step = 1 ;
ker = 'gaussian' ;
testmany(I,'triangular',1) ;
testmany(I,'triangular',2) ;
testmany(I,'gaussian',1) ;
testmany(I,'gaussian',2) ;
function testmany(I,ker,step)
global fign ;
sigmar = [0, 1, 10, 100] ;
for sigma = sigmar
[I1,I2,I3] = testone(I,ker,sigma,step) ;
compare(fign,I1,I2,I3,sprintf('%s, sigma %g, sub. step %d', ker, sigma, step)) ;
fign=fign+1 ;
end
function I=icut(I)
I=min(max(I,0),1) ;
function [I1,I2,I3]=testone(I,ker,sigma,step)
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) ;
I1 = imconv(I,g) ;
I1 = I1(1:step:end,1:step:end,:) ;
I2 = vl_imsmooth(I,sigma,'kernel',ker,'padding','zero', 'verbose','subsample',step) ;
I3 = vl_imsmooth(I,sigma,'kernel',ker,'padding','continuity','verbose','subsample',step) ;
function compare(n,I1,I2,I3,tit)
figure(n) ; clf ; colormap gray ;
subplot(1,3,1) ; axis equal ; imagesc(icut(I1)) ; axis off ;
title('Matlab zeropad') ;
subplot(1,3,2) ; axis equal ; imagesc(abs(I1-I2)) ; axis off ;
title('matlab - imsmooth') ;
subplot(1,3,3) ; axis equal ; imagesc(icut(I3)) ; axis off ;
title('vl_imsmooth contpad') ;
set(n,'name',tit) ;
function I=imconv(I,g)
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
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_hikmeans.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_hikmeans.m
| 2,037 |
utf_8
|
f57532e5de667fbe2f6cb9c714f20457
|
function vl_test_hikmeans
% VL_TEST_HIKMEANS Test VL_HIKMEANS function
K = 2;
nleaves = 2;
data = uint8(rand(2,100)*255);
[tree,A] = vl_hikmeans(data,K,nleaves,'verbose','verbose');
%keyboard;
K = 3 ;
nleaves = 100 ;
data = uint8(rand(2,1000) * 255) ;
datat = uint8(rand(2,10000)* 255) ;
[tree,A] = vl_hikmeans(data,K,nleaves,'verbose', 'verbose') ;
AT = vl_hikmeanspush(tree,datat,'verbose','verbose') ;
%keyboard
figure(1) ; clf ;
plottree(tree) ;
axis off ; axis equal ; xlim([0 255]) ; ylim([0 255]) ;
vl_demo_print('hikmeans-tree') ;
figure(2) ; clf ; hold on ;
hold on ;
cl = get(gca,'ColorOrder') ;
ncl = size(cl,1) ;
for k=1:K*K
sel=find(A(end,:)==k) ;
plot(data(1,sel),data(2,sel), '.','Color',cl(mod(k,ncl)+1,:)) ;
sel=find(AT(end,:)==k) ;
plot(datat(1,sel),datat(2,sel),'+','Color',cl(mod(k,ncl)+1,:)) ;
end
h=plottree(tree) ;
set(h,'LineWidth',4) ;
axis off ; axis equal ; xlim([0 255]) ; ylim([0 255]) ;
vl_demo_print('hikmeans-clusters') ;
% --------------------------------------------------------------------
function h=plottree(tree)
% --------------------------------------------------------------------
% PLOTTRE Plot hierarchical K-means tree
% PLOTTREE(TREE) plots a tree generated by HIKMEASN().
%
% See also:VL_HIKMEANS().
x1=[] ;
x2=[] ;
for c=1:size(tree.centers,2)
[x1p x2p]=xplot(tree.centers(:,c), tree.sub(c)) ;
x1 = [x1 x1p] ;
x2 = [x2 x2p] ;
end
h=line(x1(:),x2(:)) ;
% --------------------------------------------------------------------
function [x1,x2]=xplot(X,tree)
% --------------------------------------------------------------------
x1=[] ;
x2=[] ;
if(~isstruct(tree)), return ; end ;
C = size(tree.centers,2) ;
x1 = [double(X(1))*ones(1,C); double(tree.centers(1,:)); nan*ones(1,C)] ;
x2 = [double(X(2))*ones(1,C); double(tree.centers(2,:)); nan*ones(1,C)] ;
if(any(x1>300)), keyboard ;end
if ~isempty(tree.sub)
for c=1:C
[x1p x2p]=xplot(tree.centers(:,c), tree.sub(c)) ;
x1 = [x1 x1p] ;
x2 = [x2 x2p] ;
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_homkmap.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_homkmap.m
| 1,493 |
utf_8
|
a78c933efd15a4279e2724ba4441ad76
|
function vl_test_homkmap
x = 2.^(-12:.1:0) ;
L = .3 ;
n = 4 ;
V = vl_homkmap(x, n, L, 'kchi2') ;
V_ = featureMap('chi2', n, L, x, 1) ;
V
V_
figure(1) ; clf ;
subplot(1,2,1) ;
semilogx(x,V_','-') ; hold on ;
semilogy(x,V','--') ;
subplot(1,2,2);
plot(x,V_','-') ; hold on ;
plot(x,V','--') ;
function psi = featureMap(kappa, n, L, x, g)
if nargin < 5, g = 1 ; end
if isstr(kappa)
switch kappa
case 'inters'
kappa = @(lambda) 2/pi * 1 ./ (1 + 4 * lambda.^2) ;
case 'chi2'
kappa = @(lambda) sech(pi * lambda) ;
otherwise
error('Unknown kernel') ;
end
end
l = (1:n) * L ;
skp0 = sqrt(L) * sqrt(kappa(0)) ;
s2kp = sqrt(2*L) * sqrt(kappa(l)) ;
[d, M] = size(x) ;
sz = 1 + 2*n ;
psi = zeros(d * sz, M) ;
% do this in blocks to avoid using too much memory
br = [1:ceil(2e6 / d):M, M+1] ;
if br(end) < M, br(end+1) = M ; end
for bi = 1:length(br)-1
sel = br(bi) : br(bi+1)-1 ;
%sqx = sqrt(x(:, sel)) ;
sqx = x(:, sel).^(g/2) ;
lgx = log(x(:, sel) + eps) ;
psi(1:d, sel) = skp0 * sqx ;
for i=1:n
llgx = l(i) * lgx ;
psi(2*d*(i-1) + d + (1:d), sel) = s2kp(i) * cos(llgx) .* sqx ;
psi(2*d*(i-1) + 2*d + (1:d), sel) = s2kp(i) * sin(llgx) .* sqx ;
end
end
% sanity check
if 0
for j = 1:M
for i = 1:d
psi_((i-1)*sz + (1:sz), j) = ...
sqrt(x(i,j)) * [ ...
skp0, ...
s2kp .* cos(l * log(x(i,j))), ...
s2kp .* sin(l * log(x(i,j))) ]' ;
end
end
%keyboard
psi = psi_ ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_aibhist.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_aibhist.m
| 2,263 |
utf_8
|
d46c6fa557ab0d00e465eaedd060add9
|
% VL_TEST_AIBHIST
function vl_test_aibhist
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 ;
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) ;
[parents, cost ] = vl_aib(Pcx,'clusternull') ;
% find a null node for testing purposes
anull = min(find(parents_==0)) ;
f1 = [f1 repmat(anull,1,10)] ;
figure(100); clf ;
subplot(1,2,1) ; hold on ;
plot(parents_, 'r.-') ;
plot(parents, 'g') ;
legend('signal null', 'cluster null') ;
subplot(1,2,2) ; hold on ;
plot(cost_, 'r.-') ;
plot(cost, 'g') ;
legend('signal null', 'cluster null') ;
range = [1 10 K*K-10 K*K] ;
for c=1:length(range)
cut_size = range(c) ;
% compare two methods of getting the same cut histogram
[cut_,map_] = vl_aibcut(parents_, cut_size) ;
hist_ = vl_aibcuthist(map_, f1, 'nulls', 'append') ;
histtree_ = vl_aibhist(parents_, f1) ;
thist_ = histtree_(cut_) ;
[cut,map] = vl_aibcut(parents, cut_size) ;
hist = vl_aibcuthist(map, f1, 'nulls', 'append') ;
histtree = vl_aibhist(parents, f1) ;
thist = histtree(cut) ;
figure(100 + c) ; clf ;
subplot(2,2,1) ; hold on ; plot(hist_,'g.-') ; plot(thist_,'r') ;
legend('cut+cuthist', 'hist+cut') ;
title('vl_aibcuthist vs aibhist');
subplot(2,2,2) ; hold on ; plot(histtree_) ; title('aibtree') ;
subplot(2,2,3) ; hold on ; plot(hist,'g.-') ; plot(thist,'r') ;
legend('cut+cuthist', 'hist+cut') ;
title('vl_aibcuthist vs vl_aibhist (clust null)');
subplot(2,2,4) ; hold on ; plot(histtree) ; title('aibtree (clust null)') ;
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) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_ikmeans.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/toolbox/test/vl_test_ikmeans.m
| 1,552 |
utf_8
|
1d5747a991a0d81ed4f7a2c90cd2a213
|
function vl_test_ikmeans
% VL_TEST_IKMEANS Test VL_IKMEANS function
fprintf('test_ikmeans: Testing VL_IKMEANS and IKMEANSPUSH\n')
% -----------------------------------------------------------------------
fprintf('test_ikmeans: Testing Lloyd algorithm\n')
K = 3 ;
data = uint8(rand(2,1000) * 255) ;
datat = uint8(rand(2,10000)* 255) ;
[C,A] = vl_ikmeans(data,K,'verbose') ;
[AT] = vl_ikmeanspush(datat,C,'verbose') ;
figure(1) ; clf ; hold on ;
plot_partition(data, datat, C, A, AT) ;
title('vl_ikmeans (Lloyd algorithm)') ;
vl_demo_print('ikmeans_lloyd') ;
% -----------------------------------------------------------------------
fprintf('test_ikmeans: Testing Elkan algorithm\n')
[C,A] = vl_ikmeans(data,K,'verbose','method','elkan') ;
[AT] = vl_ikmeanspush(datat,C,'verbose','method','elkan') ;
figure(2) ; clf ; hold on ;
plot_partition(data, datat, C, A, AT) ;
title('vl_ikmeans (Elkan algorithm)') ;
vl_demo_print('ikmeans_elkan') ;
% -----------------------------------------------------------------------
function plot_partition(data, datat, C, A, AT)
% -----------------------------------------------------------------------
K = size(C,2) ;
cl = get(gca,'ColorOrder') ;
ncl = size(cl,1) ;
for k=1:K
sel = find(A == k) ;
selt = find(AT == k) ;
vl_plotframe(data(:,sel), '.','Color',cl(mod(k,ncl)+1,:)) ;
vl_plotframe(datat(:,selt),'+','Color',cl(mod(k,ncl)+1,:)) ;
end
plot(C(1,:),C(2,:),'ko','markersize',10','linewidth',6) ;
plot(C(1,:),C(2,:),'yo','markersize',10','linewidth',1) ;
axis off ; axis equal ;
|
github
|
jianxiongxiao/ProfXkit-master
|
phow_caltech101.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/vlfeat/apps/phow_caltech101.m
| 11,269 |
utf_8
|
91ef403a7a3865b32e7a5673350fec49
|
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) ;
%
% AUTORIGHTS
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 = 'pegasos' ;
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') ;
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 'pegasos'
lambda = 1 / (conf.svm.C * length(selTrain)) ;
w = [] ;
% for ci = 1:length(classes)
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) = vl_pegasos(psix(:,selTrain(perm)), ...
int8(y(perm)), lambda, ...
'NumIterations', 50/lambda, ...
'BiasMultiplier', conf.svm.biasMultiplier) ;
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' ;
end
model.b = conf.svm.biasMultiplier * w(end, :) ;
model.w = w(1:end-1, :) ;
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 appearance
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', 15)) ;
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, .7, 'kchi2') ;
scores = model.w' * psix + model.b' ;
[score, best] = max(scores) ;
className = model.classes{best} ;
|
github
|
jianxiongxiao/ProfXkit-master
|
sift_mosaic.m
|
.m
|
ProfXkit-master/SiftFu/SiftFu/SIFTransac/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
|
off2im.m
|
.m
|
ProfXkit-master/RenderMe/RenderDepth/off2im.m
| 2,233 |
utf_8
|
fc56dd8b10c07046b05234a11bc34c68
|
function depth = off2im(offfile, ratio, xzRot, tilt, objz, objx)
if ~exist('xzRot', 'var')
xzRot = rand() * pi*2;
end
if ~exist('tilt', 'var')
tilt = - rand() * 0.1 * pi;
end
if ~exist('objz', 'var')
objz = 1.5 + rand() * 4; % 1.5 to 5.5
end
if ~exist('objx', 'var')
objx = (rand()*0.5-0.25) .* objz;
end
if ~exist('ratio', 'var')
ratio = 2;
end
%% Camera Paramter
fx_rgb = 5.1885790117450188e+02 * ratio;
fy_rgb = 5.1946961112127485e+02 * ratio;
cx_rgb = 3.2558244941119034e+02 * ratio;
cy_rgb = 2.5373616633400465e+02 * ratio;
K=[fx_rgb 0 cx_rgb; 0 fy_rgb cy_rgb; 0 0 1];
imw = 640 * ratio;
imh = 480 * ratio;
C = [0;1.7;0]; % y off should be 1.7
z_near = 0.3;
z_far_ratio = 1.2;
Ryzswi = [1, 0, 0; 0, 0, 1; 0, 1, 0];
%%
offobj = offLoader(offfile);
offobj.vmat = Ryzswi * offobj.vmat;
Robj = genRotMat(xzRot);
Rcam = genTiltMat(tilt);
P = K * Rcam * [eye(3), -C];
vmat = scalePoints(Robj * offobj.vmat, [objx;1.3;objz], [1;1;1]);
result = RenderMex(P, imw, imh, vmat, uint32(offobj.fmat))';
depth = z_near./(1-double(result)/2^32);
maxDepth = max(depth(abs(depth) < 100));
cropmask = (depth < z_near) | (depth > z_far_ratio * maxDepth);
crop = findCropRegion(~cropmask);
depth = depth(crop(1)+(1:crop(3)), crop(2)+(1:crop(4)));
depth(cropmask(crop(1)+(1:crop(3)), crop(2)+(1:crop(4)))) = z_far_ratio * maxDepth;
end
function crop = findCropRegion(mask)
[xlist, ylist] = ind2sub(size(mask), find(mask));
xmin = min(xlist); xmax = max(xlist);
ymin = min(ylist); ymax = max(ylist);
crop = [xmin, ymin, xmax - xmin, ymax - ymin];
end
function R = genRotMat(theta)
R = [cos(theta), 0, -sin(theta)
0, 1, 0
sin(theta), 0, cos(theta)];
end
function R = genTiltMat(theta)
R = [1, 0, 0
0, cos(theta), -sin(theta)
0, sin(theta), cos(theta)];
end
function coornew = scalePoints(coor, center, size)
% function coornew = scalePoints(coor, box)
%
% parameters:
% coor: 3*n coordinates of n points
% center: 3*1 the center of new point cloud
% size: 3*1 the size of new point cloud
minv = min(coor, [], 2);
maxv = max(coor, [], 2);
oldCenter = (minv+maxv)/2;
oldSize = maxv - minv;
scale = min(size ./ oldSize);
coornew = bsxfun(@plus, scale * coor, center-scale*oldCenter);
end
|
github
|
jianxiongxiao/ProfXkit-master
|
quaternion.m
|
.m
|
ProfXkit-master/GCBreader/quaternion.m
| 87,509 |
utf_8
|
fb98a96f24335e62ddb5b837a2fb1f97
|
classdef quaternion
% classdef quaternion, implements quaternion mathematics and 3D rotations
%
% Properties (SetAccess = protected):
% e(4,1) components, basis [1; i; j; k]: e(1) + i*e(2) + j*e(3) + k*e(4)
% i*j=k, j*i=-k, j*k=i, k*j=-i, k*i=j, i*k=-j, i*i = j*j = k*k = -1
%
% Constructors:
% q = quaternion scalar zero quaternion, q.e = [0;0;0;0]
% q = quaternion(x) x is a matrix size [4,s1,s2,...] or [s1,4,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% x(1:4,i1,i2,...) or x(i1,1:4,i2,...).'
% q = quaternion(v) v is a matrix size [3,s1,s2,...] or [s1,3,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% [0;v(1:3,i1,i2,...)] or [0;v(i1,1:3,i2,...).']
% q = quaternion(c) c is a complex matrix size [s1,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% [real(c(i1,i2,...));imag(c(i1,i2,...));0;0]
% q = quaternion(x1,x2) x1,x2 are matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [x1(i1,i2,...);x2(i1,i2,...);0;0]
% q = quaternion(v1,v2,v3) v1,v2,v3 matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [0;v1(i1,i2,...);v2(i1,i2,...);...
% v3(i1,i2,...)]
% q = quaternion(x1,x2,x3,x4) x1,x2,x3,x4 matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [x1(i1,i2,...);x2(i1,i2,...);...
% x3(i1,i2,...);x4(i1,i2,...)]
%
% Quaternion array constructor methods:
% q = quaternion.eye(N) quaternion NxN identity matrix
% q = quaternion.nan(siz) q(:).e = [NaN;NaN;NaN;NaN]
% q = quaternion.ones(siz) q(:).e = [1;0;0;0]
% q = quaternion.rand(siz) uniform random quaternions, NOT normalized
% to 1, 0 <= q.e(1) <= 1, -1 <= q.e(2:4) <= 1
% q = quaternion.randRot(siz) random quaternions uniform in rotation space
% q = quaternion.zeros(siz) q(:).e = [0;0;0;0]
%
% Rotation constructor methods (all lower case):
% q = quaternion.angleaxis(angle,axis)
% angle is an array in radians, axis is an array
% of vectors size [3,s1,s2,...] or [s1,3,s2,...],
% q is size [s1,s2,...], quaternions normalized to 1
% equivalent to rotations about axis by angle
% q = quaternion.eulerangles(axes,angles) or
% q = quaternion.eulerangles(axes,ang1,ang2,ang3)
% axes is a string array or cell string array,
% '123' = 'xyz' = 'XYZ' = 'ijk', etc.,
% angles is an array of Euler angles in radians,
% size [3,s1,s2,...] or [s1,3,s2,...], or
% (ang1, ang2, ang3) are arrays or scalars of
% Euler angles in radians, q is size
% [s1,s2,...], quaternions normalized to 1
% equivalent to Euler Angle rotations
% q = quaternion.rotateutov(u,v,dimu,dimv)
% quaternions normalized to 1 that rotate 3
% element vectors u into the directions of 3
% element vectors v
% q = quaternion.rotationmatrix(R)
% R is an array of rotation or Direction Cosine
% Matrices size [3,3,s1,s2,...] with det(R) == 1,
% q(i1,i2,...) = quaternions normalized to 1,
% equivalent to R(1:3,1:3,i1,i2,...)
%
% Rotation methods (Mixed Case):
% [angle,axis] = AngleAxis(q) angles in radians, unit vector rotation axes
% equivalent to q
% qd = Derivative(q,w) quaternion derivatives, w are 3 component
% angular velocity vectors, qd = 0.5*q*quaternion(w)
% angles = EulerAngles(q,axes) angles are 3 Euler angles equivalent to q, axes
% are strings or cell strings, '123' = 'xyz', etc.
% [omega,axis] = OmegaAxis(q,t,dim)
% instantaneous angular velocities and rotation axes
% PlotRotation(q,interval) plot columns of rotation matrices of q,
% pause interval between figure updates in seconds
% [q1,w1,t1] = PropagateEulerEq(q0,w0,I,t,@torque,odeoptions)
% Euler equation numerical propagator, see
% help quaternion.PropagateEulerEq
% vp = RotateVector(q,v,dim) vp are 3 component vectors, rotations q acting
% on vectors v, uses rotation matrix multiplication
% vp = RotateVectorQ(q,v,dim) vp are 3 component vectors, rotations q acting
% on vectors v, uses quaternion multiplication,
% RotateVector is 7 times faster than RotateVectorQ
% R = RotationMatrix(q) 3x3 rotation matrices equivalent to q
%
% Note:
% In all rotation operations, the rotations operate from left to right on
% 3x1 column vectors and create rotated vectors, not representations of
% those vectors in rotated coordinate systems.
% For Euler angles, '123' means rotate the vector about x first, about y
% second, about z third, i.e.:
% vp = rotate(z,angle(3)) * rotate(y,angle(2)) * rotate(x,angle(1)) * v
%
% Ordinary methods:
% n = abs(q) quaternion norm, n = sqrt( sum( q.e.^2 ))
% q3 = bsxfun(func,q1,q2) binary singleton expansion of operation func
% c = complex(q) complex( real(q), imag(q) )
% qc = conj(q) quaternion conjugate, qc.e =
% [q.e(1);-q.e(2);-q.e(3);-q.e(4)]
% qt = ctranspose(q) qt = q'; quaternion conjugate transpose,
% 2-D (or scalar) q only
% qp = cumprod(q,dim) cumulative quaternion array product over
% dimension dim
% qs = cumsum(q,dim) cumulative quaternion array sum over dimension dim
% qd = diff(q,ord,dim) quaternion array difference, order ord, over
% dimension dim
% ans = display(q) 'q = ( e(1) ) + i( e(2) ) + j( e(3) ) + k( e(4) )'
% d = dot(q1,q2) quaternion element dot product, d = dot(q1.e,q2.e)
% d = double(q) d = q.e; if size(q) == [s1,s2,...], size(d) ==
% [4,s1,s2,...]
% l = eq(q1,q2) quaternion equality, l = all( q1.e == q2.e )
% l = equiv(q1,q2,tol) quaternion rotational equivalence, within
% tolerance tol, l = (q1 == q2) | (q1 == -q2)
% qe = exp(q) quaternion exponential, v = q.e(2:4), qe.e =
% exp(q.e(1))*[cos(|v|);v.*sin(|v|)./|v|]
% ei = imag(q) imaginary e(2) components
% qi = interp1(t,q,ti,method) interpolate quaternion array
% qi = inverse(q) quaternion inverse, qi = conj(q)./norm(q).^2,
% q .* qi = qi .*.q = 1 for q ~= 0
% l = isequal(q1,q2,...) true if equal sizes and values
% l = isequaln(q1,q2,...) true if equal including NaNs
% l = isequalwithequalnans(q1,q2,...) true if equal including NaNs
% l = isfinite(q) true if all( isfinite( q.e ))
% l = isinf(q) true if any( isinf( q.e ))
% l = isnan(q) true if any( isnan( q.e ))
% ej = jmag(q) e(3) components
% ek = kmag(q) e(4) components
% q3 = ldivide(q1,q2) quaternion left division, q3 = q1 \. q2 =
% inverse(q1) *. q2
% ql = log(q) quaternion logarithm, v = q.e(2:4), ql.e =
% [log(|q|);v.*acos(q.e(1)./|q|)./|v|]
% q3 = minus(q1,q2) quaternion subtraction, q3 = q1 - q2
% q3 = mldivide(q1,q2) left division only defined for scalar q1
% qp = mpower(q,p) quaternion matrix power, qp = q^p, p scalar
% integer >= 0, q square quaternion matrix
% q3 = mrdivide(q1,q2) right division only defined for scalar q2
% q3 = mtimes(q1,q2) 2-D matrix quaternion multiplication, q3 = q1 * q2
% l = ne(q1,q2) quaternion inequality, l = ~all( q1.e == q2.e )
% n = norm(q) quaternion norm, n = sqrt( sum( q.e.^2 ))
% [q,n] = normalize(q) make quaternion norm == 1, unless q == 0,
% n = matrix of previous norms
% q3 = plus(q1,q2) quaternion addition, q3 = q1 + q2
% qp = power(q,p) quaternion power, qp = q.^p
% qp = prod(q,dim) quaternion array product over dimension dim
% qp = product(q1,q2) quaternion product of scalar quaternions,
% qp = q1 .* q2, noncommutative
% q3 = rdivide(q1,q2) quaternion right division, q3 = q1 ./ q2 =
% q1 .* inverse(q2)
% er = real(q) real e(1) components
% qs = slerp(q0,q1,t) quaternion spherical linear interpolation
% qr = sqrt(q) qr = q.^0.5, square root
% qs = sum(q,dim) quaternion array sum over dimension dim
% q3 = times(q1,q2) matrix component quaternion multiplication,
% q3 = q1 .* q2, noncommutative
% qm = uminus(q) quaternion negation, qm = -q
% qp = uplus(q) quaternion unitary plus, qp = +q
% ev = vector(q) vector e(2:4) components
%
% Author:
% Mark Tincknell, MIT LL, 29 July 2011, revised 22 November 2013
properties (SetAccess = protected)
e = zeros(4,1);
end % properties
% Array constructors
methods
function q = quaternion( varargin ) % (constructor)
perm = [];
sqz = false;
switch nargin
case 0 % nargin == 0
q.e = zeros(4,1);
return;
case 1 % nargin == 1
siz = size( varargin{1} );
nel = prod( siz );
if nel == 0
q = quaternion.empty;
return;
elseif isa( varargin{1}, 'quaternion' )
q = varargin{1};
return;
elseif (nel == 1) || ~isreal( varargin{1}(:) )
for iel = nel : -1 : 1
q(iel).e = chop( [real(varargin{1}(iel)); ...
imag(varargin{1}(iel)); ...
0; ...
0] );
end
q = reshape( q, siz );
return;
end
[arg4, dim4, perm4] = finddim( varargin{1}, 4 );
if dim4 > 0
siz(dim4) = 1;
nel = prod( siz );
if dim4 > 1
perm = perm4;
else
sqz = true;
end
for iel = nel : -1 : 1
q(iel).e = chop( arg4(:,iel) );
end
else
[arg3, dim3, perm3] = finddim( varargin{1}, 3 );
if dim3 > 0
siz(dim3) = 1;
nel = prod( siz );
if dim3 > 1
perm = perm3;
else
sqz = true;
end
for iel = nel : -1 : 1
q(iel).e = chop( [0; arg3(:,iel)] );
end
else
error( 'Invalid input' );
end
end
case 2 % nargin == 2
% real-imaginary only (no j or k) inputs
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
0;
0] );
end
case 3 % nargin == 3
% vector inputs (no real, only i, j, k)
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [0; ...
varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
varargin{3}(min(iel,na(3)))] );
end
otherwise % nargin >= 4
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
varargin{3}(min(iel,na(3))); ...
varargin{4}(min(iel,na(4)))] );
end
end % switch nargin
if nel == 0
q = quaternion.empty;
end
q = reshape( q, siz );
if ~isempty( perm )
q = ipermute( q, perm );
end
if sqz
q = squeeze( q );
end
end % quaternion (constructor)
% Ordinary methods
function n = abs( q )
n = q.norm;
end % abs
function q3 = bsxfun( func, q1, q2 )
% function q3 = bsxfun( func, q1, q2 )
% Binary Singleton Expansion for quaternion arrays. Apply the element by
% element binary operation specified by the function handle func to arrays
% q1 and q2. All dimensions of q1 and q2 must either agree or be length 1.
% Inputs:
% func function handle (e.g. @plus) of quaternion function or operator
% q1(n1) quaternion array
% q2(n2) quaternion array
% Output:
% q3(n3) quaternion array of function or operator outputs
% size(q3) = max( size(q1), size(q2) )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
s1 = size( q1 );
s2 = size( q2 );
nd1 = length( s1 );
nd2 = length( s2 );
s1 = [s1, ones(1,nd2-nd1)];
s2 = [s2, ones(1,nd1-nd2)];
if ~all( (s1 == s2) | (s1 == 1) | (s2 == 1) )
error( 'Non-singleton dimensions of q1 and q2 must match each other' );
end
c1 = num2cell( s1 );
c2 = num2cell( s2 );
s3 = max( s1, s2 );
nd3 = length( s3 );
n3 = prod( s3 );
q3 = quaternion.nan( s3 );
for i3 = 1 : n3
[ix3{1:nd3}] = ind2sub( s3, i3 );
ix1 = cellfun( @min, ix3, c1, 'UniformOutput', false );
ix2 = cellfun( @min, ix3, c2, 'UniformOutput', false );
q3(i3) = func( q1(ix1{:}), q2(ix2{:}) );
end
end % bsxfun
function c = complex( q )
c = complex( real( q ), imag( q ));
end % complex
function qc = conj( q )
d = double( q );
qc = reshape( quaternion( d(1,:), -d(2,:), -d(3,:), -d(4,:) ), ...
size( q ));
end % conj
function qt = ctranspose( q )
qt = transpose( q.conj );
end % ctranspose
function qp = cumprod( q, dim )
% function qp = cumprod( q, dim )
% cumulative quaternion array product, dim defaults to first dimension of
% length > 1
if isempty( q )
qp = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
qp = q;
for is = 2 : size(q,1)
qp(is,:) = qp(is-1,:) .* q(is,:);
end
if dim > 1
qp = ipermute( qp, perm );
end
end % cumprod
function qs = cumsum( q, dim )
% function qs = cumsum( q, dim )
% cumulative quaternion array sum, dim defaults to first dimension of
% length > 1
if isempty( q )
qs = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
qs = q;
for is = 2 : size(q,1)
qs(is,:) = qs(is-1,:) + q(is,:);
end
if dim > 1
qs = ipermute( qs, perm );
end
end % cumsum
function qd = diff( q, ord, dim )
% function qd = diff( q, ord, dim )
% quaternion array difference, ord is the order of difference (default = 1)
% dim defaults to first dimension of length > 1
if isempty( q )
qd = q;
return;
end
if (nargin < 2) || isempty( ord )
ord = 1;
end
if ord <= 0
qd = q;
return;
end
if (nargin < 3) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
if siz(1) <= 1
qd = quaternion.empty;
return;
end
qd = quaternion.zeros( [(siz(1)-1), siz(2:end)] );
for is = 1 : siz(1)-1
qd(is,:) = q(is+1,:) - q(is,:);
end
ord = ord - 1;
if ord > 0
qd = diff( qd, ord, 1 );
end
if dim > 1
qd = ipermute( qd, perm );
end
end % diff
function display( q )
if ~isequal( get(0,'FormatSpacing'), 'compact' )
disp(' ');
end
if isempty( q )
fprintf( '%s \t= ([]) + i([]) + j([]) + k([])\n', inputname(1) )
return;
end
siz = size( q );
nel = [1 cumprod( siz )];
ndm = length( siz );
for iel = 1 : nel(end)
if nel(end) == 1
sub = '';
else
sub = ')';
jel = iel - 1;
for idm = ndm : -1 : 1
idx = floor( jel / nel(idm) ) + 1;
sub = [',' int2str(idx) sub]; %#ok<AGROW>
jel = rem( jel, nel(idm) );
end
sub(1) = '(';
end
fprintf( '%s%s \t= (%-12.5g) + i(%-12.5g) + j(%-12.5g) + k(%-12.5g)\n', ...
inputname(1), sub, q(iel).e )
end
end % display
function d = dot( q1, q2 )
% function d = dot( q1, q2 )
% quaternion element dot product: d = dot( q1.e, q2.e ), using binary
% singleton expansion of quaternion arrays
% dn = dot( q1, q2 )/( norm(q1) * norm(q2) ) is the cosine of the angle in
% 4D space between 4D vectors q1.e and q2.e
d = squeeze( sum( bsxfun( @times, double( q1 ), double( q2 )), 1 ));
end % dot
function d = double( q )
siz = size( q );
d = reshape( [q.e], [4 siz] );
d = chop( d );
end % double
function l = eq( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
l = logical([]);
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
l = bsxfun( @eq, [q1.e], [q2.e] );
l = reshape( all( l, 1 ), siz );
end % eq
function l = equiv( q1, q2, tol )
% function l = equiv( q1, q2, tol )
% quaternion rotational equivalence, within tolerance tol,
% l = (q1 == q2) | (q1 == -q2)
% optional argument tol (default = eps) sets tolerance for difference
% from exact equality
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
if (nargin < 3) || isempty( tol )
tol = eps;
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
l = logical([]);
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
dm = chop( bsxfun( @minus, [q1.e], [q2.e] ), tol );
dp = chop( bsxfun( @plus, [q1.e], [q2.e] ), tol );
l = all( (dm == 0) | (dp == 0), 1 );
l = reshape( l, siz );
end % equiv
function qe = exp( q )
% function qe = exp( q )
% quaternion exponential, v = q.e(2:4),
% qe.e = exp(q.e(1))*[cos(|v|);v.*sin(|v|)./|v|]
d = double( q );
siz = size( d );
od = ones( 1, ndims( q ));
vn = reshape( sqrt( sum( d(2:4,:).^2, 1 )), [1 siz(2:end)] );
cv = cos( vn );
sv = sin( vn );
n0 = vn ~= 0;
sv(n0) = sv(n0) ./ vn(n0);
sv = repmat( sv, [3, od] );
ex = repmat( reshape( exp( d(1,:) ), [1 siz(2:end)] ), [4, od] );
de = ex .* [ cv; sv .* reshape( d(2:4,:), [3 siz(2:end)] )];
qe = reshape( quaternion( de(1,:), de(2,:), de(3,:), de(4,:) ), ...
size( q ));
end % exp
function ei = imag( q )
siz = size( q );
d = double( q );
ei = reshape( d(2,:), siz );
end % imag
function qi = interp1( varargin )
% function qi = interp1( t, q, ti, method ) or
% qi = q.interp1( t, ti, method ) or
% qi = interp1( q, ti, method )
% Interpolate quaternion array. If q are rotation quaternions (i.e.
% normalized to 1), then -q is equivalent to q, and the sign of q to use as
% the second knot of the interpolation is chosen by which ever is closer to
% the first knot. Extrapolation (i.e. ti < min(t) or ti > max(t)) gives
% qi = quaternion.nan.
% Inputs:
% t(nt) array of ordinates (e.g. times); if t is not provided t=1:nt
% q(nt,nq) quaternion array
% ti(ni) array of query (interpolation) points, t(1) <= ti <= t(end)
% method [OPTIONAL] 'slerp' or 'linear'; default = 'slerp'
% Output:
% qi(ni,nq) interpolated quaternion array
nna = nnz( ~cellfun( @ischar, varargin ));
im = 4;
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
siq = size( q );
if nna == 2
if isrow( q )
t = (1 : siq(2)).';
else
t = (1 : siq(1)).';
end
ti = varargin{2}(:);
im = 3;
elseif isempty( varargin{2} )
if isrow( q )
t = (1 : siq(2)).';
else
t = (1 : siq(1)).';
end
ti = varargin{3}(:);
else
t = varargin{2}(:);
ti = varargin{3}(:);
end
elseif isa( varargin{2}, 'quaternion' )
t = varargin{1}(:);
q = varargin{2};
ti = varargin{3}(:);
siq = size( q );
else
error( 'Input q must be a quaterion' );
end
neq = prod( siq );
if neq == 0
qi = quaternion.empty;
return;
end
nt = numel( t );
if siq(1) == nt
dim = 1;
else
[q, dim, perm] = finddim( q, nt );
if dim == 0
error( 'q must have a dimension the same size as t' );
end
end
iNf = interp1( t, (1:nt).', ti );
iN = max( 1, min( nt-1, floor( iNf )));
jN = max( 2, min( nt, ceil( iNf )));
iNm = repmat( iNf - iN, [1, neq / nt] );
% If q are rotation quaternions (i.e. all normalized to 1), then -q
% represents the same rotation. Pick the sign of +/-q that has the closest
% dot product to use as the second knot of the interpolation.
qj = q(jN,:);
if all( abs( norm( q(:) ) - 1 ) <= eps(16) )
qd = dot( q(iN,:), qj );
lq = qd < -qd;
qj(lq) = -qj(lq);
end
if (length( varargin ) >= im) && ...
(strncmpi( 'linear', varargin{im}, length( varargin{im} )))
qi = (1 - iNm) .* q(iN,:) + iNm .* qj;
else
qi = slerp( q(iN,:), qj, iNm );
end
if length( siq ) > 2
sin = siq;
sin(dim) = numel( ti );
sin = circshift( sin, [0, 1-dim] );
qi = reshape( qi, sin );
end
if dim > 1
qi = ipermute( qi, perm );
end
end % interp1
function qi = inverse( q )
% function qi = inverse( q )
% quaternion inverse, qi = conj(q)/norm(q)^2, q*qi = qi*q = 1 for q ~= 0
if isempty( q )
qi = q;
return;
end
d = double( q );
d(2:4,:) = -d(2:4,:);
n2 = repmat( sum( d.^2, 1 ), 4, ones( 1, ndims( d ) - 1 ));
ne0 = n2 ~= 0;
di = Inf( size( d ));
di(ne0) = d(ne0) ./ n2(ne0);
qi = reshape( quaternion( di(1,:), di(2,:), di(3,:), di(4,:) ), ...
size( q ));
end % inverse
function l = isequal( q1, varargin )
% function l = isequal( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequal( [q1.e], [q2.e] )
return;
end
end
end
l = true;
end % isequal
function l = isequaln( q1, varargin )
% function l = isequaln( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequaln( [q1.e], [q2.e] )
return;
end
end
end
l = true;
end % isequaln
function l = isequalwithequalnans( q1, varargin )
% function l = isequalwithequalnans( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequalwithequalnans( [q1.e], [q2.e] ) %#ok<FPARK>
return;
end
end
end
l = true;
end % isequalwithequalnans
function l = isfinite( q )
% function l = isfinite( q ), l = all( isfinite( q.e ))
d = [q.e];
l = reshape( all( isfinite( d ), 1 ), size( q ));
end % isfinite
function l = isinf( q )
% function l = isinf( q ), l = any( isinf( q.e ))
d = [q.e];
l = reshape( any( isinf( d ), 1 ), size( q ));
end % isinf
function l = isnan( q )
% function l = isnan( q ), l = any( isnan( q.e ))
d = [q.e];
l = reshape( any( isnan( d ), 1 ), size( q ));
end % isnan
function ej = jmag( q )
siz = size( q );
d = double( q );
ej = reshape( d(3,:), siz );
end % jmag
function ek = kmag( q )
siz = size( q );
d = double( q );
ek = reshape( d(4,:), siz );
end % kmag
function q3 = ldivide( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)).inverse, ...
q2(min(iel,ne2)) );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % ldivide
function ql = log( q )
% function ql = log( q )
% quaternion logarithm, v = q.e(2:4), ql.e = [log(|q|);v.*acos(q.e(1)./|q|)./|v|]
% logarithm of negative real quaternions is ql.e = [log(|q|);pi;0;0]
d = double( q );
d2 = d.^2;
siz = size( d );
od = ones( 1, ndims( q ));
[vn,qn] = deal( zeros( [1 siz(2:end)] ));
vn(:) = sqrt( sum( d2(2:4,:), 1 ));
qn(:) = sqrt( sum( d2(1:4,:), 1 ));
lq = log( qn );
d1 = reshape( d(1,:), [1 siz(2:end)] );
nq = qn ~= 0;
d1(nq) = d1(nq) ./ qn(nq);
ac = acos( d1 );
nv = vn ~= 0;
ac(nv) = ac(nv) ./ vn(nv);
ac = reshape( repmat( ac, [3, od] ), 3, [] );
va = reshape( d(2:4,:) .* ac, [3 siz(2:end)] );
nn = (d1 < 0) & (vn == 0);
va(1,nn)= pi;
dl = [ lq; va ];
ql = reshape( quaternion( dl(1,:), dl(2,:), dl(3,:), dl(4,:) ), ...
size( q ));
end % log
function q3 = minus( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
d3 = bsxfun( @minus, [q1.e], [q2.e] );
q3 = quaternion( d3(1,:), d3(2,:), d3(3,:), d3(4,:) );
q3 = reshape( q3, siz );
end % minus
function q3 = mldivide( q1, q2 )
% function q3 = mldivide( q1, q2 ), left division only defined for scalar q1
if numel( q1 ) > 1
error( 'Left matix division undefined for quaternion arrays' );
end
q3 = ldivide( q1, q2 );
end % mldivide
function qp = mpower( q, p )
% function qp = mpower( q, p ), quaternion matrix power
siq = size( q );
neq = prod( siq );
nep = numel( p );
if neq == 1
qp = power( q, p );
return;
elseif isa( p, 'quaternion' )
error( 'Quaternion as matrix exponent is not defined' );
end
if (neq == 0) || (nep == 0)
qp = quaternion.empty;
return;
elseif (nep > 1) || (mod( p, 1 ) ~= 0) || (p < 0) || ...
(numel( siq ) > 2) || (siq(1) ~= siq(2))
error( 'Inputs must be a scalar non-negative integer power and a square quaternion matrix' );
elseif p == 0
qp = quaternion.eye( siq(1) );
return;
end
qp = q;
for ip = 2 : p
qp = qp * q;
end
end % mpower
function q3 = mrdivide( q1, q2 )
% function q3 = mrdivide( q1, q2 ), right division only defined for scalar q2
if numel( q2 ) > 1
error( 'Right matix division undefined for quaternion arrays' );
end
q3 = rdivide( q1, q2 );
end % mrdivide
function q3 = mtimes( q1, q2 )
% function q3 = mtimes( q1, q2 )
% q3 = matrix quaternion product of 2-D conformable quaternion matrices q1
% and q2
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 1) || (ne2 == 1)
q3 = times( q1, q2 );
return;
end
if (length( si1 ) ~= 2) || (length( si2 ) ~= 2)
error( 'Input arguments must be 2-D' );
end
if si1(2) ~= si2(1)
error( 'Inner matrix dimensions must agree' );
end
q3 = repmat( quaternion, [si1(1) si2(2)] );
for i1 = 1 : si1(1)
for i2 = 1 : si2(2)
for i3 = 1 : si1(2)
q3(i1,i2) = q3(i1,i2) + product( q1(i1,i3), q2(i3,i2) );
end
end
end
end % mtimes
function l = ne( q1, q2 )
l = ~eq( q1, q2 );
end % ne
function n = norm( q )
n = shiftdim( sqrt( sum( double( q ).^2, 1 )), 1 );
end % norm
function [q, n] = normalize( q )
% function [q, n] = normalize( q )
% q = quaternions with norm == 1 (unless q == 0), n = former norms
siz = size( q );
nel = prod( siz );
if nel == 0
if nargout > 1
n = zeros( siz );
end
return;
elseif nel > 1
nel = [];
end
d = double( q );
n = sqrt( sum( d.^2, 1 ));
if all( n(:) == 1 )
if nargout > 1
n = shiftdim( n, 1 );
end
return;
end
n4 = repmat( n, 4, nel );
ne0 = (n4 ~= 0) & (n4 ~= 1);
d(ne0) = d(ne0) ./ n4(ne0);
q = reshape( quaternion( d(1,:), d(2,:), d(3,:), d(4,:) ), siz );
if nargout > 1
n = shiftdim( n, 1 );
end
end % normalize
function q3 = plus( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
d3 = bsxfun( @plus, [q1.e], [q2.e] );
q3 = quaternion( d3(1,:), d3(2,:), d3(3,:), d3(4,:) );
q3 = reshape( q3, siz );
end % plus
function qp = power( q, p )
% function qp = power( q, p ), quaternion power
siq = size( q );
sip = size( p );
neq = prod( siq );
nep = prod( sip );
if (neq == 0) || (nep == 0)
qp = quaternion.empty;
return;
elseif ~isequal( siq, sip ) && (neq ~= 1) && (nep ~= 1)
error( 'Matrix dimensions must agree' );
end
qp = exp( p .* log( q ));
end % power
function qp = prod( q, dim )
% function qp = prod( q, dim )
% quaternion array product over dimension dim
% dim defaults to first dimension of length > 1
if isempty( q )
qp = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
qp = reshape( q(1,:), [1 siz(2:end)] );
for is = 2 : siz(1)
qp(1,:) = qp(1,:) .* q(is,:);
end
if dim > 1
qp = ipermute( qp, perm );
end
end % prod
function q3 = product( q1, q2 )
% function q3 = product( q1, q2 )
% q3 = quaternion product of scalar quaternions q1 and q2
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
if (numel( q1 ) ~= 1) || (numel( q2 ) ~= 1)
error( 'product not defined for arrays, use mtimes or times' );
end
ee = q1.e * q2.e.';
eo = [ee(1,1) - ee(2,2) - ee(3,3) - ee(4,4); ...
ee(1,2) + ee(2,1) + ee(3,4) - ee(4,3); ...
ee(1,3) - ee(2,4) + ee(3,1) + ee(4,2); ...
ee(1,4) + ee(2,3) - ee(3,2) + ee(4,1)];
eo = chop( eo );
q3 = quaternion( eo(1), eo(2), eo(3), eo(4) );
end % product
function q3 = rdivide( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)), ...
q2(min(iel,ne2)).inverse );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % rdivide
function er = real( q )
siz = size( q );
d = double( q );
er = reshape( d(1,:), siz );
end % real
function qs = slerp( q0, q1, t )
% function qs = slerp( q0, q1, t )
% quaternion spherical linear interpolation, qs = q0.*(q0.inverse.*q1).^t,
% default t = 0.5; see http://en.wikipedia.org/wiki/Slerp
if (nargin < 3) || isempty( t )
t = 0.5;
end
qs = q0 .* (q0.inverse .* q1).^t;
end % slerp
function qr = sqrt( q )
qr = q.^0.5;
end % sqrt
function qs = sum( q, dim )
% function qs = sum( q, dim )
% quaternion array sum over dimension dim
% dim defaults to first dimension of length > 1
if isempty( q )
qs = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
qs = reshape( q(1,:), [1 siz(2:end)] );
for is = 2 : siz(1)
qs(1,:) = qs(1,:) + q(is,:);
end
if dim > 1
qs = ipermute( qs, perm );
end
end % sum
function q3 = times( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)), q2(min(iel,ne2)) );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % times
function qm = uminus( q )
d = -double( q );
qm = reshape( quaternion( d(1,:), d(2,:), d(3,:), d(4,:) ), ...
size( q ));
end % uminus
function qp = uplus( q )
qp = q;
end % uplus
function ev = vector( q )
siz = size( q );
d = double( q );
ev = reshape( d(2:4,:), [3 siz] );
end % vector
function [angle, axis] = AngleAxis( q )
% function [angle, axis] = AngleAxis( q ) or [angle, axis] = q.AngleAxis
% Construct angle-axis pairs equivalent to quaternion rotations
% Input:
% q quaternion array
% Outputs:
% angle rotation angles in radians, 0 <= angle <= 2*pi
% axis 3xN or Nx3 rotation axis unit vectors
% Note: angle and axis are constructed so at least 2 out of 3 elements of
% axis are >= 0.
siz = size( q );
ndm = length( siz );
[angle, s] = deal( zeros( siz ));
axis = zeros( [3 siz] );
nel = prod( siz );
if nel == 0
return;
end
[q, n] = normalize( q );
d = double( q );
neg = repmat( reshape( d(1,:) < 0, [1 siz] ), ...
[4, ones(1,ndm)] );
d(neg) = -d(neg);
angle(1:end)= 2 * acos( d(1,:) );
s(1:end) = sin( 0.5 * angle );
angle(n==0) = 0;
s(s==0) = 1;
s3 = shiftdim( s, -1 );
axis(1:end) = bsxfun( @rdivide, reshape( d(2:4,:), [3 siz] ), s3 );
axis(1,(mod(angle,2*pi)==0)) = 1;
angle = chop( angle );
axis = chop( axis );
% Flip axis so at least 2 out of 3 elements are >= 0
flip = (sum( axis < 0, 1 ) > 1) | ...
((sum( axis == 0, 1 ) == 2) & (any( axis < 0, 1 ) == 1));
angle(flip) = 2 * pi - angle(flip);
flip = repmat( flip, [3, ones(1,ndm)] );
axis(flip) = -axis(flip);
axis = squeeze( axis );
end % AngleAxis
function qd = Derivative( varargin )
% function qd = Derivative( q, w ) or qd = q.Derivative( w )
% Inputs:
% q quaternion array
% w 3xN or Nx3 element angle rate vectors in radians/s
% Output:
% qd quaternion derivatives, qd = 0.5 * q * quaternion(w)
if isa( varargin{1}, 'quaternion' )
qd = 0.5 .* varargin{1} .* quaternion( varargin{2} );
else
qd = 0.5 .* varargin{2} .* quaternion( varargin{1} );
end
end % Derivative
function angles = EulerAngles( varargin )
% function angles = EulerAngles( q, axes ) or angles = q.EulerAngles( axes )
% Construct Euler angle triplets equivalent to quaternion rotations
% Inputs:
% q quaternion array
% axes axes designation strings (e.g. '123' = xyz) or cell strings
% (e.g. {'123'})
% Output:
% angles 3 element Euler Angle vectors in radians
ics = cellfun( @ischar, varargin );
if any( ics )
varargin{ics} = cellstr( varargin{ics} );
else
ics = cellfun( @iscellstr, varargin );
end
if ~any( ics )
error( 'Must provide axes as a string (e.g. ''123'') or cell string (e.g. {''123''})' );
end
siv = cellfun( @size, varargin, 'UniformOutput', false );
axes = varargin{ics};
six = siv{ics};
nex = prod( six );
q = varargin{~ics};
siq = siv{~ics};
neq = prod( siq );
if neq == 1
siz = six;
nel = nex;
elseif nex == 1
siz = siq;
nel = neq;
elseif nex == neq
siz = siq;
nel = neq;
else
error( 'Must have compatible dimensions for quaternion and axes' );
end
angles = zeros( [3 siz] );
q = normalize( q );
for jel = 1 : nel
iel = min( jel, neq );
switch axes{min(jel,nex)}
case {'121', 'xyx', 'XYX', 'iji'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(3)- ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
angles(2,iel) = acos(q(iel).e(1).^2+q(iel).e(2).^2- ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
case {'123', 'xyz', 'XYZ', 'ijk'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(4).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
case {'131', 'xzx', 'XZX', 'iki'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
angles(2,iel) = acos(q(iel).e(1).^2+q(iel).e(2).^2- ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(4)- ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
case {'132', 'xzy', 'XZY', 'ikj'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(4).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
angles(3,iel) = atan2(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
case {'212', 'yxy', 'YXY', 'jij'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2+ ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(3)- ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
case {'213', 'yxz', 'YXZ', 'jik'}
angles(1,iel) = atan2(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(4).*q(iel).e(2)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
case {'231', 'yzx', 'YZX', 'jki'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
case {'232', 'yzy', 'YZY', 'jkj'}
angles(1,iel) = atan2((q(iel).e(3).*q(iel).e(4)- ...
q(iel).e(2).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2+ ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
case {'312', 'zxy', 'ZXY', 'kij'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
case {'313', 'zxz', 'ZXZ', 'kik'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(4)- ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2- ...
q(iel).e(3).^2+q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
case {'321', 'zyx', 'ZYX', 'kji'}
angles(1,iel) = atan2(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
case {'323', 'zyz', 'ZYZ', 'kjk'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2- ...
q(iel).e(3).^2+q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(3).*q(iel).e(4)- ...
q(iel).e(2).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
otherwise
error( 'Invalid output Euler angle axes' );
end % switch axes
end % for iel
angles = chop( angles );
end % EulerAngles
function [omega, axis] = OmegaAxis( q, t, dim )
% function [omega, axis] = OmegaAxis( q, t, dim ) or
% [omega, axis] = q.OmegaAxis( t, dim )
% Estimate instantaneous angular velocities and rotation axes from a time
% series of quaternions. The angular velocity vector omegav is computed by:
% omegav(:,1) = vector( 2*log( q(1) * inverse(q(2)) )/(t(2) - t(1)) );
% omegav(:,i) = vector(...
% (log( q(i-1) * inverse(q(i)) ) + log( q(i) * inverse(q(i+1))) )/...
% (0.5*(t(i+1) - t(i-1))) );
% omegav(:,end) = vector( 2*log( q(end-1) * inverse(q(end)) )/...
% (t(end) - t(end-1)) );
% [axis, omega] = unitvector( omegav );
% Inputs:
% q array of normalized (rotation) quaternions
% t [OPT] array of monotonically increasing (or decreasing) times.
% if omitted or empty, unit time steps are assumed.
% t must either be a vector with the same length as dimension
% dim of q, or the same size as q.
% dim [OPT] dimension of q that is varying in time; if omitted or empty,
% the first non-singleton dimension is used.
% Outputs:
% omega array of instantaneous angular velocities, radians/(unit time)
% omega >= 0
% axis instantaneous 3D rotation axis unit vectors at each time
if isempty( q )
omega = [];
axis = [];
return;
end
if (nargin < 3) || isempty( dim )
if (nargin > 1) && ~isempty( t )
siq = size( q );
sit = size( t );
if isequal( siq, sit )
dim = find( siq > 1, 1 );
else
dim = find( siq == length( t ), 1 );
end
if isempty( dim )
error( 'size of t must agree with at least one dimension of q' );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
if isequal( siq, sit )
t = permute( t, perm );
end
end
else
[q, dim, perm] = finddim( q, -2 );
if dim == 0
omega = 0;
axis = unitvector( q.e(2:4), 1 );
return;
end
end
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
n = norm( q );
if ~all( abs( n(:) - 1 ) < eps(16) )
error( 'q must be normalized' );
end
siq = size( q );
if (nargin < 2) || isempty( t )
t = repmat( (0 : (siq(1)-1)).', [1 siq(2:end)] );
elseif length( t ) == siq(1)
t = repmat( t(:), [1 siq(2:end)] );
elseif ~isequal( siq, size( t ))
error( 'size of t must match size of q' );
end
dt = zeros( siq );
difft = diff( t, 1 );
dt(1,:) = difft(1,:);
dt(2:end-1,:) = 0.5 *( difft(1:end-1,:) + difft(2:end,:) );
dt(end,:) = difft(end,:);
dq = quaternion.zeros( siq );
q1iq2 = q(1:end-1,:) .* inverse( q(2:end,:) );
neg = real( q1iq2 ) < 0;
q1iq2(neg) = -q1iq2(neg); % keep real element >= 0
derivq = log( q1iq2 );
dq(1,:) = 2 .* derivq(1,:);
dq(2:end-1,:) = derivq(1:end-1,:) + derivq(2:end,:);
dq(end,:) = 2 .* derivq(end,:);
omegav = vector( dq ); % angular velocity vectors
[axis, omega] = unitvector( omegav, 1 );
omega = reshape( omega(1,:), siq )./ dt;
axis = -axis;
if dim > 1
axis = ipermute( axis, [1, 1+perm] );
omega = ipermute( omega, perm );
end
end % OmegaAxis
function PlotRotation( q, interval )
% function PlotRotation( q, interval ) or q.PlotRotation( interval )
% Inputs:
% q quaternion array
% interval pause between figure updates in seconds, default = 0.1
% Output:
% figure plotting the 3 Cartesian axes orientations for the series of
% quaternions in array q
if (nargin < 2) || isempty( interval )
interval = 0.1;
end
nel = numel( q );
or = zeros(1,3);
ax = eye(3);
alx = zeros( nel, 3, 3 );
figure;
for iel = 1 : nel
% plot3( [ or; ax(:,1).' ], [ or ; ax(:,2).' ], [ or; ax(:,3).' ], ':' );
plot3( [ or; ax(1,:) ], [ or ; ax(2,:) ], [ or; ax(3,:) ], ':' );
hold on
set( gca, 'Xlim', [-1 1], 'Ylim', [-1 1], 'Zlim', [-1 1] );
xlabel( 'x' );
ylabel( 'y' );
zlabel( 'z' );
grid on
nax = q(iel).RotationMatrix;
alx(iel,:,:) = nax;
% plot3( [ or; nax(:,1).' ], [ or ; nax(:,2).' ], [ or; nax(:,3).' ], '-', 'LineWidth', 2 );
plot3( [ or; nax(1,:) ], [ or ; nax(2,:) ], [ or; nax(3,:) ], '-', 'LineWidth', 2 );
% plot3( alx(1:iel,:,1), alx(1:iel,:,2), alx(1:iel,:,3), '*' );
plot3( squeeze(alx(1:iel,1,:)), squeeze(alx(1:iel,2,:)), squeeze(alx(1:iel,3,:)), '*' );
if interval
pause( interval );
end
hold off
end
end % PlotRotation
function [q1, w1, t1] = PropagateEulerEq( q0, w0, I, t, torque, varargin )
% function [q1, w1, t1] = PropagateEulerEq( q0, w0, I, t, torque, odeoptions )
% Inputs:
% q0 initial orientation quaternion (normalized, scalar)
% w0(3) initial body frame angular velocity vector
% I(3) principal body moments of inertia (if no torque, only
% ratios of elements of I are used)
% t(nt) initial and subsequent (or previous) times t = [t0,t1,...]
% (monotonic)
% @torque [OPTIONAL] function handle to calculate torque vector:
% tau(1:3) = torque( t, y ), where y = [q.e(1:4); w(1:3)]
% odeoptions [OPTIONAL] ode45 options
% Outputs:
% q1(1,nt) array of normalized quaternions at times t1
% w1(3,nt) array of body frame angular velocity vectors at times t1
% t1(1,nt) array of output times
% Calls:
% Derivative quaternion derivative method
% odeset matlab ode options setter
% ode45 matlab ode numerical differential equation integrator
% torque [OPTIONAL] user-supplied torque as function of time, orientation,
% and angular rates; default is no torque
% Author:
% Mark Tincknell, 20 December 2010
% modified 25 July 2012, enforce normalization of q0 and q1
options = odeset( varargin{:} );
q0 = q0.normalize;
y0 = [q0.e; w0(:)];
I0 = [ (I(2) - I(3)) / I(1);
(I(3) - I(1)) / I(2);
(I(1) - I(2)) / I(3) ];
[T, Y] = ode45( @Euler, t, y0, options );
function yd = Euler( ti, yi )
qi = quaternion( yi(1), yi(2), yi(3), yi(4) );
wi = yi(5:7);
qd = double( qi.Derivative( wi ));
wd = [ wi(2) * wi(3) * I0(1);
wi(3) * wi(1) * I0(2);
wi(1) * wi(2) * I0(3) ];
if exist( 'torque', 'var' ) && isa( torque, 'function_handle' )
tau = torque( ti, yi );
wd = tau(:) ./ I + wd;
end
yd = [ qd; wd ];
end
if numel(t) == 2
nT = 2;
T = [T(1); T(end)];
Y = [Y(1,:); Y(end,:)];
else
nT = length(T);
end
q1 = repmat( quaternion, [1 nT] );
w1 = zeros( [3 nT] );
t1 = T(:).';
for it = 1 : nT
q1(it) = quaternion( Y(it,1), Y(it,2), Y(it,3), Y(it,4) );
w1(:,it) = Y(it,5:7).';
end
q1 = q1.normalize;
neg = real( q1 ) < 0;
q1(neg) = -q1(neg); % keep real element >= 0
end % PropagateEulerEq
function vp = RotateVector( varargin )
% function vp = RotateVector( q, v, dim ) or
% vp = q.RotateVector( v, dim )
% 3x3 rotation matrices are created from q and matrix multiplication
% rotates v into vp. RotateVector is 7 times faster than RotateVectorQ.
% Inputs:
% q quaternion array
% v 3xN or Nx3 element Cartesian vectors
% dim [OPTIONAL] dimension of v with size 3 to rotate
% Output:
% vp 3xN or Nx3 element rotated vectors
if nargin < 2
error( 'RotateVector method requires 2 inputs: a vector and a quaternion' );
end
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
v = varargin{2};
else
v = varargin{1};
q = varargin{2};
end
if (nargin > 2) && ~isempty( varargin{3} )
dim = varargin{3};
if size( v, dim ) ~= 3
error( 'Dimension dim of vector v must be size 3' );
end
if dim > 1
ndm = ndims( v );
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
else
[v, dim, perm] = finddim( v, 3 );
if dim == 0
error( 'v must have a dimension of size 3' );
end
end
sip = size( v );
v = reshape( v, 3, [] );
nev = prod( sip )/ 3;
R = q.RotationMatrix;
siq = size( q );
neq = prod( siq );
if neq == nev
vp = zeros( sip );
for iel = 1 : neq
vp(:,iel) = R(:,:,iel) * v(:,iel);
end
if dim > 1
vp = ipermute( vp, perm );
end
elseif nev == 1
siz = [3 siq];
vp = zeros( siz );
for iel = 1 : neq
vp(:,iel) = R(:,:,iel) * v;
end
if siz(2) == 1
vp = squeeze( vp );
end
elseif neq == 1
vp = R * v;
vp = reshape( vp, sip );
if dim > 1
vp = ipermute( vp, perm );
end
else
error( 'q and v must have compatible dimensions' );
end
end % RotateVector
function vp = RotateVectorQ( varargin )
% function vp = RotateVectorQ( q, v, dim ) or
% vp = q.RotateVectorQ( v, dim )
% quaternions are created from v and quaternion multiplication rotates v
% into vp. RotateVector is 7 times faster than RotateVectorQ.
% Inputs:
% q quaternion array
% v 3xN or Nx3 element Cartesian vectors
% dim [OPTIONAL] dimension of v with size 3 to rotate
% Output:
% vp 3xN or Nx3 element rotated vectors
if nargin < 2
error( 'RotateVectorQ method requires 2 inputs: a vector and a quaternion' );
end
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
v = varargin{2};
else
v = varargin{1};
q = varargin{2};
end
siv = size( v );
if (nargin > 2) && ~isempty( varargin{3} )
dim = varargin{3};
if size( v, dim ) ~= 3
error( 'Dimension dim of vector v must be size 3' );
end
if dim > 1
ndm = ndims( v );
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
else
[v, dim, perm] = finddim( v, 3 );
if dim == 0
error( 'v must have a dimension of size 3' );
end
end
sip = size( v );
qv = quaternion( v(1,:), v(2,:), v(3,:) );
qv = reshape( qv, [1 sip(2:end)] );
if dim > 1
qv = ipermute( qv, perm );
end
q = q.normalize;
qp = q .* qv .* q.conj;
dp = qp.double;
nev = prod( siv )/ 3;
sqz = false;
if nev == 1
siz = [3 size(q)];
if siz(2) == 1
sqz = true;
end
else
siz = siv;
end
vp = reshape( dp(2:4,:), siz );
if sqz
vp = squeeze( vp );
end
end % RotateVectorQ
function R = RotationMatrix( q )
% function R = RotationMatrix( q ) or R = q.RotationMatrix
% Construct rotation (or direction cosine) matrices from quaternions
% Input:
% q quaternion array
% Output:
% R 3x3xN rotation (or direction cosine) matrices
siz = size( q );
R = zeros( [3 3 siz] );
nel = prod( siz );
q = normalize( q );
for iel = 1 : nel
e11 = q(iel).e(1)^2;
e12 = q(iel).e(1) * q(iel).e(2);
e13 = q(iel).e(1) * q(iel).e(3);
e14 = q(iel).e(1) * q(iel).e(4);
e22 = q(iel).e(2)^2;
e23 = q(iel).e(2) * q(iel).e(3);
e24 = q(iel).e(2) * q(iel).e(4);
e33 = q(iel).e(3)^2;
e34 = q(iel).e(3) * q(iel).e(4);
e44 = q(iel).e(4)^2;
R(:,:,iel) = ...
[ e11 + e22 - e33 - e44, 2*(e23 - e14), 2*(e24 + e13); ...
2*(e23 + e14), e11 - e22 + e33 - e44, 2*(e34 - e12); ...
2*(e24 - e13), 2*(e34 + e12), e11 - e22 - e33 + e44 ];
end
R = chop( R );
end % RotationMatrix
end % methods
% Static methods
methods(Static)
function q = angleaxis( angle, axis )
% function q = quaternion.angleaxis( angle, axis )
% Construct quaternions from rotation axes and rotation angles
% Inputs:
% angle array of rotation angles in radians
% axis 3xN or Nx3 array of axes (need not be unit vectors)
% Output:
% q quaternion array
sig = size( angle );
six = size( axis );
[axis, dim, perm] = finddim( axis, 3 );
if dim == 0
error( 'axis must have a dimension of size 3' );
end
neg = prod( sig );
nex = prod( six )/ 3;
if neg == 1
siz = six;
siz(dim)= 1;
nel = nex;
elseif nex == 1
siz = sig;
nel = neg;
elseif nex == neg
siz = sig;
nel = neg;
else
error( 'angle and axis must have compatible sizes' );
end
for iel = nel : -1 : 1
d(:,iel) = AngAxis2e( angle(min(iel,neg)), axis(:,min(iel,nex)) );
end
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = reshape( q, siz );
if neg == 1
q = ipermute( q, perm );
end
end % quaternion.angleaxis
function q = eulerangles( varargin )
% function q = quaternion.eulerangles( axes, angles ) OR
% function q = quaternion.eulerangles( axes, ang1, ang2, ang3 )
% Construct quaternions from triplets of axes and Euler angles
% Inputs:
% axes string array or cell string array
% '123' = 'xyz' = 'XYZ' = 'ijk', etc.
% angles 3xN or Nx3 array of angles in radians OR
% ang1, ang2, ang3 arrays of angles in radians
% Output:
% q quaternion array
ics = cellfun( @ischar, varargin );
if any( ics )
varargin{ics} = cellstr( varargin{ics} );
else
ics = cellfun( @iscellstr, varargin );
end
siv = cellfun( @size, varargin, 'UniformOutput', false );
axes = varargin{ics};
six = siv{ics};
nex = prod( six );
dim = 1;
if nargin == 2 % angles is 3xN or Nx3 array
angles = varargin{~ics};
sig = siv{~ics};
[angles, dim, perm] = finddim( angles, 3 );
if dim == 0
error( 'Must supply 3 Euler angles' );
end
sig(dim) = 1;
neg = prod( sig );
if nex == 1
siz = sig;
elseif neg == 1
siz = six;
elseif nex == neg
siz = sig;
end
nel = prod( siz );
for iel = nel : -1 : 1
q(iel) = EulerAng2q( axes{min(iel,nex)}, ...
angles(:,min(iel,neg)) );
end
elseif nargin == 4 % each of 3 angles is separate input argument
angles = varargin(~ics);
na = cellfun( 'prodofsize', angles );
[neg, jeg] = max( na );
if ~all( (na == 1) | (na == neg) )
error( 'All angles must be singletons or have the same number of elements' );
end
sig = size( angles{jeg} );
if nex == 1
siz = sig;
elseif neg == 1
siz = six;
elseif nex == neg
siz = sig;
end
nel = prod( siz );
for iel = nel : -1 : 1
q(iel) = EulerAng2q( axes{min(iel,nex)}, ...
[angles{1}(min(iel,na(1))), ...
angles{2}(min(iel,na(2))), ...
angles{3}(min(iel,na(3)))] );
end
else
error( 'Must supply either 2 or 4 input arguments' );
end % if nargin
q = reshape( q, siz );
if (dim > 1) && isequal( siz, sig )
q = ipermute( q, perm );
end
if ~ismatrix( q ) && (size( q, 1 ) == 1)
q = shiftdim( q, 1 );
end
end % quaternion.eulerangles
function q = eye( N )
% function q = eye( N )
if nargin < 1
N = 1;
end
if isempty(N) || (N <= 0)
q = quaternion.empty;
else
q = quaternion( eye(N), 0, 0, 0 );
end
end % quaternion.eye
function q = nan( varargin )
% function q = quaternion.nan( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( nan(siz), nan, nan, nan );
end
end % quaternion.nan
function q = NaN( varargin )
% function q = quaternion.NaN( siz )
q = quaternion.nan( varargin{:} );
end % quaternion.NaN
function q = ones( varargin )
% function q = quaternion.ones( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( ones(siz), 0, 0, 0 );
end
end % quaternion.ones
function q = rand( varargin )
% function q = quaternion.rand( siz )
% Input:
% siz size of output array q
% Output:
% q uniform random quaternions, NOT normalized to 1,
% 0 <= q.e(1) <= 1, -1 <= q.e(2:4) <= 1
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = quaternion.empty;
return;
end
d = [ rand( [1, siz] ); 2 * rand( [3, siz] ) - 1 ];
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = reshape( q, siz );
end % quaternion.rand
function q = randRot( varargin )
% function q = quaternion.randRot( siz )
% Random quaternions uniform in rotation space
% Input:
% siz size of output array q
% Output:
% q random quaternions, normalized to 1, 0 <= q.e(1) <= 1,
% uniform over the 3D surface of a 4 dimensional hypersphere
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = quaternion.empty;
return;
end
d = randn( [4, prod( siz )] );
n = sqrt( sum( d.^2, 1 ));
dn = bsxfun( @rdivide, d, n );
neg = dn(1,:) < 0;
dn(:,neg) = -dn(:,neg);
q = quaternion( dn(1,:), dn(2,:), dn(3,:), dn(4,:) );
q = reshape( q, siz );
end % quaternion.randRot
function q = rotateutov( u, v, dimu, dimv )
% function q = quaternion.rotateutov( u, v, dimu, dimv )
% Construct quaternions to rotate vectors u into directions of vectors v
% Inputs:
% u 3x1 or 3xN or 1x3 or Nx3 arrays of vectors
% v 3x1 or 3xN or 1x3 or Nx3 arrays of vectors
% dimu [OPTIONAL] dimension of u with size 3 to use
% dimv [OPTIONAL] dimension of v with size 3 to use
% Output:
% q quaternion array
if (nargin < 3) || isempty( dimu )
[u, dimu, permu] = finddim( u, 3 );
if dimu == 0
error( 'u must have a dimension of size 3' );
end
elseif dimu > 1
ndmu = ndims( u );
permu = [ dimu : ndmu, 1 : dimu-1 ];
u = permute( u, permu );
else
permu = 1 : ndims(u);
end
siu = size( u );
siu(1) = 1;
neu = prod( siu );
if (nargin < 4) || isempty( dimv )
[v, dimv, permv] = finddim( v, 3 );
if dimv == 0
error( 'v must have a dimension of size 3' );
end
elseif dimv > 1
ndmv = ndims( v );
permv = [ dimv : ndmv, 1 : dimv-1 ];
v = permute( v, permv );
else
permv = 1 : ndims(v);
end
siv = size( v );
siv(1) = 1;
nev = prod( siv );
if neu == nev
siz = siu;
nel = neu;
perm = permu;
dim = dimu;
elseif (neu > 1) && (nev == 1)
siz = siu;
nel = neu;
perm = permu;
dim = dimu;
elseif (neu == 1) && (nev > 1)
siz = siv;
nel = nev;
perm = permv;
dim = dimv;
else
error( 'Number of 3 element vectors in u and v must be 1 or equal' );
end
for iel = nel : -1 : 1
q(iel) = UV2q( u(:,min(iel,neu)), v(:,min(iel,nev)) );
end
if dim > 1
q = ipermute( reshape( q, siz ), perm );
end
end % quaternion.rotateutov
function q = rotationmatrix( R )
% function q = quaternion.rotationmatrix( R )
% Construct quaternions from rotation (or direction cosine) matrices
% Input:
% R 3x3xN rotation (or direction cosine) matrices
% Output:
% q quaternion array
siz = [size(R) 1 1];
if ~all( siz(1:2) == [3 3] ) || ...
(abs( det( R(:,:,1) ) - 1 ) > eps(16) )
error( 'Rotation matrices must be 3x3xN with det(R) == 1' );
end
nel = prod( siz(3:end) );
for iel = nel : -1 : 1
d(:,iel) = RotMat2e( chop( R(:,:,iel) ));
end
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = normalize( q );
q = reshape( q, siz(3:end) );
end % quaternion.rotationmatrix
function q = zeros( varargin )
% function q = quaternion.zeros( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( zeros(siz), 0, 0, 0 );
end
end % quaternion.zeros
end % methods(Static)
end % classdef quaternion
% Scalar rotation conversion functions
function eout = AngAxis2e( angle, axis )
% function eout = AngAxis2e( angle, axis )
% One Angle-Axis -> one quaternion
s = sin( 0.5 * angle );
v = axis(:);
vn = norm( v );
if vn == 0
if s == 0
c = 0;
else
c = 1;
end
u = zeros( 3, 1 );
else
c = cos( 0.5 * angle );
u = v(:) ./ vn;
end
eout = [ c; s * u ];
if (eout(1) < 0) && (mod( angle/(2*pi), 2 ) ~= 1)
eout = -eout; % rotationally equivalent quaternion with real element >= 0
end
end % AngAxis2e
function qout = EulerAng2q( axes, angles )
% function qout = EulerAng2q( axes, angles )
% One triplet Euler Angles -> one quaternion
na = length( axes );
axis = zeros( 3, na );
for i0 = 1 : na
switch axes(i0)
case {'1', 'i', 'x', 'X'}
axis(:,i0) = [ 1; 0; 0 ];
case {'2', 'j', 'y', 'Y'}
axis(:,i0) = [ 0; 1; 0 ];
case {'3', 'k', 'z', 'Z'}
axis(:,i0) = [ 0; 0; 1 ];
otherwise
error( 'Illegal axis designation' );
end
end
q0 = quaternion.angleaxis( angles(:).', axis );
qout = q0(1);
for i0 = 2 : numel(q0)
qout = product( q0(i0), qout );
end
if qout.e(1) < 0
qout = -qout; % rotationally equivalent quaternion with real element >= 0
end
end % EulerAng2q
function eout = RotMat2e( R )
% function eout = RotMat2e( R )
% One Rotation Matrix -> one quaternion
eout = zeros(4,1);
if ~all( all( R == 0 ))
eout(1) = 0.5 * sqrt( max( 0, R(1,1) + R(2,2) + R(3,3) + 1 ));
if eout(1) == 0
eout(2) = sqrt( max( 0, -0.5 *( R(2,2) + R(3,3) ))) * ...
sgn( -R(2,3) );
eout(3) = sqrt( max( 0, -0.5 *( R(1,1) + R(3,3) ))) * ...
sgn( -R(1,3) );
eout(4) = sqrt( max( 0, -0.5 *( R(1,1) + R(2,2) ))) * ...
sgn( -R(1,2) );
else
eout(2) = 0.25 *( R(3,2) - R(2,3) )/ eout(1);
eout(3) = 0.25 *( R(1,3) - R(3,1) )/ eout(1);
eout(4) = 0.25 *( R(2,1) - R(1,2) )/ eout(1);
end
end
end % RotMat2e
function qout = UV2q( u, v )
% function qout = UV2q( u, v )
% One pair vectors U, V -> one quaternion
w = cross( u, v ); % construct vector w perpendicular to u and v
magw = norm( w );
dotuv = dot( u, v );
if magw == 0
% Either norm(u) == 0 or norm(v) == 0 or dotuv/(norm(u)*norm(v)) == 1
if dotuv >= 0
qout = quaternion( 1, 0, 0, 0 );
return;
end
% dotuv/(norm(u)*norm(v)) == -1
% If v == [v(1); 0; 0], rotate by pi about the [0; 0; 1] axis
if (v(2) == 0) && (v(3) == 0)
qout = quaternion( 0, 0, 0, 1 );
return;
end
% Otherwise constuct "what" such that dot(v,what) == 0, and rotate about it
% by pi
what = [ 0; -v(3); v(2) ]./ sqrt( v(2)^2 + v(3)^2 );
costh = -1;
else
% Use w as rotation axis, angle between u and v as rotation angle
what = w(:) / magw;
costh = dotuv /( norm(u) * norm(v) );
end
c = sqrt( 0.5 *( 1 + costh )); % real element >= 0
s = sqrt( 0.5 *( 1 - costh ));
eout = [ c; s * what ];
qout = quaternion( eout(1), eout(2), eout(3), eout(4) );
end % UV2q
% Helper functions
function out = chop( in, tol )
% function out = chop( in, tol )
% Replace values that differ from an integer by <= tol by the integer
% Inputs:
% in input array
% tol tolerance, default = eps
% Output:
% out input array with integer replacements, if any
if (nargin < 2) || isempty( tol )
tol = eps;
end
out = in;
rin = round( in );
lx = abs( rin - in ) <= tol;
out(lx) = rin(lx);
end % chop
function [aout, dim, perm] = finddim( ain, len )
% function [aout, dim, perm] = finddim( ain, len )
% Find first dimension in ain of length len, permute ain to make it first
% Inputs:
% ain(s1,s2,...) data array, size = [s1, s2, ...]
% len length sought, e.g. s2 == len
% if len < 0, then find first dimension >= |len|
% Outputs:
% aout(s2,...,s1) data array, permuted so first dimension is length len
% dim dimension number of length len, 0 if ain has none
% perm permutation order (for permute and ipermute) of aout,
% e.g. [2, ..., 1]
% Notes: if no dimension has length len, aout = ain, dim = 0, perm = 1:ndm
% ain = ipermute( aout, perm )
siz = size( ain );
ndm = length( siz );
if len < 0
dim = find( siz >= -len, 1, 'first' );
else
dim = find( siz == len, 1, 'first' );
end
if isempty( dim )
dim = 0;
end
if dim < 2
aout = ain;
perm = 1 : ndm;
else
% Permute so that dim becomes the first dimension
perm = [ dim : ndm, 1 : dim-1 ];
aout = permute( ain, perm );
end
end % finddim
function s = sgn( x )
% function s = sgn( x ), if x >= 0, s = 1, else s = -1
s = ones( size( x ));
s(x < 0) = -1;
end % sgn
function [u, n] = unitvector( v, dim )
% function [u, n] = unitvector( v, dim )
% Inputs:
% v matrix of vectors
% dim [OPTIONAL] dimension to normalize, dim >= 1
% if no dim input, use first dimension of length >= 2
% Outputs:
% u matrix of unit vectors (except for vectors of norm 0)
% n matrix same size as v and u of norms
ndm = ndims( v );
if (nargin < 2) || isempty( dim )
[v, dim, perm] = finddim( v, -2 );
if dim == 0
n = sqrt( v.*conj(v) );
n0 = (n ~= 0) & (n ~= 1);
u = v;
u(n0) = v(n0) ./ n(n0);
return;
end
else
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
u = v;
sv = size( v );
n = repmat( sqrt( sum( v.*conj(v), 1 )), [sv(1) ones(1,ndm-1)] );
n0 = (n ~= 0) & (n ~= 1);
u(n0) = v(n0) ./ n(n0);
u = ipermute( u, perm );
if nargout > 1
n = ipermute( n, perm );
end
end % unitvector
|
github
|
jianxiongxiao/ProfXkit-master
|
fill_depth_cross_bfx.m
|
.m
|
ProfXkit-master/segmentGraph/CrossBilateralFiltering/fill_depth_cross_bfx.m
| 1,675 |
utf_8
|
8f5319ababaa10742c0b8552d969f7c2
|
% In-paints the depth image using a cross-bilateral filter. The operation
% is implemented via several filterings at various scales. The number of
% scales is determined by the number of spacial and range sigmas provided.
% 3 spacial/range sigmas translated into filtering at 3 scales.
%
% Args:
% imgRgb - the RGB image, a uint8 HxWx3 matrix
% imgDepthAbs - the absolute depth map, a HxW double matrix whose values
% indicate depth in meters.
% spaceSigmas - (optional) sigmas for the spacial gaussian term.
% rangeSigmas - (optional) sigmas for the intensity gaussian term.
%
% Returns:
% imgDepthAbs - the inpainted depth image.
function imgDepthAbs = fill_depth_cross_bfx(imgRgb, imgDepthAbs, mask, ...
spaceSigmas, rangeSigmas)
error(nargchk(2,4,nargin));
assert(isa(imgRgb, 'uint8'), 'imgRgb must be uint8');
assert(isa(imgDepthAbs, 'double'), 'imgDepthAbs must be a double');
if nargin < 4
spaceSigmas = [12 5 8];
end
if nargin < 5
rangeSigmas = [0.2 0.08 0.02];
end
assert(numel(spaceSigmas) == numel(rangeSigmas));
assert(isa(rangeSigmas, 'double'));
assert(isa(spaceSigmas, 'double'));
% Create the 'noise' image and get the maximum observed depth.
maxv = max(imgDepthAbs(~mask));
minv = min(imgDepthAbs(~mask));
% Convert the depth image to uint8.
imgDepth = (imgDepthAbs - minv) ./ (maxv - minv);
imgDepth = uint8(imgDepth * 255);
% Run the cross-bilateral filter.
imgDepthAbs = mex_cbf(imgDepth, rgb2gray(imgRgb), mask, spaceSigmas(:), rangeSigmas(:));
% Convert back to absolute depth (meters).
imgDepthAbs = im2double(imgDepthAbs) .* (maxv - minv) + minv;
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.