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
|
rising-turtle/slam_matlab-master
|
vl_demo_aib.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_demo_alldist.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_demo_svmpegasos.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/demo/vl_demo_svmpegasos.m
| 1,304 |
utf_8
|
5470b2cbce41c6323cb562dbcd37556b
|
% VL_DEMO_SVMPEGASOS Demo: SVMPEGASOS: 2D linear learning
function vl_demo_svmpegasos
% Set up training data
Np = 200 ;
Nn = 200 ;
Xp = diag([1 3])*randn(2, Np) ;
Xn = diag([1 3])*randn(2, Nn) ;
Xp(1,:) = Xp(1,:) + 2 ;
Xn(1,:) = Xn(1,:) - 2 ;
X = [Xp Xn] ;
y = [ones(1,Np) -ones(1,Nn)] ;
figure(1)
plot(Xn(1,:),Xn(2,:),'*')
hold on
plot(Xp(1,:),Xp(2,:),'*r')
axis equal ;
%axis off ; axis tight ;
vl_demo_print('pegasos_training') ;
% parameters
lambda = 0.01 ;
% training
energy = [] ;
dataset = vl_maketrainingset(X, int8(y)) ;
[w b info] = vl_svmpegasos(dataset, lambda, ...
'MaxIterations',5000,...
'DiagnosticFunction',@diagnostics,...
'DiagnosticCallRef',energy) ;
figure(1) ;
x = min(X(1,:)):max(X(1,:)) ;
hold on
set(line([0 w(1)], [0 w(2)]), 'color', 'y', 'linewidth', 4) ;
xlim([-3 3]) ;
ylim([-3 3]) ;
set(line(10*[w(2) -w(2)], 10*[-w(1) w(1)]), ...
'color', 'y', 'linewidth', 2, 'linestyle', '-') ;
axis equal ;
hold off
%axis off ; axis tight ;
vl_demo_print('pegasos_res') ;
figure(2)
%axis equal ;
%axis off ; axis tight ;
vl_demo_print('pegasos_energy') ;
function energy = diagnostics(svm,energy)
figure(2) ;
%keyboard
energy = [energy svm.energy] ;
plot(energy) ;
drawnow ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_demo_kdtree_sift.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/demo/vl_demo_kdtree_sift.m
| 6,832 |
utf_8
|
e676f80ac330a351f0110533c6ebba89
|
function vl_demo_kdtree_sift
% VL_DEMO_KDTREE_SIFT
% Demonstrates the use of a kd-tree forest to match SIFT
% features. If FLANN is present, this function runs a comparison
% against it.
% AUTORIGHS
rand('state',0) ;
randn('state',0);
do_median = 0 ;
do_mean = 1 ;
% try to setup flann
if ~exist('flann_search', 'file')
if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab'))
addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ;
end
end
do_flann = exist('nearest_neighbors') == 3 ;
if ~do_flann
warning('FLANN not found. Comparison disabled.') ;
end
maxNumComparisonsRange = [1 10 50 100 200 300 400] ;
numTreesRange = [1 2 5 10] ;
% get data (SIFT features)
im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ;
im1 = single(rgb2gray(im1)) ;
im2 = single(rgb2gray(im2)) ;
[f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ;
[f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ;
% add some noise to make matches unique
d1 = single(d1) + rand(size(d1)) ;
d2 = single(d2) + rand(size(d2)) ;
% match exhaustively to get the ground truth
elapsedDirect = tic ;
D = vl_alldist(d1,d2) ;
[drop, best] = min(D, [], 1) ;
elapsedDirect = toc(elapsedDirect) ;
for ti=1:length(numTreesRange)
for vi=1:length(maxNumComparisonsRange)
v = maxNumComparisonsRange(vi) ;
t = numTreesRange(ti) ;
if do_median
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'median', ...
'numtrees', t) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons',v) ;
elapsedKD_median(vi,ti) = toc ;
errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_mean
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'mean', ...
'numtrees', t) ;
%kdtree = readflann(kdtree, '/tmp/flann.txt') ;
%checkx(kdtree, d1, 1, 1) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons', v) ;
elapsedKD_mean(vi,ti) = toc ;
errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_flann
tic ;
[i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ...
'trees', t, ...
'checks', v));
ifla = i ;
elapsedKD_flann(vi,ti) = toc;
errors_flann(vi,ti) = sum(i ~= best) / length(best) ;
errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
end
end
figure(1) ; clf ;
leg = {} ;
hnd = [] ;
sty = {{'color','r'},{'color','g'},...
{'color','b'},{'color','c'},...
{'color','k'}} ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('percentage of incorrect matches (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_incorrect',.6) ;
figure(2) ; clf ;
leg = {} ;
hnd = [] ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('relative overestimation of minmium distannce (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_distortion',.6) ;
% --------------------------------------------------------------------
function checkx(kdtree, X, t, n, mib, mab)
% --------------------------------------------------------------------
if nargin <= 4
mib = -inf * ones(size(X,1),1) ;
mab = +inf * ones(size(X,1),1) ;
end
lc = kdtree.trees(t).nodes.lowerChild(n) ;
uc = kdtree.trees(t).nodes.upperChild(n) ;
if lc < 0
for i=-lc:-uc-1
di = kdtree.trees(t).dataIndex(i) ;
if any(X(:,di) > mab)
error('a') ;
end
if any(X(:,di) < mib)
error('b') ;
end
end
return
end
i = kdtree.trees(t).nodes.splitDimension(n) ;
v = kdtree.trees(t).nodes.splitThreshold(n) ;
mab_ = mab ;
mab_(i) = min(mab(i), v) ;
checkx(kdtree, X, t, lc, mib, mab_) ;
mib_ = mib ;
mib_(i) = max(mib(i), v) ;
checkx(kdtree, X, t, uc, mib_, mab) ;
% --------------------------------------------------------------------
function kdtree = readflann(kdtree, path)
% --------------------------------------------------------------------
data = textread(path)' ;
for i=1:size(data,2)
nodeIds = data(1,:) ;
ni = find(nodeIds == data(1,i)) ;
if ~isnan(data(2,i))
% internal node
li = find(nodeIds == data(4,i)) ;
ri = find(nodeIds == data(5,i)) ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ;
kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ;
kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ;
else
di = data(3,i) + 1 ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ;
end
kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ;
end
|
github
|
rising-turtle/slam_matlab-master
|
vl_impattern.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/imop/vl_impattern.m
| 6,702 |
utf_8
|
7f5d173ebd720f7b89eccfa416aa71d3
|
function im = vl_impattern(varargin)
% VL_IMPATTERN Generate an image from a stock pattern
% IM=VLPATTERN(NAME) returns an instance of the specified
% pattern. These stock patterns are useful for testing algoirthms.
%
% All generated patterns are returned as an image of class
% DOUBLE. Both gray-scale and colour images have range in [0,1].
%
% VL_IMPATTERN() without arguments shows a gallery of the stock
% patterns. The following patterns are supported:
%
% Wedge::
% The image of a wedge.
%
% Cone::
% The image of a cone.
%
% SmoothChecker::
% A checkerboard with Gaussian filtering on top. Use the
% option-value pair 'sigma', SIGMA to specify the standard
% deviation of the smoothing and the pair 'step', STEP to specfity
% the checker size in pixels.
%
% ThreeDotsSquare::
% A pattern with three small dots and two squares.
%
% UniformNoise::
% Random i.i.d. noise.
%
% Blobs:
% Gaussian blobs of various sizes and anisotropies.
%
% Blobs1:
% Gaussian blobs of various orientations and anisotropies.
%
% Blob:
% One Gaussian blob. Use the option-value pairs 'sigma',
% 'orientation', and 'anisotropy' to specify the respective
% parameters. 'sigma' is the scalar standard deviation of an
% isotropic blob (the image domain is the rectangle
% [-1,1]^2). 'orientation' is the clockwise rotation (as the Y
% axis points downards). 'anisotropy' (>= 1) is the ratio of the
% the largest over the smallest axis of the blob (the smallest
% axis length is set by 'sigma'). Set 'cut' to TRUE to cut half
% half of the blob.
%
% A stock image::
% Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'.
%
% All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but
% the stock images, the default size is [128,128].
% Author: Andrea Vedaldi
% AUTORIGHTS
if nargin > 0
pattern=varargin{1} ;
varargin=varargin(2:end) ;
else
pattern = 'gallery' ;
end
patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ...
'blob', 'blobs', 'blobs1', ...
'box', 'roofs1', 'roofs2', 'river1', 'river2'} ;
% spooling
switch lower(pattern)
case 'wedge', im = wedge(varargin) ;
case 'cone', im = cone(varargin) ;
case 'smoothchecker', im = smoothChecker(varargin) ;
case 'threedotssquare', im = threeDotSquare(varargin) ;
case 'uniformnoise', im = uniformNoise(varargin) ;
case 'blob', im = blob(varargin) ;
case 'blobs', im = blobs(varargin) ;
case 'blobs1', im = blobs1(varargin) ;
case {'box','roofs1','roofs2','river1','river2','spots'}
im = stockImage(pattern, varargin) ;
case 'gallery'
clf ;
num = numel(patterns) ;
for p = 1:num
vl_tightsubplot(num,p,'box','outer') ;
imagesc(vl_impattern(patterns{p}),[0 1]) ;
axis image off ;
title(patterns{p}) ;
end
colormap gray ;
return ;
otherwise
error('Unknown patter ''%s''.', pattern) ;
end
if nargout == 0
clf ; imagesc(im) ; hold on ;
colormap gray ; axis image off ;
title(pattern) ;
clear im ;
end
function [u,v,opts,args] = commonOpts(args)
opts.size = [128 128] ;
[opts,args] = vl_argparse(opts, args) ;
ur = linspace(-1,1,opts.size(2)) ;
vr = linspace(-1,1,opts.size(1)) ;
[u,v] = meshgrid(ur,vr);
function im = wedge(args)
[u,v,opts,args] = commonOpts(args) ;
im = abs(u) + abs(v) > (1/4) ;
im(v < 0) = 0 ;
function im = cone(args)
[u,v,opts,args] = commonOpts(args) ;
im = sqrt(u.^2+v.^2) ;
im = im / max(im(:)) ;
function im = smoothChecker(args)
opts.size = [128 128] ;
opts.step = 16 ;
opts.sigma = 2 ;
opts = vl_argparse(opts, args) ;
[u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ;
im = xor((mod(u,opts.step*2) < opts.step),...
(mod(v,opts.step*2) < opts.step)) ;
im = double(im) ;
im = vl_imsmooth(im, opts.sigma) ;
function im = threeDotSquare(args)
[u,v,opts,args] = commonOpts(args) ;
im = ones(size(u)) ;
im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ;
im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ;
[drop,i] = min(abs(v(:,1))) ;
[drop,j1] = min(abs(u(1,:)-1/6)) ;
[drop,j2] = min(abs(u(1,:))) ;
[drop,j3] = min(abs(u(1,:)+1/6)) ;
im(i,j1) = 0 ;
im(i,j2) = 0 ;
im(i,j3) = 0 ;
function im = blobs(args)
[u,v,opts,args] = commonOpts(args) ;
im = zeros(size(u)) ;
num = 5 ;
square = 2 / num ;
sigma = square / 2 / 3 ;
scales = logspace(log10(0.5), log10(1), num) ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ;
C = inv(A'*A) ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = blob(args)
[u,v,opts,args] = commonOpts(args) ;
opts.sigma = 0.15 ;
opts.anisotropy = .5 ;
opts.orientation = 2/3 * pi ;
opts.cut = false ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
th = opts.orientation ;
R = [cos(th) -sin(th) ; sin(th) cos(th)] ;
A = opts.sigma * R * diag([opts.anisotropy 1]) ;
T = [0;0] ;
[x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ;
im = exp(-0.5 *(x.^2 + y.^2)) ;
if opts.cut
im = im .* double(x > 0) ;
end
function im = blobs1(args)
[u,v,opts,args] = commonOpts(args) ;
opts.number = 5 ;
opts.sigma = [] ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
square = 2 / opts.number ;
num = opts.number ;
if isempty(opts.sigma)
sigma = 1/6 * square ;
else
sigma = opts.sigma * square ;
end
rotations = linspace(0,pi,num+1) ;
rotations(end) = [] ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
th = rotations(i) ;
R = [cos(th) -sin(th); sin(th) cos(th)] ;
A = sigma * R * diag([1 1/skews(j)]) ;
C = inv(A*A') ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = uniformNoise(args)
opts.size = [128 128] ;
opts.seed = 1 ;
opts = vl_argparse(opts, args) ;
state = vl_twister('state') ;
vl_twister('state',opts.seed) ;
im = vl_twister(opts.size([2 1])) ;
vl_twister('state',state) ;
function im = stockImage(pattern,args)
opts.size = [] ;
opts = vl_argparse(opts, args) ;
switch pattern
case 'river1', path='river1.jpg' ;
case 'river2', path='river2.jpg' ;
case 'roofs1', path='roofs1.jpg' ;
case 'roofs2', path='roofs2.jpg' ;
case 'box', path='box.pgm' ;
case 'spots', path='spots.jpg' ;
end
im = imread(fullfile(vl_root,'data',path)) ;
im = im2double(im) ;
if ~isempty(opts.size)
im = imresize(im, opts.size) ;
im = max(im,0) ;
im = min(im,1) ;
end
|
github
|
rising-turtle/slam_matlab-master
|
vl_tpsu.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_xyz2lab.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_twister.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_kdtree.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_imwbackward.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_pegasos.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_pegasos.m
| 5,428 |
utf_8
|
cc28a57ce6cf6ecba349d21698228e2e
|
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 b info] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
% test input
vl_assert_equal(info.biasMultiplier,s.biasMultiplier);
vl_assert_almost_equal(info.biasLearningRate,.1,1e-3);
vl_assert_almost_equal(conv([w; b]), conv(s.w), 0.1) ;
end
function test_continue_training(s)
for conv = {@single,@double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier) ;
vl_twister('state',0) ;
[w1 b1] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1, ...
'MaxIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier) ;
[w2 b2] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1501, ...
'StartingModel', w1, ...
'StartingBias', b1, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier) ;
vl_assert_almost_equal([w; b],[w2; b2],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 b] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
vl_twister('state',0) ;
[w1 b1] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1, ...
'MaxIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
[w2 b2] = vl_pegasos(conv(s.X), int8(s.y), s.lambda, ...
'StartingIteration', 1501, ...
'StartingModel', w1, ...
'StartingBias', b1, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
vl_assert_almost_equal([w; b],[w2; b2],1e-7) ;
end
function test_homkermap(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
sxe = vl_homkermap(conv(s.X), 1, 'kchi2', 'gamma', .5) ;
[we be] = vl_pegasos(sxe, int8(s.y), s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_twister('state',0) ;
[w b] = vl_pegasos(s.X, int8(s.y), s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1,...
'homkermap',1,...
'gamma',.5,...
'kchi2') ;
vl_assert_almost_equal([w; b],[we; be], 1e-7) ;
end
function test_diagnostic(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
x = 0;
dhandle = @(x,stat) (assert(stat.elapsedTime == 0 || stat.elapsedTime ~= 0)) ;
[w b] = vl_pegasos(s.X, int8(s.y), s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_twister('state',0) ;
[wd bd] = vl_pegasos(s.X, int8(s.y), s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1,...
'DiagnosticFunction',dhandle,...
'DiagnosticCallRef',x) ;
vl_assert_almost_equal([w; b], [wd; bd], 1e-7) ;
end
function test_epsilon(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
[w b info] = vl_pegasos(s.X, int8(s.y), s.lambda, ...
'MaxIterations', 1000000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_twister('state',0) ;
[we be infoe] = vl_pegasos(s.X, int8(s.y), s.lambda, ...
'MaxIterations', 1000000, ...
'Epsilon',1e-7,...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_assert_almost_equal([w; b], [we; be], 1e-2) ;
assert(info.iterations > infoe.iterations);
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
|
rising-turtle/slam_matlab-master
|
vl_test_alphanum.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_svmpegasos.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_svmpegasos.m
| 5,802 |
utf_8
|
dcd13a3246830b74817e8c44100db022
|
function results = vl_test_svmpegasos(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} ;
dataset = vl_maketrainingset(conv(s.X), int8(s.y)) ;
[w b info] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
% test input
vl_assert_equal(info.biasMultiplier,s.biasMultiplier);
vl_assert_almost_equal(info.biasLearningRate,.1,1e-3);
vl_assert_almost_equal(conv([w; b]), conv(s.w), 0.1) ;
end
function test_continue_training(s)
for conv = {@single,@double}
conv = conv{1} ;
vl_twister('state',0) ;
dataset = vl_maketrainingset(conv(s.X), int8(s.y)) ;
[w b] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier) ;
vl_twister('state',0) ;
[w1 b1] = vl_svmpegasos(dataset, s.lambda, ...
'StartingIteration', 1, ...
'MaxIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier) ;
[w2 b2] = vl_svmpegasos(dataset, s.lambda, ...
'StartingIteration', 1501, ...
'StartingModel', w1, ...
'StartingBias', b1, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier) ;
vl_assert_almost_equal([w; b],[w2; b2],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) ;
dataset = vl_maketrainingset(conv(s.X), int8(s.y)) ;
[w b] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
vl_twister('state',0) ;
[w1 b1] = vl_svmpegasos(dataset, s.lambda, ...
'StartingIteration', 1, ...
'MaxIterations', 1500, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
[w2 b2] = vl_svmpegasos(dataset, s.lambda, ...
'StartingIteration', 1501, ...
'StartingModel', w1, ...
'StartingBias', b1, ...
'MaxIterations', 3000, ...
'BiasMultiplier', s.biasMultiplier, ...
'Permutation', perm) ;
vl_assert_almost_equal([w; b],[w2; b2],1e-7) ;
end
function test_homkermap(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
sxe = vl_homkermap(conv(s.X), 1, 'kchi2', 'gamma', .5) ;
dataset = vl_maketrainingset(conv(s.X), int8(s.y),...
'homkermap',1,...
'gamma',.5,...
'kchi2') ;
[we be] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_twister('state',0) ;
[w b] = vl_pegasos(s.X, int8(s.y), s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1,...
'homkermap',1,...
'gamma',.5,...
'kchi2') ;
vl_assert_almost_equal([w; b],[we; be], 1e-7) ;
end
function test_diagnostic(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
x = [];
dhandle = @(stat,x) ([x stat.energy]) ;
dataset = vl_maketrainingset(conv(s.X), int8(s.y)) ;
[w b] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_twister('state',0) ;
[wd bd info] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 100000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1,...
'DiagnosticFunction',dhandle,...
'DiagnosticCallRef',x) ;
vl_assert_almost_equal([w; b], [wd; bd], 1e-7) ;
end
function test_epsilon(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
dataset = vl_maketrainingset(conv(s.X), int8(s.y)) ;
[w b info] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 1000000, ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_twister('state',0) ;
[we be infoe] = vl_svmpegasos(dataset, s.lambda, ...
'MaxIterations', 1000000, ...
'Epsilon',1e-7,...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', .1) ;
vl_assert_almost_equal([w; b], [we; be], 1e-2) ;
assert(info.iterations > infoe.iterations);
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
|
rising-turtle/slam_matlab-master
|
vl_test_cummax.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_cummax.m
| 762 |
utf_8
|
3dddb5736dfffacdd94b156e67cb9c14
|
function results = vl_test_cummax(varargin)
% VL_TEST_CUMMAX
vl_test_init ;
function test_basic()
vl_assert_almost_equal(...
vl_cummax(1), 1) ;
vl_assert_almost_equal(...
vl_cummax([1 2 3 4], 2), [1 2 3 4]) ;
function test_multidim()
a = [1 2 3 4 3 2 1] ;
b = [1 2 3 4 4 4 4] ;
for k=1:6
dims = ones(1,6) ;
dims(k) = numel(a) ;
a = reshape(a, dims) ;
b = reshape(b, dims) ;
vl_assert_almost_equal(...
vl_cummax(a, k), b) ;
end
function test_storage_classes()
types = {@double, @single, @int64, @uint64, ...
@int32, @uint32, @int16, @uint16, ...
@int8, @uint8} ;
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ;
end
end
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_imintegral.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_sift.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_binsum.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_lbp.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_colsubset.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_alldist.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_ihashsum.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_ihashsum.m
| 581 |
utf_8
|
edc283062469af62056b0782b171f5fc
|
function results = vl_test_ihashsum(varargin)
% VL_TEST_IHASHSUM
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(round(16*rand(2,100))) ;
sel = find(all(s.data==0)) ;
s.data(1,sel)=1 ;
function test_hash(s)
D = size(s.data,1) ;
K = 5 ;
h = zeros(1,K,'uint32') ;
id = zeros(D,K,'uint8');
next = zeros(1,K,'uint32') ;
[h,id,next] = vl_ihashsum(h,id,next,K,s.data) ;
sel = vl_ihashfind(id,next,K,s.data) ;
count = double(h(sel)) ;
[drop,i,j] = unique(s.data','rows') ;
for k=1:size(s.data,2)
count_(k) = sum(j == j(k)) ;
end
vl_assert_equal(count,count_) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_grad.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_whistc.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_roc.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_roc.m
| 1,019 |
utf_8
|
9b2ae71c9dc3eda0fc54c65d55054d0c
|
function results = vl_test_roc(varargin)
% VL_TEST_ROC
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ;
function test_perfect_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(info.eer, 0) ;
vl_assert_almost_equal(info.auc, 1) ;
function test_swap1_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ;
function test_swap1_tptn_stable(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ;
function test_swap1_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(info.eer, 1/3) ;
vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_dsift.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_alldist2.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_alldist2.m
| 2,284 |
utf_8
|
89a787e3d83516653ae8d99c808b9d67
|
function results = vl_test_alldist2(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
% TODO: test integer classes
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist2(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', ...
'kchi2', 'kl2', 'kl1', 'khell'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y)};
types = {'single', 'double', 'sparse'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
a = vl_alldist2(X,Y,dists{d}) ;
b = makedist(distsEquiv{d},X,Y) ;
vl_assert_almost_equal(a,b, ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist2(X,X,ker) ;
kyy = vl_alldist2(Y,Y,ker) ;
kxy = vl_alldist2(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist2(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_imsmooth.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_phow.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_kmeans.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_hikmeans.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_hikmeans.m
| 463 |
utf_8
|
dc3b493646e66316184e86ff4e6138ab
|
function results = vl_test_hikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[tree, assign] = vl_hikmeans(s.data,3,100) ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_aib.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_aib.m
| 1,277 |
utf_8
|
78978ae54e7ebe991d136336ba4bf9c6
|
function results = vl_test_aib(varargin)
% VL_TEST_AIB
vl_test_init ;
function s = setup()
s = [] ;
function test_basic(s)
Pcx = [.3 .3 0 0
0 0 .2 .2] ;
% This results in the AIB tree
%
% 1 - \
% 5 - \
% 2 - / \
% - 7
% 3 - \ /
% 6 - /
% 4 - /
%
% coded by the map [5 5 6 6 7 1] (1 denotes the root).
[parents,cost] = vl_aib(Pcx) ;
vl_assert_equal(parents, [5 5 6 6 7 7 1]) ;
vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ;
[cut,map,short] = vl_aibcut(parents,2) ;
vl_assert_equal(cut, [5 6]) ;
vl_assert_equal(map, [1 1 2 2 1 2 0]) ;
vl_assert_equal(short, [5 5 6 6 5 6 7]) ;
function test_cluster_null(s)
Pcx = [.5 .5 0 0
0 0 0 0] ;
% This results in the AIB tree
%
% 1 - \
% 5
% 2 - /
%
% 3 x
%
% 4 x
%
% If ClusterNull is specified, the values 3 and 4
% which have zero probability are merged first
%
% 1 ----------\
% 7
% 2 ----- \ /
% 6-/
% 3 -\ /
% 5 -/
% 4 -/
parents1 = vl_aib(Pcx) ;
parents2 = vl_aib(Pcx,'ClusterNull') ;
vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ;
vl_assert_equal(parents2(3), parents2(4)) ;
function x = mi(P)
% mutual information
P1 = sum(P,1) ;
P2 = sum(P,2) ;
x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_imarray.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_homkermap.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_slic.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_slic.m
| 211 |
utf_8
|
9077cfa77eb7b8d43880ba62408291f8
|
function results = vl_test_slic(varargin)
% VL_TEST_SLIC
vl_test_init ;
function s = setup()
s.im = im2single(vl_impattern('roofs1')) ;
function test_slic(s)
segmentation = vl_slic(s.im, 10, 0.1, 'verbose') ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_ikmeans.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_ikmeans.m
| 466 |
utf_8
|
1ee2f647ac0035ed0d704a0cd615b040
|
function results = vl_test_ikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[centers, assign] = vl_ikmeans(s.data,100) ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[centers, assign] = vl_ikmeans(s.data,100,'method','elkan') ;
assign_ = vl_ikmeanspush(s.data, centers) ;
vl_assert_equal(assign,assign_) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_mser.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_mser.m
| 242 |
utf_8
|
1ad33563b0c86542a2978ee94e0f4a39
|
function results = vl_test_mser(varargin)
% VL_TEST_MSER
vl_test_init ;
function s = setup()
s.im = im2uint8(rgb2gray(vl_impattern('roofs1'))) ;
function test_mser(s)
[regions,frames] = vl_mser(s.im) ;
mask = vl_erfill(s.im, regions(1)) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_inthist.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_inthist.m
| 811 |
utf_8
|
459027d0c54d8f197563a02ab66ef45d
|
function results = vl_test_inthist(varargin)
% VL_TEST_INTHIST
vl_test_init ;
function s = setup()
rand('state',0) ;
s.labels = uint32(8*rand(123, 76, 3)) ;
function test_basic(s)
l = 10 ;
hist = vl_inthist(s.labels, 'numlabels', l) ;
hist_ = inthist_slow(s.labels, l) ;
vl_assert_equal(double(hist),hist_) ;
function test_sample(s)
rand('state',0) ;
boxes = 10 * rand(4,20) + .5 ;
boxes(3:4,:) = boxes(3:4,:) + boxes(1:2,:) ;
boxes = min(boxes, 10) ;
boxes = uint32(boxes) ;
inthist = vl_inthist(s.labels) ;
hist = vl_sampleinthist(inthist, boxes) ;
function hist = inthist_slow(labels, numLabels)
m = size(labels,1) ;
n = size(labels,2) ;
l = numLabels ;
b = zeros(m*n,l) ;
b = vl_binsum(b, 1, reshape(labels,m*n,[]), 2) ;
b = reshape(b,m,n,l) ;
for k=1:l
hist(:,:,k) = cumsum(cumsum(b(:,:,k)')') ;
end
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_imdisttf.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_pr.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_pr.m
| 2,950 |
utf_8
|
fbe44689dacb16970984e4dbcede0430
|
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]) ;
|
github
|
rising-turtle/slam_matlab-master
|
vl_test_hog.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_argparse.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_binsearch.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_test_maketrainingset.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/xtest/vl_test_maketrainingset.m
| 1,014 |
utf_8
|
147ca63d80a18ed3659dac4a3efcf84e
|
function results = vl_test_maketrainingset(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)] ;
function test_plain_trainingset(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
tset = vl_maketrainingset(conv(s.X),int8(s.y)) ;
vl_assert_almost_equal(tset.data, conv(s.X), 0.1) ;
vl_assert_almost_equal(tset.labels, int8(s.y), 0.1) ;
end
function test_homkermap(s)
for conv = {@single,@double}
vl_twister('state',0) ;
conv = conv{1} ;
tset = vl_maketrainingset(conv(s.X),int8(s.y),'homkermap',1, ...
'kchi2', 'gamma', .5) ;
vl_assert_almost_equal(tset.data, conv(s.X), 0.1) ;
vl_assert_almost_equal(tset.labels, int8(s.y), 0.1) ;
vl_assert_equal(tset.map.order, 1) ;
end
|
github
|
rising-turtle/slam_matlab-master
|
vl_plotframe.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/plotop/vl_plotframe.m
| 5,397 |
utf_8
|
eb21148a33aae6a835f47faa0db311d6
|
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) ;
% Convert frames to oriented ellipses
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
|
rising-turtle/slam_matlab-master
|
vl_roc.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/plotop/vl_roc.m
| 8,743 |
utf_8
|
eb8acd02ccf91e98a933e49754da010a
|
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 = 'tntp' ; 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 positve 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 positve rate') ;
ylabel('true positve 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 positve 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
|
rising-turtle/slam_matlab-master
|
vl_click.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_pr.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/toolbox/plotop/vl_pr.m
| 8,131 |
utf_8
|
089b4b895dac21402ff0f7fba75fb823
|
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 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 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 specify additional 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.
%
% 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.
%
% 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, fp, p, n, perm, varargin] = vl_tpfp(labels, scores, varargin{:}) ;
opts.stable = false ;
opts.interpolate = false ;
opts = vl_argparse(opts,varargin) ;
% compute precision and recall
small = 1e-10 ;
recall = tp / max(p, small) ;
precision = max(tp, small) ./ max(tp + fp, small) ;
% 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) ;
spline([0 1], [1 1] * p / length(labels), '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
|
rising-turtle/slam_matlab-master
|
vl_ubcread.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
vl_plotsiftdescriptor.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
phow_caltech101.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/apps/phow_caltech101.m
| 11,301 |
utf_8
|
8316095b4842a2c43cf3dfc91e313aee
|
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 ;
data = vl_maketrainingset(psix(:,selTrain(perm)), int8(y(perm))) ;
[w(:,ci) b(ci)] = vl_svmpegasos(data, lambda, ...
'MaxIterations', 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 * 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 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, 'kchi2', 'period', .7) ;
scores = model.w' * psix + model.b' ;
[score, best] = max(scores) ;
className = model.classes{best} ;
|
github
|
rising-turtle/slam_matlab-master
|
sift_mosaic.m
|
.m
|
slam_matlab-master/SIFT/vlfeat-0.9.16/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
|
rising-turtle/slam_matlab-master
|
gen_shapes.m
|
.m
|
slam_matlab-master/SIFT/vicinalboost-1.0/code/gen_shapes.m
| 3,755 |
utf_8
|
059f82692aa112d79d75cc2e74209581
|
function gen_shapes
% GEN_SHAPES Generate synthetic shapes dataset
% Data will be saved to 'data/shapes.mat'.
% N = number of patches per type
% h = size of a patch in pixels
N = 1000 ;
h = 24 ;
% these functions generates the basic shapes
genf = { @genbox, @gentri, @gencirc, @genstar } ;
% x will store the patterns and y their labels
x = [] ;
y = [] ;
% loop over shapes kind
for k=1:length(genf)
% generate the shape and the virtual samples
D = virtualsamples(genf{k},N,h) ;
% generate a preview
figure(k) ; clf ; imarraysc((D+1)/2,'clim',[-1 1]) ;
colormap gray ; drawnow ;
% store patterns
x = [x reshape(D,h*h,N)] ;
y = [y k*ones(1,size(D,3))] ;
end
save('data/shapes','x','y') ;
% --------------------------------------------------------------------
function D=virtualsamples(shapef,N,h)
% --------------------------------------------------------------------
% generate basic shape
mask = feval(shapef,h) ;
% parameters
sigma(1) = .5 ; % std dev translation x
sigma(2) = .5 ; % std dev translation y
sigma(3) = .2 ; % std dev skewiness
sigma(4) = .1 ; % std dev scale
sigma(5) = .1 ; % std dev rotation
sigma(6) = .08 ; % std dev brightness
sigma(7) = .1 ; % std dev offset
sigma(8) = .05 ; % std dev noise
% brightness bias (min abs bright)
bright = .5 ;
% generate a bunch of random affine tf
tx = sigma(1) * randn(1,N) ;
ty = sigma(2) * randn(1,N) ;
sk = sigma(3) * randn(1,N) ;
sc = sigma(4) * randn(1,N) + 1 ;
rt = sigma(5) * randn(1,N) ;
% generate a bunch of illuminations
b = sigma(6) * randn(1,N) ; b = sign(b)*bright + b ;
o = sigma(7) * randn(1,N) ;
% coordinate system
ur=linspace(-h/2,h/2,h) ;
vr=linspace(-h/2,h/2,h) ;
[u,v]=meshgrid(ur,vr) ;
% warp patches
D = zeros(h,h,N) ;
for n=1:N
c = cos(rt(n)) ;
s = sin(rt(n)) ;
% rotation, skew, scale translation
R = [c -s ; s c ] ;
Q = [1 sk(n) ; 0 1 ] ;
S = [sc(n) 0 ; 0 sc(n) ] ;
T = [tx(n) ; ty(n) ] ;
% compose
A = R*S*Q ;
% warp mesh
[wu,wv]=waffine(A,T,u,v);
% warp image
I = imwbackward(ur,vr,mask,wu,wv) ;
% pad with zeros instead of NaNs
I(isnan(I))=0 ;
% add brightness, offsett and noise
I = b(n)*I + o(n) + sigma(8)*randn(h) ;
% save back
D(:,:,n) = I ;
%figure(100) ; clf ; imagesc(I) ; drawnow ; colormap gray ;
end
% --------------------------------------------------------------------
function mask=genbox(h)
% --------------------------------------------------------------------
mask = zeros(h) ;
mask(6:18,6:18) =1 ;
% --------------------------------------------------------------------
function mask=gencirc(h)
% --------------------------------------------------------------------
mask = zeros(h) ;
ur=linspace(-h/2,h/2,h) ;
vr=linspace(-h/2,h/2,h) ;
[u,v]=meshgrid(ur,vr) ;
mask = (1+erf((h/3)^2 - u.*u-v.*v))*.5 ;
% --------------------------------------------------------------------
function mask=gentri(h)
% --------------------------------------------------------------------
ur=linspace(-h/2,h/2,h) ;
vr=linspace(-h/2,h/2,h) ;
[u,v]=meshgrid(ur,vr) ;
mask = (1+erf((h/3)^2 - u.*u-v.*v)) ;
n1 = [-sqrt(3),-1] ;
l1 = +sqrt(3)/4 ;
n2 = [+sqrt(3),-1] ;
l2 = +sqrt(3)/4 ;
n3 = [0,+1] ;
l3 = +sqrt(3)/4 ;
dv = -sqrt(3)/4 + 2/sqrt(3)/4 ;
sc = 1.5/h;
u = sc * u ;
v = sc * v + dv ;
mask = ones(h) ;
mask = mask & (n1(1)*u+n1(2)*v+l1 >= 0) ;
mask = mask & (n2(1)*u+n2(2)*v+l2 >= 0) ;
mask = mask & (n3(1)*u+n3(2)*v+l3 >= 0) ;
mask = double(mask) ;
% --------------------------------------------------------------------
function mask=genstar(h)
% --------------------------------------------------------------------
mask = gentri(h) ;
mask = mask | flipud(gentri(h)) ;
mask = double(mask) ;
|
github
|
rising-turtle/slam_matlab-master
|
vicinalboost.m
|
.m
|
slam_matlab-master/SIFT/vicinalboost-1.0/code/vicinalboost.m
| 18,197 |
utf_8
|
2f86f963b5d08b16753b25e8ac24f903
|
function rs = vicinalboost(cfg, data)
% VICINALBOOST
%
% RS = VICINALBOOST(CFG, DATA)
%
% DATA is a structure with the following fields:
%
% DATA.Y Training data labels
% DATA.X Training data samples
% DATA.DX Data tangent vectors (scaled)
% DATA.IS_TRAIN Mark training / testing data
% DATA.F0 Collection of initial WCs
% DATA.DIMS Dimensions of the data (for visualization)
%
%
% CFG is a structure with the following fields:
%
% CFG.NWC Number of weak classifier of the final model
% CFG.SIGMA Isotropic Parzen window smoothing
% CFG.USE_TG Use or not the tangent space
% CFG.GD_MAX_NITERS # of GD iterations (set to 0 to de-activate)
% CFG.GD_RESTART_NITERS
% # of GD iterations before restart
% CFG.GD_METHOD CGD method: 'NONE', 'FR, 'PR', 'HS'.
% CFG.HAAR_N # of HAAR wavelets (set t0 0 to de-activate)
% CFG.VERBOSITY 0 - quiet, 1 - text, 2 - main figs, 3 - all
%
% RS is a structure with the following fields:
%
% RS.F Weak classifiers parameters
% RS.COEFF Coefficients
% RS.EE Exp. criterion as each WC is added
% RS.E01 Train error as each WC is added
% RS.E01T Test error as each WC is added
% AUTORIGHTS
% Copyright 2007 (c) Andrea Vedaldi and Paolo Favaro
%
% This file is part of VicinalBoost, available in the terms of the GNU
% General Public License version 2.
% --------------------------------------------------------------------
% Setup
% --------------------------------------------------------------------
% sel = select training data
% selt = select testing data
sel = find( data.is_train) ;
selt = find(~data.is_train) ;
% this is not really necessary:
sel = sel(randperm(length(sel))) ;
selt = selt(randperm(length(selt))) ;
% y = training data labels
% yt = testing data labels
% x = training data
% xt = testing data
y = data.y( sel ) ;
yt = data.y( selt) ;
x = data.x(:, sel ) ;
xt = data.x(:, selt) ;
% L = data dimensionality
% N = # of training data
% Nt = # of testing data
% Np = # of positive training data
% Nm = # of negative training data
% Npt = # of positive testing data
% Nmt = # of negative testing data
L = size(data.x, 1) ;
N = length(sel ) ;
Nt = length(selt) ;
Np = sum(y == +1) ;
Npt = sum(yt == +1) ;
Nm = N - Np ;
Nmt = Nt - Npt ;
% wgt = AdaBoost coefficients or weights
% ywgt = weights .* y
% F = weak classifiers selected so far
% H = strong classifier H evaluated on train
% Ht = strong classifier H evaluated on test
wgt = ones(1,N) / N ;
ywgt = y .* wgt ;
F = zeros(L + 1, cfg.nwc) ;
coeff = zeros(1, cfg.nwc) ;
H = zeros(1, N ) ;
Ht = zeros(1, Nt) ;
movie_nf = 1 ;
movie_do = 0 ;
% e01 = 01 loss of strong class on train
% e01t = 01 loss of strong class on test
% ee = exp loss of strong class on train
rs.e01 = zeros(1, cfg.nwc) ;
rs.e01t = zeros(1, cfg.nwc) ;
rs.ee = zeros(1, cfg.nwc) ;
% weights used to rebalance the test set to correspond to the train
% set when computing the test error
adj_test = zeros(length(yt),1) ;
adj_test(yt == +1) = (Nt / Npt) * (Np / N) ;
adj_test(yt == -1) = (Nt / Nmt) * (Nm / N) ;
if cfg.verbosity > 0
fprintf('vicinalboost: sigma = %g\n', cfg.sigma) ;
fprintf('vicinalboost: use_tg = %g\n', cfg.use_tg) ;
fprintf('vicinalboost: gd_max_niters = %d\n', cfg.gd_max_niters) ;
fprintf('vicinalboost: gd_restart_niters = %d\n', cfg.gd_restart_niters) ;
fprintf('vicinalboost: gd_method = %s\n', cfg.gd_method) ;
fprintf('vicinalboost: haar_n = %d\n', cfg.haar_n) ;
fprintf('vicinalboost: train data: %d (%d pos, %d neg)\n', N, Np, Nm ) ;
fprintf('vicinalboost: test data: %d (%d pos, %d neg)\n', Nt, Npt, Nmt) ;
fprintf('vicinalboost: init WCs: %d\n', size(data.F0,2)) ;
end
% --------------------------------------------------------------------
% Parzen smoothing
% --------------------------------------------------------------------
% Prepare co-variance matrices of Parzen's kernels.
% sigma = isotropic Parzen's window variance
sigma = cfg.sigma ;
if cfg.use_tg == 0
% for isotropic noise S is a scalar
S = sigma * ones(1, N ) ;
St = sigma * ones(1, Nt) ;
if cfg.verbosity
fprintf('vicinalboost: using isotropic Parzen window\n') ;
end
else
% for anisotropic noise S is a scalar plus a vector for each
% tangent space dimensions.
P = length(data.dx) ;
S = sigma * ones(P*L+1, N ) ;
St = sigma * ones(P*L+1, Nt) ;
for p=1:P
S( 1 + (p-1) * L + (1:L), :) = data.dx{p}(:, sel ) ;
St(1 + (p-1) * L + (1:L), :) = data.dx{p}(:, selt) ;
end
if cfg.verbosity
fprintf('vicinalboost: using anisotropic Parzen window with %d directions\n', P) ;
end
end
% --------------------------------------------------------------------
% Pre-processing
% --------------------------------------------------------------------
% For each initial WC h in data.F0 compute
% ha = - <gamma1,x_i>
% hb = sqrt(2 gamma1'S(x_i)gamma1)
if cfg.verbosity
fprintf('vicinalboost: pre-processing initial WCs ... ') ;
end
K = size(data.F0, 2) ;
ha = zeros(K, N) ;
hb = zeros(K, N) ;
for k = 1:K
gamma1 = data.F0(2:end,k) ;
ha(k,:) = - gamma1' * x ;
hb(k,:) = sqrt( 2 * multvar(S,gamma1) ) ;
if cfg.verbosity
fprintf('\b\b\b\b\b\b\b [%4i]',k) ;
end
end
if cfg.verbosity
fprintf(' done.\n') ;
end
if 0
figure(1) ; clf ; colormap gray ;
imarraysc(reshape(data.F0(2:end,:),24,24,WC)) ;
end
% --------------------------------------------------------------------
% Boost
% --------------------------------------------------------------------
force_stop = 0 ;
for t = 1:cfg.nwc
% ------------------------------------------------------------------
% Select best initial WC
% ------------------------------------------------------------------
% Compute optimal threshold and optimal correlation of each WC
K = size(data.F0, 2) ;
E = zeros(1, K) ;
gamma0 = zeros(1, K) ;
nu = sqrt(2/pi) ;
for k = 1:K
a = ha(k,:) ;
b = hb(k,:) ;
ywgtp = [ +ywgt -ywgt ] ;
ap = [ a-b*nu a+b*nu ] ;
bp = [ b*nu b*nu ] ;
% divide
ywgtp = ywgtp ./ bp ;
% sort
[ap,perm] = sort(ap) ;
ywgtp = ywgtp(perm) ;
% energy for all threhsolds
Ep = - ap .* cumsum(ywgtp) + cumsum(ap .* ywgtp) ;
% sanity check
if 0
figure(212) ; clf ; hold on ;
plot(ap,Ep) ;
Epp = [] ;
for t=ap
param = [t;h_set(2:end,k)] ;
Epp = [Epp -sum(ywgt.*weak_erf(param,x,S)) ] ;
end
plot(ap,Epp,'r') ;
drawnow;
end
% select best threshold
[Ep,best] = min(Ep) ;
% this is the fit for the WC number k. Save back.
E(k) = - Ep ;
gamma0(k) = ap(best) ;
end
% Select best WC
[drop,best] = max(E) ;
% take the parameters of the WC and the optimal threshold
param = [gamma0(best) ; data.F0(2:end,best)] ;
h_cur = weak_erf(param,x,S) ;
E = E(best) ;
% ------------------------------------------------------------------
% Optimize WC
% ------------------------------------------------------------------
% Optimize orientation and treshold by gradient descent
% extract parameters
gamma0 = param(1) ;
gamma1 = param(2:end) ;
% for non-linear conjugate gradient descent
conj = [] ;
for gd_iter = 1:cfg.gd_max_niters
[gSg,Sg] = multvar(S,gamma1) ;
gSg = 2 * gSg ;
sgSg = sqrt(gSg) ;
num = gamma0 + gamma1' * x ;
wdrf = ywgt .* derf( num ./ sgSg ) ;
tmp1 = wdrf ./ sgSg ;
tmp2 = 2 * tmp1 .* num ./ gSg ;
dgamma0 = sum(tmp1) ;
dgamma1 = x * tmp1' - Sg * tmp2' ;
% Non-linear conjugate gradient adjustment.
%
% See:
%
% http://www.ipp.mpg.de/de/for/bereiche/stellarator/ ...
% Comp_sci/CompScience/csep/csep1.phy.ornl.gov/mo/node20.html
if mod(gd_iter - 1, cfg.gd_restart_niters) == 0
% restart conjugate direction after n iterations
grad = [dgamma0 ; dgamma1] ;
conj = grad ;
else
% calculate conjugate direction
grad_ = grad ;
conj_ = conj ;
grad = [dgamma0 ; dgamma1] ;
switch cfg.gd_method
case 'none'
beta = 0 ;
case 'fr'
beta = (grad'*grad) / (grad_'*grad_) ;
case 'pr'
beta = (grad'*(grad-grad_)) / (grad_'*grad_) ;
case 'hs'
beta = (grad'*(grad-grad_)) / (conj_'*(grad-grad_)) ;
end
% rarely it might procude NaNs... in this case give up
if isnan(beta), beta = 0 ; end
conj = grad + beta*conj_ ;
dgamma0 = conj(1) ;
dgamma1 = conj(2:end) ;
end
% Now the direction is decided by the gradient; do
% a Newton step along that direction!
%
%
% MAPLE says:
% a + l b
% f := l -> ----------------------
% 2
% sqrt(c + 2 r l + d l )
%
% b (a + l b) (2 r + 2 d l)
% --------------------- - 1/2 -----------------------
% 2 1/2 2 3/2
% (c + 2 r l + d l ) (c + 2 r l + d l )
%
% 2
% b (2 r + 2 d l) (a + l b) (2 r + 2 d l) (a + l b) d
% - --------------------- + 3/4 ------------------------ - ---------------------
% 2 3/2 2 5/2 2 3/2
% (c + 2 r l + d l ) (c + 2 r l + d l ) (c + 2 r l + d l )
step = 0 ;
a = gamma0 + gamma1' * x ;
b = dgamma0 + dgamma1' * x ;
c = gSg / 2 ;
d = multvar(S,dgamma1) ;
r = multvar(S,gamma1,dgamma1) ;
den = c + 2*r* step + d* step^2 ;
dens = sqrt(den) ;
den3s = den .* dens ;
den5s = den .* den3s ;
tmp1 = a + b * step ;
tmp2 = 2 * (r + d * step) ;
tmp3 = tmp1 ./ dens ;
drf = ywgt .* derf(tmp3 / sqrt(2)) / sqrt(2) ;
ddrf = ywgt .* dderf(tmp3 / sqrt(2)) / 2 ;
tmp4 = b ./ dens - .5 * tmp1.*tmp2./den3s ;
tmp5 = - b.*tmp2./den3s ...
+ 3/4 * tmp1.* tmp2.*tmp2./den5s ...
- tmp1.*d./den3s ;
dstep = sum( drf .* tmp4) ;
ddstep = sum(ddrf .* tmp4.*tmp4 + drf .* tmp5);
if abs(ddstep) < 1e-10
ddstep = 1e-10 ;
end
stepsz = - dstep / ddstep ;
% We adjust stepsz for cases in which the Hessian is really bad
% (stepsz < 0) and we also enlarge a little bit the aperture.
stepsz = abs(stepsz) * 1.5 ;
% Line search
stepr = linspace(0,stepsz,15) ;
for i = 1:length(stepr)
step = stepr(i) ;
den = c + 2*r* step + d* step^2 ;
dens = sqrt(den) ;
den3s = den .* dens ;
den5s = den .* den3s ;
tmp1 = a + b * step ;
tmp2 = 2 * (r + d * step) ;
tmp3 = tmp1 ./ dens ;
rf = ywgt .* erf(tmp3 / sqrt(2)) ;
E_ls(i) = sum(rf) ;
end
[E_,best] = max(E_ls) ;
step = stepr(best) ;
% do step, finally
gamma1_ = gamma1 + step * dgamma1 ;
gamma0_ = gamma0 + step * dgamma0 ;
param_ = [gamma0_;gamma1_] ;
h_cur_ = weak_erf(param_,x,S) ;
% save pack for next iteration
E = E_ ;
gamma1 = gamma1_ ;
gamma0 = gamma0_ ;
param = param_ ;
h_cur = h_cur_ ;
% save history
E_gd(gd_iter) = E ;
if gd_iter > 1 && ...
(E_gd(gd_iter) - E_gd(gd_iter-1))/E_gd(gd_iter-1) < 1e-5
break ;
end
if cfg.verbosity >=3
figure(1000) ; clf ;
set(gcf,'color','w') ;
axes('position',[.08 .08 .36 .36]) ;
plot(E_gd(1:gd_iter),'linewidth',2) ;
title('Weak classifier fit') ;
ylabel('fit') ;
xlabel('iteration') ;
subplot(2,2,1) ;
if length(data.dims == 2)
imagesc(reshape(gamma1,data.dims))
axis equal ; axis off ;
else
plot(gamma1(:)) ;
end
title('Weak classifier') ;
subplot(2,2,2) ;
if length(data.dims == 2)
imagesc(reshape(dgamma1,data.dims)) ;
axis equal ; axis off ;
else
plot(dgamma1(:)) ;
end
title('Weak classifier gradient') ;;
axes('position',[.58 .08 .36 .36]) ;
plot(stepr,E_ls,'linewidth',2) ;
title('Line search') ;
ylabel('fit') ;
xlabel('step size') ;
drawnow ;
spn = linspace(0,1,256) ;
colormap(gray(256)) ;
if movie_do
MOV(nf) = getframe(1000) ;
nf=nf+1 ;
end
end
end % next GD iteration
if cfg.haar_n > 0
% approximate WC with Haar wavelets
sz = data.dims ;
if (length(sz) ~= 2),
error('Haar projection is supported only for 2D data');
end
gamma_haar = image2dyadic(gamma1,sz);
gamma_haar = haarfilter(gamma_haar,sz,...
floor(log2(min(sz))),...
cfg.haar_n) ;
gamma_haar = dyadic2image(gamma_haar,sz);
gamma1_ = gamma_haar(:);
param_ = [gamma0;gamma1_] ;
h_cur_ = weak_erf(param_,x,S) ;
% save pack for next iteration
gamma1 = gamma1_ ;
param = param_ ;
h_cur = h_cur_ ;
% re-calculate correlation
E = sum(ywgt .* h_cur) ;
end
% ------------------------------------------------------------------
% Calculate mixing constant
% ------------------------------------------------------------------
% E at this point must contain correlation of current learner to
% boosting gradient and SZ its size
c = 0 ;
wgt_ = wgt ;
if all(y .* h_cur > 0)
force_stop = 1 ;
if t == 1
c = 1 ;
else
c = coeff(t - 1) ;
end
end
while ~ force_stop
% re-calculate weak classifier size
SZ = sum(wgt .* h_cur .* h_cur) ;
% Gauss-Newton step
dc = E / SZ ;
c = c + dc ;
% update weights
wgt = wgt_ .* exp( - c .* y .* h_cur) ;
Z = sum(wgt) ;
wgt = wgt / Z ;
ywgt = y .* wgt ;
if dc / (c+1e-3) < 1e-8
break
end
% re-calculate correlation
E = sum(ywgt .* h_cur) ;
end
% ------------------------------------------------------------------
% Record new weak classifier
% ------------------------------------------------------------------
F(:,t) = param ;
coeff(t) = c ;
% ------------------------------------------------------------------
% Update
% ------------------------------------------------------------------
% train
H = H + coeff(t) * h_cur ;
% test
ht = weak_erf(F(:,t), xt, St) ;
Ht = Ht + coeff(t) * ht ;
% ------------------------------------------------------------------
% Energies
% ------------------------------------------------------------------
rs.ee(t) = mean(exp(- y .* H)) ;
rs.e01(t) = mean((1 - y .* sign(H) ) / 2) ;
rs.e01t(t) = mean((1 - yt .* sign(Ht)) / 2 .* adj_test') ;
if force_stop
break ;
end
% ------------------------------------------------------------------
% Plots
% ------------------------------------------------------------------
% if(mod(t - 1, 10)~=0 && t ~= cfg.nwc) continue ; end
%fprintf('ada: weak learner %d added\n',t) ;
fprintf('vicinalboost: nwc:%4i train:%5.2f%% test:%5.2f%% exp:%5.2f%%\n',...
t,...
rs.e01(t) * 100, ...
rs.e01t(t) * 100, ...
rs.ee(t) * 100) ;
if cfg.verbosity >= 2
figure(100) ; clf ;
hold on ;
plot(rs.ee(1:t) * 100, 'r-', 'LineWidth',2) ;
plot(rs.e01(1:t) * 100, 'b-', 'LineWidth',2) ;
plot(rs.e01t(1:t) * 100, 'g-', 'LineWidth',2) ;
ylim([0 110]) ; ylabel('%') ;
xlabel('num. WCs') ;
legend('exp. bound','train err.','tes err.') ;
title('Energies') ;
end
drawnow ;
if movie_do
MOV(nf) = getframe(gcf) ;
nf=nf + 1 ;
end
end
rs.ee(t+1:end) = rs.ee(t) ;
rs.e01(t+1:end) = rs.e01(t) ;
rs.e01t(t+1:end) = rs.e01t(t) ;
rs.cfg = cfg ;
rs.F = F ;
rs.coeff = coeff ;
% --------------------------------------------------------------------
function y = weak(h,X)
% --------------------------------------------------------------------
% Calculate weak lerner.
c = cos(h(1)) ;
s = sin(h(1)) ;
y = sign([c s]*X-h(2)) ;
% --------------------------------------------------------------------
function y = weak_erf(h,X,S)
% --------------------------------------------------------------------
% Calculate smooth weak learner.
% Each column of S is either a scalar or a stacked varaince matrix.
L = size(X,1) ;
N = size(X,2) ;
fast_erf = @erf ;
num = h(2:end)' * X + h(1) ;
den = sqrt( 2 * multvar(S,h(2:end)) ) ;
y = fast_erf( num ./ den ) ;
% --------------------------------------------------------------------
function y = derf(x)
% --------------------------------------------------------------------
% erf derivative
y = 2/sqrt(pi) * exp(-x.*x) ;
% --------------------------------------------------------------------
function y = dderf(x)
% --------------------------------------------------------------------
% erf second derivative
y = - 4/sqrt(pi) * x .* exp(-x.*x) ;
|
github
|
rising-turtle/slam_matlab-master
|
plotexp.m
|
.m
|
slam_matlab-master/SIFT/vicinalboost-1.0/code/experiments/plotexp.m
| 5,198 |
utf_8
|
4cbdb4ceb5f1ff95ac8640af96a9cf85
|
function plotexp(rs, aggr, split, print_path)
% PLOTEXP Plot experiment results
%
% PLOTEXP(RS, AGGR) plot the experiments RS. AGGR is a cell array of
% string listing the fileds of the RS structure that should be used
% to identify uniquely an experiment (experiments with the same
% values of this field are treated as equivalent folds and aggregate
% in the plotted statistics).
cfg.do_bars = 1 ;
rs = [rs{:}] ;
if nargin < 3 || isequal(split, [])
split = aggr{end} ;
end
if nargin < 3
print_path = [] ;
end
styles = { { 'color', [1 .75 .75], 'linestyle', '--', 'marker', 'none' }, ...
{ 'color', [1 .5 .5], 'linestyle', '-', 'marker', 'none' }, ...
{ 'color', [1 0 0], 'linestyle', '-', 'marker', '.' }, ...
{ 'color', [.75 1 .75], 'linestyle', '--', 'marker', 'none' }, ...
{ 'color', [.5 1 .5], 'linestyle', '-', 'marker', 'none' }, ...
{ 'color', [0 1 0], 'linestyle', '-', 'marker', '.' }, ...
{ 'color', [.75 .75 1], 'linestyle', '--', 'marker', 'none' }, ...
{ 'color', [.5 .5 1], 'linestyle', '-', 'marker', 'none' }, ...
{ 'color', [0 0 1], 'linestyle', '-', 'marker', '.' } } ;
% --------------------------------------------------------------------
% Aggregate and split experiments
% --------------------------------------------------------------------
% The fields in SPLIT are used to divide the experiments in
% multplipe figures.
% valies assumed by the split fields
splitr = unique_cells({rs.(split)}) ;
% remove from aggr fields the one appearing among the split fields
aggr_ = aggr ;
aggr_(strcmp(split, aggr_)) = [] ;
% -------------------------------------------------------------------
% For each split a figure
% -------------------------------------------------------------------
for splitv = splitr
legend_content = {} ;
bar_data = [] ;
% create a new figure
figure(find(splitv == splitr)) ; clf ;
subplot(2,1,1) ; hold on ;
% find subset of experiments with this value of the split parameter
sel_split = find_cells({rs.(split)}, splitv) ;
rs_split = rs(sel_split) ;
% for all experiment in the split, aggregate the data and plot
% the corresponding curves
n_curve = 1 ;
while ~ isempty(rs_split)
% ---------------------------------------------------------------
% For this figure
% ---------------------------------------------------------------
% Aggregate folds
sel_aggr = 1:length(rs_split) ;
legend_content{end+1} = '' ;
for af = aggr_
% value of the next aggr field
af = af{1} ;
aggrv = rs_split(1).(af) ;
% find all experiments with that value of the aggr field
sel_aggr = intersect(sel_aggr, find_cells({rs_split.(af)}, aggrv)) ;
legend_content{end} = [legend_content{end} ...
sprintf('%s=%g ', af, aggrv)] ;
end
% collect error curves
e01 = rs_split(sel_aggr(1)).e01t ;
for s=sel_aggr(2:end)
e01 = [e01 ; rs_split(s).e01t] ;
end
std_e01 = std(e01,1) ;
avg_e01 = mean(e01,1) ;
% add to bar data
bar_data = [bar_data, ...
[mean(avg_e01(end-3:end)); mean(std_e01(end-3:end)) ; ] ];
% plot
if cfg.do_bars
prec = std_e01 / sqrt(length(sel_aggr)) ;
h = errorbar(1:size(e01,2), 100 * avg_e01, 100 * prec) ;
else
h = plot(1:size(e01,2), 100*mean(e01,1)) ;
end
if n_curve <= length(styles)
set(h, styles{n_curve}{:}) ;
else
extra_cols = jet(256) ;
set(h, 'color', extra_cols(n_curve, :)) ;
end
yl = get(gca,'ylim') ; yl(1)=0; set(gca,'ylim',yl) ;
xlim([0 size(e01,2)]) ;
% remove the aggregate set of experiments from the split
rs_split(sel_aggr) = [] ;
% next curve
n_curve = n_curve + 1 ;
% keyboard
end
if n_curve <= 10
h=legend(legend_content{:},'location','northeastoutside') ;
else
h=legend(legend_content{1:10},'...','location','northeastoutside') ;
end
for k=1:length(legend_content)
fprintf('%5d: %s\n', k, legend_content{k}) ;
end
set(h,'interpreter','none')
xlabel('num. WCs') ;
ylabel('test error (%)') ;
ylim([0 30]) ;
title(sprintf('%s = %g', split, splitv)) ;
% bar plot
subplot(2,1,2) ;
clear bard ;
bard(1,:) = bar_data(1,:) - bar_data(2,:) ;
bard(2,:) = bar_data(2,:) ;
bard(3,:) = bar_data(2,:) ;
bar(bard','stacked') ;
xlabel('curve number') ;
if ~isempty(print_path)
name = [print_path sprintf('-%d',find(splitv == splitr))] ;
print(fullfile('figures', name),'-depsc') ;
end
end
% --------------------------------------------------------------------
function b = unique_cells(a)
% --------------------------------------------------------------------
if isnumeric(a{1})
b = unique([a{:}]) ;
else
b = unique(a) ;
end
% --------------------------------------------------------------------
function b = find_cells(a, x)
% --------------------------------------------------------------------
b = [] ;
for t = 1:numel(a)
if isequal(a{t}, x), b = [b t] ; end
end
|
github
|
rising-turtle/slam_matlab-master
|
plotmatches.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.19/sift/plotmatches.m
| 10,144 |
utf_8
|
4d7daa0d3265f0885ebc7f3310a47fc1
|
function h=plotmatches(I1,I2,P1,P2,matches,varargin)
% PLOTMATCHES Plot keypoint matches
% PLOTMATCHES(I1,I2,P1,P2,MATCHES) plots the two images I1 and I2
% and lines connecting the frames (keypoints) P1 and P2 as specified
% by MATCHES.
%
% P1 and P2 specify two sets of frames, one per column. The first
% two elements of each column specify the X,Y coordinates of the
% corresponding frame. Any other element is ignored.
%
% MATCHES specifies a set of matches, one per column. The two
% elementes of each column are two indexes in the sets P1 and P2
% respectively.
%
% The images I1 and I2 might be either both grayscale or both color
% and must have DOUBLE storage class. If they are color the range
% must be normalized in [0,1].
%
% The function accepts the following option-value pairs:
%
% 'Stacking' ['h']
% Stacking of images: horizontal ['h'], vertical ['v'], diagonal
% ['h'], overlap ['o']
%
% 'Interactive' [0]
% If set to 1, starts the interactive session. In this mode the
% program lets the user browse the matches by moving the mouse:
% Click to select and highlight a match; press any key to end.
% If set to a value greater than 1, the feature matches are not
% drawn at all (useful for cluttered scenes).
%
% See also PLOTSIFTDESCRIPTOR(), PLOTSIFTFRAME(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
stack='h' ;
interactive=0 ;
only_interactive=0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'stacking'
stack=varargin{k+1} ;
case 'interactive'
interactive=varargin{k+1};
otherwise
error(['[Unknown option ''', varargin{k}, '''.']) ;
end
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
[M1,N1,K1]=size(I1) ;
[M2,N2,K2]=size(I2) ;
switch stack
case 'h'
N3=N1+N2 ;
M3=max(M1,M2) ;
oj=N1 ;
oi=0 ;
case 'v'
M3=M1+M2 ;
N3=max(N1,N2) ;
oj=0 ;
oi=M1 ;
case 'd'
M3=M1+M2 ;
N3=N1+N2 ;
oj=N1 ;
oi=M1 ;
case 'o'
M3=max(M1,M2) ;
N3=max(N1,N2) ;
oj=0;
oi=0;
otherwise
error(['Unkown stacking type '''], stack, ['''.']) ;
end
% Combine the two images. In most cases just place one image next to
% the other. If the stacking is 'o', however, combine the two images
% linearly.
I=zeros(M3,N3,K1) ;
if stack ~= 'o'
I(1:M1,1:N1,:) = I1 ;
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
else
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
I(1:M1,1:N1,:) = I(1:M1,1:N1,:) + I1 ;
I(1:min(M1,M2),1:min(N1,N2),:) = 0.5 * I(1:min(M1,M2),1:min(N1,N2),:) ;
end
axes('Position', [0 0 1 1]) ;
imagesc(I) ; colormap gray ; hold on ; axis image ; axis off ;
K = size(matches, 2) ;
nans = NaN * ones(1,K) ;
x = [ P1(1,matches(1,:)) ; P2(1,matches(2,:))+oj ; nans ] ;
y = [ P1(2,matches(1,:)) ; P2(2,matches(2,:))+oi ; nans ] ;
% if interactive > 1 we do not drive lines, but just points.
if(interactive > 1)
h = plot(x(:),y(:),'g.') ;
else
h = line(x(:)', y(:)') ;
end
set(h,'Marker','.','Color','g') ;
% --------------------------------------------------------------------
% Interactive
% --------------------------------------------------------------------
if(~interactive), return ; end
sel1 = unique(matches(1,:)) ;
sel2 = unique(matches(2,:)) ;
K1 = length(sel1) ; %size(P1,2) ;
K2 = length(sel2) ; %size(P2,2) ;
X = [ P1(1,sel1) P2(1,sel2)+oj ;
P1(2,sel1) P2(2,sel2)+oi ; ] ;
fig = gcf ;
is_hold = ishold ;
hold on ;
% save the handlers for later to restore
dhandler = get(fig,'WindowButtonDownFcn') ;
uhandler = get(fig,'WindowButtonUpFcn') ;
mhandler = get(fig,'WindowButtonMotionFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'KeyPressFcn', @key_handler) ;
set(fig,'WindowButtonDownFcn',@click_down_handler) ;
set(fig,'WindowButtonUpFcn', @click_up_handler) ;
set(fig,'Pointer','crosshair') ;
data.exit = 0 ; % signal exit to the interactive mode
data.selected = [] ; % currently selected feature
data.X = X ; % feature anchors
highlighted = [] ; % currently highlighted feature
hh = [] ; % hook of the highlight plot
guidata(fig,data) ;
while ~ data.exit
uiwait(fig) ;
data = guidata(fig) ;
if(any(size(highlighted) ~= size(data.selected)) || ...
any(highlighted ~= data.selected) )
highlighted = data.selected ;
% delete previous highlight
if( ~isempty(hh) )
delete(hh) ;
end
hh=[] ;
% each selected feature uses its own color
c=1 ;
colors=[1.0 0.0 0.0 ;
0.0 1.0 0.0 ;
0.0 0.0 1.0 ;
1.0 1.0 0.0 ;
0.0 1.0 1.0 ;
1.0 0.0 1.0 ] ;
% more than one feature might be seleted at one time...
for this=highlighted
% find matches
if( this <= K1 )
sel=find(matches(1,:)== sel1(this)) ;
else
sel=find(matches(2,:)== sel2(this-K1)) ;
end
K=length(sel) ;
% plot matches
x = [ P1(1,matches(1,sel)) ; P2(1,matches(2,sel))+oj ; nan*ones(1,K) ] ;
y = [ P1(2,matches(1,sel)) ; P2(2,matches(2,sel))+oi ; nan*ones(1,K) ] ;
hh = [hh line(x(:)', y(:)',...
'Marker','*',...
'Color',colors(c,:),...
'LineWidth',3)];
if( size(P1,1) == 4 )
f1 = unique(P1(:,matches(1,sel))','rows')' ;
hp=plotsiftframe(f1);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
if( size(P2,1) == 4 )
f2 = unique(P2(:,matches(2,sel))','rows')' ;
f2(1,:)=f2(1,:)+oj ;
f2(2,:)=f2(2,:)+oi ;
hp=plotsiftframe(f2);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
c=c+1 ;
end
drawnow ;
end
end
if( ~isempty(hh) )
delete(hh) ;
end
if ~is_hold
hold off ;
end
set(fig,'WindowButtonDownFcn', dhandler) ;
set(fig,'WindowButtonUpFcn', uhandler) ;
set(fig,'WindowButtonMotionFcn',mhandler) ;
set(fig,'KeyPressFcn', khandler) ;
set(fig,'Pointer', pointer ) ;
% ====================================================================
function data=selection_helper(data)
% --------------------------------------------------------------------
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
d = (data.X(1,:) - P(1)).^2 + (data.X(2,:) - P(2)).^2 ;
dmin=min(d) ;
idx=find(d==dmin) ;
data.selected = idx ;
% ====================================================================
function click_down_handler(obj,event)
% --------------------------------------------------------------------
% select a feature and change motion handler for dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
data.mhandler = get(fig,'WindowButtonMotionFcn') ;
set(fig,'WindowButtonMotionFcn',@motion_handler) ;
data = selection_helper(data) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function click_up_handler(obj,event)
% --------------------------------------------------------------------
% stop dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
set(fig,'WindowButtonMotionFcn',data.mhandler) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function motion_handler(obj,event)
% --------------------------------------------------------------------
% select features while dragging
data = guidata(obj) ;
data = selection_helper(data);
guidata(obj,data) ;
uiresume(obj) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
% use keypress to exit
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
rising-turtle/slam_matlab-master
|
gaussianss.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.19/sift/gaussianss.m
| 7,935 |
utf_8
|
ea953b78ba9dcf80cd10b1f4c599408e
|
function SS = gaussianss(I,sigman,O,S,omin,smin,smax,sigma0)
% GAUSSIANSS
% SS = GAUSSIANSS(I,SIGMAN,O,S,OMIN,SMIN,SMAX,SIGMA0) returns the
% Gaussian scale space of image I. Image I is assumed to be
% pre-smoothed at level SIGMAN. O,S,OMIN,SMIN,SMAX,SIGMA0 are the
% parameters of the scale space as explained in PDF:SIFT.USER.SS.
%
% See also DIFFSS(), PDF:SIFT.USER.SS.
% History
% 4-15-2006 Fixed some comments
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(nargin < 6)
error('Six arguments are required.') ;
end
if(~isreal(I) || ndims(I) > 2)
error('I must be a real two dimensional matrix') ;
end
if(smin >= smax)
error('smin must be greather or equal to smax') ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
% Scale multiplicative step
k = 2^(1/S) ;
% Lowe's convention: the scale (o,s)=(0,-1) has standard deviation
% 1.6 (was it variance?)
if(nargin < 7)
sigma0 = 1.6 * k ;
end
dsigma0 = sigma0 * sqrt(1 - 1/k^2) ; % Scale step factor
sigman = 0.5 ; % Nominal smoothing of the image
% Scale space structure
SS.O = O ;
SS.S = S ;
SS.sigma0 = sigma0 ;
SS.omin = omin ;
SS.smin = smin ;
SS.smax = smax ;
% If mino < 0, multiply the size of the image.
% (The rest of the code is consistent with this.)
if omin < 0
for o=1:-omin
I = doubleSize(I) ;
end
elseif omin > 0
for o=1:omin
I = halveSize(I) ;
end
end
[M,N] = size(I) ;
% Index offset
so = -smin+1 ;
% --------------------------------------------------------------------
% First octave
% --------------------------------------------------------------------
%
% The first level of the first octave has scale index (o,s) =
% (omin,smin) and scale coordinate
%
% sigma(omin,smin) = sigma0 2^omin k^smin
%
% The input image I is at nominal scale sigman. Thus in order to get
% the first level of the pyramid we need to apply a smoothing of
%
% sqrt( (sigma0 2^omin k^smin)^2 - sigman^2 ).
%
% As we have pre-scaled the image omin octaves (up or down,
% depending on the sign of omin), we need to correct this value
% by dividing by 2^omin, getting
%e
% sqrt( (sigma0 k^smin)^2 - (sigman/2^omin)^2 )
%
if(sigma0 * 2^omin * k^smin < sigman)
warning('The nominal smoothing exceeds the lowest level of the scale space.') ;
end
SS.octave{1} = zeros(M,N,smax-smin+1) ;
SS.octave{1}(:,:,1) = imsmooth(I, ...
sqrt((sigma0*k^smin)^2 - (sigman/2^omin)^2)) ;
for s=smin+1:smax
% Here we go from (omin,s-1) to (omin,s). The extra smoothing
% standard deviation is
%
% (sigma0 2^omin 2^(s/S) )^2 - (simga0 2^omin 2^(s/S-1/S) )^2
%
% Aftred dividing by 2^omin (to take into account the fact
% that the image has been pre-scaled omin octaves), the
% standard deviation of the smoothing kernel is
%
% dsigma = sigma0 k^s sqrt(1-1/k^2)
%
dsigma = k^s * dsigma0 ;
SS.octave{1}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{1}(:,:,s-1 +so)...
), dsigma ) ;
end
% --------------------------------------------------------------------
% Other octaves
% --------------------------------------------------------------------
for o=2:O
% We need to initialize the first level of octave (o,smin) from
% the closest possible level of the previous octave. A level (o,s)
% in this octave corrsponds to the level (o-1,s+S) in the previous
% octave. In particular, the level (o,smin) correspnds to
% (o-1,smin+S). However (o-1,smin+S) might not be among the levels
% (o-1,smin), ..., (o-1,smax) that we have previously computed.
% The closest pick is
%
% / smin+S if smin+S <= smax
% (o-1,sbest) , sbest = |
% \ smax if smin+S > smax
%
% The amount of extra smoothing we need to apply is then given by
%
% ( sigma0 2^o 2^(smin/S) )^2 - ( sigma0 2^o 2^(sbest/S - 1) )^2
%
% As usual, we divide by 2^o to cancel out the effect of the
% downsampling and we get
%
% ( sigma 0 k^smin )^2 - ( sigma0 2^o k^(sbest - S) )^2
%
sbest = min(smin + S, smax) ;
TMP = halveSize(squeeze(SS.octave{o-1}(:,:,sbest+so))) ;
target_sigma = sigma0 * k^smin ;
prev_sigma = sigma0 * k^(sbest - S) ;
if(target_sigma > prev_sigma)
TMP = imsmooth(TMP, sqrt(target_sigma^2 - prev_sigma^2) ) ;
end
[M,N] = size(TMP) ;
SS.octave{o} = zeros(M,N,smax-smin+1) ;
SS.octave{o}(:,:,1) = TMP ;
for s=smin+1:smax
% The other levels are determined as above for the first octave.
dsigma = k^s * dsigma0 ;
SS.octave{o}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{o}(:,:,s-1 +so)...
), dsigma) ;
end
end
% -------------------------------------------------------------------------
% Auxiliary functions
% -------------------------------------------------------------------------
function J = doubleSize(I)
[M,N]=size(I) ;
J = zeros(2*M,2*N) ;
J(1:2:end,1:2:end) = I ;
J(2:2:end-1,2:2:end-1) = ...
0.25*I(1:end-1,1:end-1) + ...
0.25*I(2:end,1:end-1) + ...
0.25*I(1:end-1,2:end) + ...
0.25*I(2:end,2:end) ;
J(2:2:end-1,1:2:end) = ...
0.5*I(1:end-1,:) + ...
0.5*I(2:end,:) ;
J(1:2:end,2:2:end-1) = ...
0.5*I(:,1:end-1) + ...
0.5*I(:,2:end) ;
function J = halveSize(I)
J=I(1:2:end,1:2:end) ;
%[M,N] = size(I) ;
%m=floor((M+1)/2) ;
%n=floor((N+1)/2) ;
%J = I(:,1:2:2*n) + I(:,2:2:2*n+1) ;
%J = 0.25*(J(1:2:2*m,:)+J(2:2:2*m+1,:)) ;
|
github
|
rising-turtle/slam_matlab-master
|
plotsiftdescriptor.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.19/sift/plotsiftdescriptor.m
| 5,461 |
utf_8
|
4159397cc60b624656bb3372023a43e9
|
function h=plotsiftdescriptor(d,f)
% PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptors D, stored as
% columns of the matrix D. D has the same format used by SIFT().
%
% 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 SIFT().
%
% H=PLOTSIFTDESCRIPTOR(...) returns the handle H to the line drawing
% representing the descriptors.
%
% REMARK. Currently the function supports only descriptors with 4x4
% spatial bins and 8 orientation bins (Lowe's default.)
%
% See also PLOTSIFTFRAME(), PLOTMATCHES(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
lowe_compatible = 1 ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= 128)
error('D should be a 128xK matrix (only standard descriptors accepted)') ;
end
if nargin > 1
if(size(f,1) ~= 4)
error('F should be a 4xK matrix');
end
if(size(f,2) ~= size(f,2))
error('D and F must have the same number of columns') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2
f = repmat([0;0;1;0],1,K) ;
end
maginf = 3.0 ;
NBP=4 ;
NBO=8 ;
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
SBP = maginf * f(3,k) ;
th=f(4,k) ;
c=cos(th) ;
s=sin(th) ;
[x,y] = render_descr(d(:,k)) ;
xall = [xall SBP*(c*x-s*y)+f(1,k)+1] ;
yall = [yall SBP*(s*x+c*y)+f(2,k)+1] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
% Helper functions
% --------------------------------------------------------------------
% Renders a single descriptor
function [x,y] = render_descr( d )
lowe_compatible=1;
NBP=4 ;
NBO=8 ;
[x,y] = meshgrid(-NBP/2:NBP/2,-NBP/2:NBP/2) ;
% Rescale d so that the biggest peak fits inside the bin diagram
d = 0.4 * d / max(d(:)) ;
% We have NBP*NBP 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 swap the order of the bin diagrams because they are stored row
% major into the descriptor (Lowe's convention that we follow.)
xc = xc' ;
yc = yc' ;
% Each bin contains a star with eight tips
xc = repmat(xc(:)',NBO,1) ;
yc = repmat(yc(:)',NBO,1) ;
% Do the stars
th=linspace(0,2*pi,NBO+1) ;
th=th(1:end-1) ;
if lowe_compatible
xd = repmat(cos(-th), 1, NBP*NBP ) ;
yd = repmat(sin(-th), 1, NBP*NBP ) ;
else
xd = repmat(cos(th), 1, NBP*NBP ) ;
yd = repmat(sin(th), 1, NBP*NBP ) ;
end
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,NBP^2*NBO) ;
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,NBP+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
|
rising-turtle/slam_matlab-master
|
plotmatches.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.19-bin/sift/plotmatches.m
| 10,144 |
utf_8
|
4d7daa0d3265f0885ebc7f3310a47fc1
|
function h=plotmatches(I1,I2,P1,P2,matches,varargin)
% PLOTMATCHES Plot keypoint matches
% PLOTMATCHES(I1,I2,P1,P2,MATCHES) plots the two images I1 and I2
% and lines connecting the frames (keypoints) P1 and P2 as specified
% by MATCHES.
%
% P1 and P2 specify two sets of frames, one per column. The first
% two elements of each column specify the X,Y coordinates of the
% corresponding frame. Any other element is ignored.
%
% MATCHES specifies a set of matches, one per column. The two
% elementes of each column are two indexes in the sets P1 and P2
% respectively.
%
% The images I1 and I2 might be either both grayscale or both color
% and must have DOUBLE storage class. If they are color the range
% must be normalized in [0,1].
%
% The function accepts the following option-value pairs:
%
% 'Stacking' ['h']
% Stacking of images: horizontal ['h'], vertical ['v'], diagonal
% ['h'], overlap ['o']
%
% 'Interactive' [0]
% If set to 1, starts the interactive session. In this mode the
% program lets the user browse the matches by moving the mouse:
% Click to select and highlight a match; press any key to end.
% If set to a value greater than 1, the feature matches are not
% drawn at all (useful for cluttered scenes).
%
% See also PLOTSIFTDESCRIPTOR(), PLOTSIFTFRAME(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
stack='h' ;
interactive=0 ;
only_interactive=0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'stacking'
stack=varargin{k+1} ;
case 'interactive'
interactive=varargin{k+1};
otherwise
error(['[Unknown option ''', varargin{k}, '''.']) ;
end
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
[M1,N1,K1]=size(I1) ;
[M2,N2,K2]=size(I2) ;
switch stack
case 'h'
N3=N1+N2 ;
M3=max(M1,M2) ;
oj=N1 ;
oi=0 ;
case 'v'
M3=M1+M2 ;
N3=max(N1,N2) ;
oj=0 ;
oi=M1 ;
case 'd'
M3=M1+M2 ;
N3=N1+N2 ;
oj=N1 ;
oi=M1 ;
case 'o'
M3=max(M1,M2) ;
N3=max(N1,N2) ;
oj=0;
oi=0;
otherwise
error(['Unkown stacking type '''], stack, ['''.']) ;
end
% Combine the two images. In most cases just place one image next to
% the other. If the stacking is 'o', however, combine the two images
% linearly.
I=zeros(M3,N3,K1) ;
if stack ~= 'o'
I(1:M1,1:N1,:) = I1 ;
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
else
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
I(1:M1,1:N1,:) = I(1:M1,1:N1,:) + I1 ;
I(1:min(M1,M2),1:min(N1,N2),:) = 0.5 * I(1:min(M1,M2),1:min(N1,N2),:) ;
end
axes('Position', [0 0 1 1]) ;
imagesc(I) ; colormap gray ; hold on ; axis image ; axis off ;
K = size(matches, 2) ;
nans = NaN * ones(1,K) ;
x = [ P1(1,matches(1,:)) ; P2(1,matches(2,:))+oj ; nans ] ;
y = [ P1(2,matches(1,:)) ; P2(2,matches(2,:))+oi ; nans ] ;
% if interactive > 1 we do not drive lines, but just points.
if(interactive > 1)
h = plot(x(:),y(:),'g.') ;
else
h = line(x(:)', y(:)') ;
end
set(h,'Marker','.','Color','g') ;
% --------------------------------------------------------------------
% Interactive
% --------------------------------------------------------------------
if(~interactive), return ; end
sel1 = unique(matches(1,:)) ;
sel2 = unique(matches(2,:)) ;
K1 = length(sel1) ; %size(P1,2) ;
K2 = length(sel2) ; %size(P2,2) ;
X = [ P1(1,sel1) P2(1,sel2)+oj ;
P1(2,sel1) P2(2,sel2)+oi ; ] ;
fig = gcf ;
is_hold = ishold ;
hold on ;
% save the handlers for later to restore
dhandler = get(fig,'WindowButtonDownFcn') ;
uhandler = get(fig,'WindowButtonUpFcn') ;
mhandler = get(fig,'WindowButtonMotionFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'KeyPressFcn', @key_handler) ;
set(fig,'WindowButtonDownFcn',@click_down_handler) ;
set(fig,'WindowButtonUpFcn', @click_up_handler) ;
set(fig,'Pointer','crosshair') ;
data.exit = 0 ; % signal exit to the interactive mode
data.selected = [] ; % currently selected feature
data.X = X ; % feature anchors
highlighted = [] ; % currently highlighted feature
hh = [] ; % hook of the highlight plot
guidata(fig,data) ;
while ~ data.exit
uiwait(fig) ;
data = guidata(fig) ;
if(any(size(highlighted) ~= size(data.selected)) || ...
any(highlighted ~= data.selected) )
highlighted = data.selected ;
% delete previous highlight
if( ~isempty(hh) )
delete(hh) ;
end
hh=[] ;
% each selected feature uses its own color
c=1 ;
colors=[1.0 0.0 0.0 ;
0.0 1.0 0.0 ;
0.0 0.0 1.0 ;
1.0 1.0 0.0 ;
0.0 1.0 1.0 ;
1.0 0.0 1.0 ] ;
% more than one feature might be seleted at one time...
for this=highlighted
% find matches
if( this <= K1 )
sel=find(matches(1,:)== sel1(this)) ;
else
sel=find(matches(2,:)== sel2(this-K1)) ;
end
K=length(sel) ;
% plot matches
x = [ P1(1,matches(1,sel)) ; P2(1,matches(2,sel))+oj ; nan*ones(1,K) ] ;
y = [ P1(2,matches(1,sel)) ; P2(2,matches(2,sel))+oi ; nan*ones(1,K) ] ;
hh = [hh line(x(:)', y(:)',...
'Marker','*',...
'Color',colors(c,:),...
'LineWidth',3)];
if( size(P1,1) == 4 )
f1 = unique(P1(:,matches(1,sel))','rows')' ;
hp=plotsiftframe(f1);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
if( size(P2,1) == 4 )
f2 = unique(P2(:,matches(2,sel))','rows')' ;
f2(1,:)=f2(1,:)+oj ;
f2(2,:)=f2(2,:)+oi ;
hp=plotsiftframe(f2);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
c=c+1 ;
end
drawnow ;
end
end
if( ~isempty(hh) )
delete(hh) ;
end
if ~is_hold
hold off ;
end
set(fig,'WindowButtonDownFcn', dhandler) ;
set(fig,'WindowButtonUpFcn', uhandler) ;
set(fig,'WindowButtonMotionFcn',mhandler) ;
set(fig,'KeyPressFcn', khandler) ;
set(fig,'Pointer', pointer ) ;
% ====================================================================
function data=selection_helper(data)
% --------------------------------------------------------------------
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
d = (data.X(1,:) - P(1)).^2 + (data.X(2,:) - P(2)).^2 ;
dmin=min(d) ;
idx=find(d==dmin) ;
data.selected = idx ;
% ====================================================================
function click_down_handler(obj,event)
% --------------------------------------------------------------------
% select a feature and change motion handler for dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
data.mhandler = get(fig,'WindowButtonMotionFcn') ;
set(fig,'WindowButtonMotionFcn',@motion_handler) ;
data = selection_helper(data) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function click_up_handler(obj,event)
% --------------------------------------------------------------------
% stop dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
set(fig,'WindowButtonMotionFcn',data.mhandler) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function motion_handler(obj,event)
% --------------------------------------------------------------------
% select features while dragging
data = guidata(obj) ;
data = selection_helper(data);
guidata(obj,data) ;
uiresume(obj) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
% use keypress to exit
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
rising-turtle/slam_matlab-master
|
gaussianss.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.19-bin/sift/gaussianss.m
| 7,935 |
utf_8
|
ea953b78ba9dcf80cd10b1f4c599408e
|
function SS = gaussianss(I,sigman,O,S,omin,smin,smax,sigma0)
% GAUSSIANSS
% SS = GAUSSIANSS(I,SIGMAN,O,S,OMIN,SMIN,SMAX,SIGMA0) returns the
% Gaussian scale space of image I. Image I is assumed to be
% pre-smoothed at level SIGMAN. O,S,OMIN,SMIN,SMAX,SIGMA0 are the
% parameters of the scale space as explained in PDF:SIFT.USER.SS.
%
% See also DIFFSS(), PDF:SIFT.USER.SS.
% History
% 4-15-2006 Fixed some comments
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(nargin < 6)
error('Six arguments are required.') ;
end
if(~isreal(I) || ndims(I) > 2)
error('I must be a real two dimensional matrix') ;
end
if(smin >= smax)
error('smin must be greather or equal to smax') ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
% Scale multiplicative step
k = 2^(1/S) ;
% Lowe's convention: the scale (o,s)=(0,-1) has standard deviation
% 1.6 (was it variance?)
if(nargin < 7)
sigma0 = 1.6 * k ;
end
dsigma0 = sigma0 * sqrt(1 - 1/k^2) ; % Scale step factor
sigman = 0.5 ; % Nominal smoothing of the image
% Scale space structure
SS.O = O ;
SS.S = S ;
SS.sigma0 = sigma0 ;
SS.omin = omin ;
SS.smin = smin ;
SS.smax = smax ;
% If mino < 0, multiply the size of the image.
% (The rest of the code is consistent with this.)
if omin < 0
for o=1:-omin
I = doubleSize(I) ;
end
elseif omin > 0
for o=1:omin
I = halveSize(I) ;
end
end
[M,N] = size(I) ;
% Index offset
so = -smin+1 ;
% --------------------------------------------------------------------
% First octave
% --------------------------------------------------------------------
%
% The first level of the first octave has scale index (o,s) =
% (omin,smin) and scale coordinate
%
% sigma(omin,smin) = sigma0 2^omin k^smin
%
% The input image I is at nominal scale sigman. Thus in order to get
% the first level of the pyramid we need to apply a smoothing of
%
% sqrt( (sigma0 2^omin k^smin)^2 - sigman^2 ).
%
% As we have pre-scaled the image omin octaves (up or down,
% depending on the sign of omin), we need to correct this value
% by dividing by 2^omin, getting
%e
% sqrt( (sigma0 k^smin)^2 - (sigman/2^omin)^2 )
%
if(sigma0 * 2^omin * k^smin < sigman)
warning('The nominal smoothing exceeds the lowest level of the scale space.') ;
end
SS.octave{1} = zeros(M,N,smax-smin+1) ;
SS.octave{1}(:,:,1) = imsmooth(I, ...
sqrt((sigma0*k^smin)^2 - (sigman/2^omin)^2)) ;
for s=smin+1:smax
% Here we go from (omin,s-1) to (omin,s). The extra smoothing
% standard deviation is
%
% (sigma0 2^omin 2^(s/S) )^2 - (simga0 2^omin 2^(s/S-1/S) )^2
%
% Aftred dividing by 2^omin (to take into account the fact
% that the image has been pre-scaled omin octaves), the
% standard deviation of the smoothing kernel is
%
% dsigma = sigma0 k^s sqrt(1-1/k^2)
%
dsigma = k^s * dsigma0 ;
SS.octave{1}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{1}(:,:,s-1 +so)...
), dsigma ) ;
end
% --------------------------------------------------------------------
% Other octaves
% --------------------------------------------------------------------
for o=2:O
% We need to initialize the first level of octave (o,smin) from
% the closest possible level of the previous octave. A level (o,s)
% in this octave corrsponds to the level (o-1,s+S) in the previous
% octave. In particular, the level (o,smin) correspnds to
% (o-1,smin+S). However (o-1,smin+S) might not be among the levels
% (o-1,smin), ..., (o-1,smax) that we have previously computed.
% The closest pick is
%
% / smin+S if smin+S <= smax
% (o-1,sbest) , sbest = |
% \ smax if smin+S > smax
%
% The amount of extra smoothing we need to apply is then given by
%
% ( sigma0 2^o 2^(smin/S) )^2 - ( sigma0 2^o 2^(sbest/S - 1) )^2
%
% As usual, we divide by 2^o to cancel out the effect of the
% downsampling and we get
%
% ( sigma 0 k^smin )^2 - ( sigma0 2^o k^(sbest - S) )^2
%
sbest = min(smin + S, smax) ;
TMP = halveSize(squeeze(SS.octave{o-1}(:,:,sbest+so))) ;
target_sigma = sigma0 * k^smin ;
prev_sigma = sigma0 * k^(sbest - S) ;
if(target_sigma > prev_sigma)
TMP = imsmooth(TMP, sqrt(target_sigma^2 - prev_sigma^2) ) ;
end
[M,N] = size(TMP) ;
SS.octave{o} = zeros(M,N,smax-smin+1) ;
SS.octave{o}(:,:,1) = TMP ;
for s=smin+1:smax
% The other levels are determined as above for the first octave.
dsigma = k^s * dsigma0 ;
SS.octave{o}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{o}(:,:,s-1 +so)...
), dsigma) ;
end
end
% -------------------------------------------------------------------------
% Auxiliary functions
% -------------------------------------------------------------------------
function J = doubleSize(I)
[M,N]=size(I) ;
J = zeros(2*M,2*N) ;
J(1:2:end,1:2:end) = I ;
J(2:2:end-1,2:2:end-1) = ...
0.25*I(1:end-1,1:end-1) + ...
0.25*I(2:end,1:end-1) + ...
0.25*I(1:end-1,2:end) + ...
0.25*I(2:end,2:end) ;
J(2:2:end-1,1:2:end) = ...
0.5*I(1:end-1,:) + ...
0.5*I(2:end,:) ;
J(1:2:end,2:2:end-1) = ...
0.5*I(:,1:end-1) + ...
0.5*I(:,2:end) ;
function J = halveSize(I)
J=I(1:2:end,1:2:end) ;
%[M,N] = size(I) ;
%m=floor((M+1)/2) ;
%n=floor((N+1)/2) ;
%J = I(:,1:2:2*n) + I(:,2:2:2*n+1) ;
%J = 0.25*(J(1:2:2*m,:)+J(2:2:2*m+1,:)) ;
|
github
|
rising-turtle/slam_matlab-master
|
plotsiftdescriptor.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.19-bin/sift/plotsiftdescriptor.m
| 5,461 |
utf_8
|
4159397cc60b624656bb3372023a43e9
|
function h=plotsiftdescriptor(d,f)
% PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptors D, stored as
% columns of the matrix D. D has the same format used by SIFT().
%
% 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 SIFT().
%
% H=PLOTSIFTDESCRIPTOR(...) returns the handle H to the line drawing
% representing the descriptors.
%
% REMARK. Currently the function supports only descriptors with 4x4
% spatial bins and 8 orientation bins (Lowe's default.)
%
% See also PLOTSIFTFRAME(), PLOTMATCHES(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
lowe_compatible = 1 ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= 128)
error('D should be a 128xK matrix (only standard descriptors accepted)') ;
end
if nargin > 1
if(size(f,1) ~= 4)
error('F should be a 4xK matrix');
end
if(size(f,2) ~= size(f,2))
error('D and F must have the same number of columns') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2
f = repmat([0;0;1;0],1,K) ;
end
maginf = 3.0 ;
NBP=4 ;
NBO=8 ;
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
SBP = maginf * f(3,k) ;
th=f(4,k) ;
c=cos(th) ;
s=sin(th) ;
[x,y] = render_descr(d(:,k)) ;
xall = [xall SBP*(c*x-s*y)+f(1,k)+1] ;
yall = [yall SBP*(s*x+c*y)+f(2,k)+1] ;
end
h=line(xall,yall) ;
% --------------------------------------------------------------------
% Helper functions
% --------------------------------------------------------------------
% Renders a single descriptor
function [x,y] = render_descr( d )
lowe_compatible=1;
NBP=4 ;
NBO=8 ;
[x,y] = meshgrid(-NBP/2:NBP/2,-NBP/2:NBP/2) ;
% Rescale d so that the biggest peak fits inside the bin diagram
d = 0.4 * d / max(d(:)) ;
% We have NBP*NBP 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 swap the order of the bin diagrams because they are stored row
% major into the descriptor (Lowe's convention that we follow.)
xc = xc' ;
yc = yc' ;
% Each bin contains a star with eight tips
xc = repmat(xc(:)',NBO,1) ;
yc = repmat(yc(:)',NBO,1) ;
% Do the stars
th=linspace(0,2*pi,NBO+1) ;
th=th(1:end-1) ;
if lowe_compatible
xd = repmat(cos(-th), 1, NBP*NBP ) ;
yd = repmat(sin(-th), 1, NBP*NBP ) ;
else
xd = repmat(cos(th), 1, NBP*NBP ) ;
yd = repmat(sin(th), 1, NBP*NBP ) ;
end
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,NBP^2*NBO) ;
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,NBP+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
|
rising-turtle/slam_matlab-master
|
plotmatches.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.17/sift/plotmatches.m
| 10,221 |
utf_8
|
a701b7d74819dd725219aa884d6f7f18
|
function h=plotmatches(I1,I2,P1,P2,matches,varargin)
% PLOTMATCHES Plot keypoint matches
% PLOTMATCHES(I1,I2,P1,P2,MATCHES) plots the two images I1 and I2
% and lines connecting the frames (keypoints) P1 and P2 as specified
% by MATCHES.
%
% P1 and P2 specify two sets of frames, one per column. The first
% two elements of each column specify the X,Y coordinates of the
% corresponding frame. Any other element is ignored.
%
% MATCHES specifies a set of matches, one per column. The two
% elementes of each column are two indexes in the sets P1 and P2
% respectively.
%
% The images I1 and I2 might be either both grayscale or both color
% and must have DOUBLE storage class. If they are color the range
% must be normalized in [0,1].
%
% The function accepts the following option-value pairs:
%
% 'Stacking' ['h']
% Stacking of images: horizontal ['h'], vertical ['v'], diagonal
% ['h'], overlap ['o']
%
% 'Interactive' [0]
% If set to 1, starts the interactive session. In this mode the
% program lets the user browse the matches by moving the mouse:
% Click to select and highlight a match; press any key to end.
% If set to a value greater than 1, the feature matches are not
% drawn at all (useful for cluttered scenes).
%
% See also PLOTSIFTDESCRIPTOR(), PLOTSIFTFRAME(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
stack='h' ;
interactive=0 ;
only_interactive=0 ;
for k=1:2:length(varargin)
switch lower(varargin{k})
case 'stacking'
stack=varargin{k+1} ;
case 'interactive'
interactive=varargin{k+1};
otherwise
error(['[Unknown option ''', varargin{k}, '''.']) ;
end
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
[M1,N1,K1]=size(I1) ;
[M2,N2,K2]=size(I2) ;
switch stack
case 'h'
N3=N1+N2 ;
M3=max(M1,M2) ;
oj=N1 ;
oi=0 ;
case 'v'
M3=M1+M2 ;
N3=max(N1,N2) ;
oj=0 ;
oi=M1 ;
case 'd'
M3=M1+M2 ;
N3=N1+N2 ;
oj=N1 ;
oi=M1 ;
case 'o'
M3=max(M1,M2) ;
N3=max(N1,N2) ;
oj=0;
oi=0;
otherwise
error(['Unkown stacking type '''], stack, ['''.']) ;
end
% Combine the two images. In most cases just place one image next to
% the other. If the stacking is 'o', however, combine the two images
% linearly.
I=zeros(M3,N3,K1) ;
if stack ~= 'o'
I(1:M1,1:N1,:) = I1 ;
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
else
I(oi+(1:M2),oj+(1:N2),:) = I2 ;
I(1:M1,1:N1,:) = I(1:M1,1:N1,:) + I1 ;
I(1:min(M1,M2),1:min(N1,N2),:) = 0.5 * I(1:min(M1,M2),1:min(N1,N2),:) ;
end
axes('Position', [0 0 1 1]) ;
imagesc(I) ; colormap gray ; hold on ; axis image ; axis off ;
K = size(matches, 2) ;
nans = NaN * ones(1,K) ;
x = [ P1(1,matches(1,:)) ; P2(1,matches(2,:))+oj ; nans ] ;
y = [ P1(2,matches(1,:)) ; P2(2,matches(2,:))+oi ; nans ] ;
% if interactive > 1 we do not drive lines, but just points.
if(interactive > 1)
h = plot(x(:),y(:),'g.') ;
else
h = line(x(:)', y(:)') ;
end
set(h,'Marker','.','Color','g') ;
% --------------------------------------------------------------------
% Interactive
% --------------------------------------------------------------------
if(~interactive), return ; end
sel1 = unique(matches(1,:)) ;
sel2 = unique(matches(2,:)) ;
K1 = length(sel1) ; %size(P1,2) ;
K2 = length(sel2) ; %size(P2,2) ;
X = [ P1(1,sel1) P2(1,sel2)+oj ;
P1(2,sel1) P2(2,sel2)+oi ; ] ;
fig = gcf ;
is_hold = ishold ;
hold on ;
% save the handlers for later to restore
dhandler = get(fig,'WindowButtonDownFcn') ;
uhandler = get(fig,'WindowButtonUpFcn') ;
mhandler = get(fig,'WindowButtonMotionFcn') ;
khandler = get(fig,'KeyPressFcn') ;
pointer = get(fig,'Pointer') ;
set(fig,'KeyPressFcn', @key_handler) ;
set(fig,'WindowButtonDownFcn',@click_down_handler) ;
set(fig,'WindowButtonUpFcn', @click_up_handler) ;
set(fig,'Pointer','crosshair') ;
data.exit = 0 ; % signal exit to the interactive mode
data.selected = [] ; % currently selected feature
data.X = X ; % feature anchors
highlighted = [] ; % currently highlighted feature
hh = [] ; % hook of the highlight plot
guidata(fig,data) ;
while ~ data.exit
uiwait(fig) ;
data = guidata(fig) ;
if(any(size(highlighted) ~= size(data.selected)) || ...
any(highlighted ~= data.selected) )
highlighted = data.selected ;
% delete previous highlight
if( ~isempty(hh) )
delete(hh) ;
end
hh=[] ;
% each selected feature uses its own color
c=1 ;
colors=[1.0 0.0 0.0 ;
0.0 1.0 0.0 ;
0.0 0.0 1.0 ;
1.0 1.0 0.0 ;
0.0 1.0 1.0 ;
1.0 0.0 1.0 ] ;
% more than one feature might be seleted at one time...
for this=highlighted
% find matches
if( this <= K1 )
sel=find(matches(1,:)== sel1(this)) ;
else
sel=find(matches(2,:)== sel2(this-K1)) ;
end
K=length(sel) ;
% plot matches
x = [ P1(1,matches(1,sel)) ; P2(1,matches(2,sel))+oj ; nan*ones(1,K) ] ;
y = [ P1(2,matches(1,sel)) ; P2(2,matches(2,sel))+oi ; nan*ones(1,K) ] ;
hh = [hh line(x(:)', y(:)',...
'Marker','*',...
'Color',colors(c,:),...
'LineWidth',3)];
if( size(P1,1) == 4 )
f1 = unique(P1(:,matches(1,sel))','rows')' ;
hp=plotsiftframe(f1);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
if( size(P2,1) == 4 )
f2 = unique(P2(:,matches(2,sel))','rows')' ;
f2(1,:)=f2(1,:)+oj ;
f2(2,:)=f2(2,:)+oi ;
hp=plotsiftframe(f2);
set(hp,'Color',colors(c,:)) ;
hh=[hh hp] ;
end
c=c+1 ;
end
drawnow ;
end
end
if( ~isempty(hh) )
delete(hh) ;
end
if ~is_hold
hold off ;
end
set(fig,'WindowButtonDownFcn', dhandler) ;
set(fig,'WindowButtonUpFcn', uhandler) ;
set(fig,'WindowButtonMotionFcn',mhandler) ;
set(fig,'KeyPressFcn', khandler) ;
set(fig,'Pointer', pointer ) ;
% ====================================================================
function data=selection_helper(data)
% --------------------------------------------------------------------
P = get(gca, 'CurrentPoint') ;
P = [P(1,1); P(1,2)] ;
d = (data.X(1,:) - P(1)).^2 + (data.X(2,:) - P(2)).^2 ;
dmin=min(d) ;
idx=find(d==dmin) ;
data.selected = idx ;
% ====================================================================
function click_down_handler(obj,event)
% --------------------------------------------------------------------
% select a feature and change motion handler for dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
data.mhandler = get(fig,'WindowButtonMotionFcn') ;
set(fig,'WindowButtonMotionFcn',@motion_handler) ;
data = selection_helper(data) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function click_up_handler(obj,event)
% --------------------------------------------------------------------
% stop dragging
[obj,fig]=gcbo ;
data = guidata(fig) ;
set(fig,'WindowButtonMotionFcn',data.mhandler) ;
guidata(fig,data) ;
uiresume(obj) ;
% ====================================================================
function motion_handler(obj,event)
% --------------------------------------------------------------------
% select features while dragging
data = guidata(obj) ;
data = selection_helper(data);
guidata(obj,data) ;
uiresume(obj) ;
% ====================================================================
function key_handler(obj,event)
% --------------------------------------------------------------------
% use keypress to exit
data = guidata(gcbo) ;
data.exit = 1 ;
guidata(obj,data) ;
uiresume(gcbo) ;
|
github
|
rising-turtle/slam_matlab-master
|
gaussianss.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.17/sift/gaussianss.m
| 7,995 |
utf_8
|
5ddc73695f19ef5411d4e19a24f9a860
|
function SS = gaussianss(I,sigman,O,S,omin,smin,smax,sigma0)
% GAUSSIANSS
% SS = GAUSSIANSS(I,SIGMAN,O,S,OMIN,SMIN,SMAX,SIGMA0) returns the
% Gaussian scale space of image I. Image I is assumed to be
% pre-smoothed at level SIGMAN. O,S,OMIN,SMIN,SMAX,SIGMA0 are the
% parameters of the scale space as explained in PDF:SIFT.USER.SS.
%
% See also DIFFSS(), PDF:SIFT.USER.SS.
% History
% 4-15-2006 Fixed some comments
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(nargin < 6)
error('Six arguments are required.') ;
end
if(~isreal(I) || ndims(I) > 2)
error('I must be a real two dimensional matrix') ;
end
if(smin >= smax)
error('smin must be greather or equal to smax') ;
end
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
% Scale multiplicative step
k = 2^(1/S) ;
% Lowe's convention: the scale (o,s)=(0,-1) has standard deviation
% 1.6 (was it variance?)
if(nargin < 7)
sigma0 = 1.6 * k ;
end
dsigma0 = sigma0 * sqrt(1 - 1/k^2) ; % Scale step factor
sigman = 0.5 ; % Nominal smoothing of the image
% Scale space structure
SS.O = O ;
SS.S = S ;
SS.sigma0 = sigma0 ;
SS.omin = omin ;
SS.smin = smin ;
SS.smax = smax ;
% If mino < 0, multiply the size of the image.
% (The rest of the code is consistent with this.)
if omin < 0
for o=1:-omin
I = doubleSize(I) ;
end
elseif omin > 0
for o=1:omin
I = halveSize(I) ;
end
end
[M,N] = size(I) ;
% Index offset
so = -smin+1 ;
% --------------------------------------------------------------------
% First octave
% --------------------------------------------------------------------
%
% The first level of the first octave has scale index (o,s) =
% (omin,smin) and scale coordinate
%
% sigma(omin,smin) = sigma0 2^omin k^smin
%
% The input image I is at nominal scale sigman. Thus in order to get
% the first level of the pyramid we need to apply a smoothing of
%
% sqrt( (sigma0 2^omin k^smin)^2 - sigman^2 ).
%
% As we have pre-scaled the image omin octaves (up or down,
% depending on the sign of omin), we need to correct this value
% by dividing by 2^omin, getting
%e
% sqrt( (sigma0 k^smin)^2 - (sigman/2^omin)^2 )
%
if(sigma0 * 2^omin * k^smin < sigman)
warning('The nominal smoothing exceeds the lowest level of the scale space.') ;
end
SS.octave{1} = zeros(M,N,smax-smin+1) ;
SS.octave{1}(:,:,1) = imsmooth(I, ...
sqrt((sigma0*k^smin)^2 - (sigman/2^omin)^2)) ;
for s=smin+1:smax
% Here we go from (omin,s-1) to (omin,s). The extra smoothing
% standard deviation is
%
% (sigma0 2^omin 2^(s/S) )^2 - (simga0 2^omin 2^(s/S-1/S) )^2
%
% Aftred dividing by 2^omin (to take into account the fact
% that the image has been pre-scaled omin octaves), the
% standard deviation of the smoothing kernel is
%
% dsigma = sigma0 k^s sqrt(1-1/k^2)
%
dsigma = k^s * dsigma0 ;
SS.octave{1}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{1}(:,:,s-1 +so)...
), dsigma ) ;
end
% --------------------------------------------------------------------
% Other octaves
% --------------------------------------------------------------------
for o=2:O
% We need to initialize the first level of octave (o,smin) from
% the closest possible level of the previous octave. A level (o,s)
% in this octave corrsponds to the level (o-1,s+S) in the previous
% octave. In particular, the level (o,smin) correspnds to
% (o-1,smin+S). However (o-1,smin+S) might not be among the levels
% (o-1,smin), ..., (o-1,smax) that we have previously computed.
% The closest pick is
%
% / smin+S if smin+S <= smax
% (o-1,sbest) , sbest = |
% \ smax if smin+S > smax
%
% The amount of extra smoothing we need to apply is then given by
%
% ( sigma0 2^o 2^(smin/S) )^2 - ( sigma0 2^o 2^(sbest/S - 1) )^2
%
% As usual, we divide by 2^o to cancel out the effect of the
% downsampling and we get
%
% ( sigma 0 k^smin )^2 - ( sigma0 2^o k^(sbest - S) )^2
%
sbest = min(smin + S, smax) ;
TMP = halveSize(squeeze(SS.octave{o-1}(:,:,sbest+so))) ;
target_sigma = sigma0 * k^smin ;
prev_sigma = sigma0 * k^(sbest - S) ;
if(target_sigma > prev_sigma)
TMP = imsmooth(TMP, sqrt(target_sigma^2 - prev_sigma^2) ) ;
end
[M,N] = size(TMP) ;
SS.octave{o} = zeros(M,N,smax-smin+1) ;
SS.octave{o}(:,:,1) = TMP ;
for s=smin+1:smax
% The other levels are determined as above for the first octave.
dsigma = k^s * dsigma0 ;
SS.octave{o}(:,:,s +so) = ...
imsmooth(squeeze(...
SS.octave{o}(:,:,s-1 +so)...
), dsigma) ;
end
end
% -------------------------------------------------------------------------
% Auxiliary functions
% -------------------------------------------------------------------------
function J = doubleSize(I)
[M,N]=size(I) ;
J = zeros(2*M,2*N) ;
J(1:2:end,1:2:end) = I ;
J(2:2:end-1,2:2:end-1) = ...
0.25*I(1:end-1,1:end-1) + ...
0.25*I(2:end,1:end-1) + ...
0.25*I(1:end-1,2:end) + ...
0.25*I(2:end,2:end) ;
J(2:2:end-1,1:2:end) = ...
0.5*I(1:end-1,:) + ...
0.5*I(2:end,:) ;
J(1:2:end,2:2:end-1) = ...
0.5*I(:,1:end-1) + ...
0.5*I(:,2:end) ;
function J = halveSize(I)
J=I(1:2:end,1:2:end) ;
%[M,N] = size(I) ;
%m=floor((M+1)/2) ;
%n=floor((N+1)/2) ;
%J = I(:,1:2:2*n) + I(:,2:2:2*n+1) ;
%J = 0.25*(J(1:2:2*m,:)+J(2:2:2*m+1,:)) ;
|
github
|
rising-turtle/slam_matlab-master
|
plotsiftdescriptor.m
|
.m
|
slam_matlab-master/SIFT/sift-0.9.17/sift/plotsiftdescriptor.m
| 5,466 |
utf_8
|
65f208762b6abd63cf2fa092410c1256
|
function h=plotsiftdescriptor(d,f)
% PLOTSIFTDESCRIPTOR Plot SIFT descriptor
% PLOTSIFTDESCRIPTOR(D) plots the SIFT descriptors D, stored as
% columns of the matrix D. D has the same format used by SIFT().
%
% 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 SIFT().
%
% H=PLOTSIFTDESCRIPTOR(...) returns the handle H to the line drawing
% representing the descriptors.
%
% REMARK. Currently the function supports only descriptors with 4x4
% spatial bins and 8 orientation bins (Lowe's default.)
%
% See also PLOTSIFTFRAME(), PLOTMATCHES(), PLOTSS().
% AUTORIGHTS
% Copyright (c) 2006 The Regents of the University of California.
% All Rights Reserved.
%
% Created by Andrea Vedaldi
% UCLA Vision Lab - Department of Computer Science
%
% Permission to use, copy, modify, and distribute this software and its
% documentation for educational, research and non-profit purposes,
% without fee, and without a written agreement is hereby granted,
% provided that the above copyright notice, this paragraph and the
% following three paragraphs appear in all copies.
%
% This software program and documentation are copyrighted by The Regents
% of the University of California. The software program and
% documentation are supplied "as is", without any accompanying services
% from The Regents. The Regents does not warrant that the operation of
% the program will be uninterrupted or error-free. The end-user
% understands that the program was developed for research purposes and
% is advised not to rely exclusively on the program for any reason.
%
% This software embodies a method for which the following patent has
% been issued: "Method and apparatus for identifying scale invariant
% features in an image and use of same for locating an object in an
% image," David G. Lowe, US Patent 6,711,293 (March 23,
% 2004). Provisional application filed March 8, 1999. Asignee: The
% University of British Columbia.
%
% IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY
% FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
% INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND
% ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
% ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE UNIVERSITY OF
% CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
% LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
% A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS"
% BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE
% MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
lowe_compatible = 1 ;
% --------------------------------------------------------------------
% Check the arguments
% --------------------------------------------------------------------
if(size(d,1) ~= 128)
error('D should be a 128xK matrix (only standard descriptors accepted)') ;
end
if nargin > 1
if(size(f,1) ~= 4)
error('F should be a 4xK matrix');
end
if(size(f,2) ~= size(f,2))
error('D and F must have the same number of columns') ;
end
end
% Descriptors are often non-double numeric arrays
d = double(d) ;
K = size(d,2) ;
if nargin < 2
f = repmat([0;0;1;0],1,K) ;
end
maginf = 3.0 ;
NBP=4 ;
NBO=8 ;
% --------------------------------------------------------------------
% Do the job
% --------------------------------------------------------------------
xall=[] ;
yall=[] ;
for k=1:K
SBP = maginf * f(3,k) ;
th=f(4,k) ;
c=cos(th) ;
s=sin(th) ;
[x,y] = render_descr(d(:,k)) ;
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) ;
% --------------------------------------------------------------------
% Helper functions
% --------------------------------------------------------------------
% Renders a single descriptor
function [x,y] = render_descr( d )
lowe_compatible=1;
NBP=4 ;
NBO=8 ;
[x,y] = meshgrid(-NBP/2:NBP/2,-NBP/2:NBP/2) ;
% Rescale d so that the biggest peak fits inside the bin diagram
d = 0.4 * d / max(d(:)) ;
% We have NBP*NBP 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 swap the order of the bin diagrams because they are stored row
% major into the descriptor (Lowe's convention that we follow.)
xc = xc' ;
yc = yc' ;
% Each bin contains a star with eight tips
xc = repmat(xc(:)',NBO,1) ;
yc = repmat(yc(:)',NBO,1) ;
% Do the stars
th=linspace(0,2*pi,NBO+1) ;
th=th(1:end-1) ;
if lowe_compatible
xd = repmat(cos(-th), 1, NBP*NBP ) ;
yd = repmat(sin(-th), 1, NBP*NBP ) ;
else
xd = repmat(cos(th), 1, NBP*NBP ) ;
yd = repmat(sin(th), 1, NBP*NBP ) ;
end
xd = xd .* d(:)' ;
yd = yd .* d(:)' ;
% Re-arrange in sequential order the lines to draw
nans = NaN * ones(1,NBP^2*NBO) ;
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,NBP+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
|
rising-turtle/slam_matlab-master
|
syn_error_pos.m
|
.m
|
slam_matlab-master/torso_orien/syn_error_pos.m
| 1,620 |
utf_8
|
58cae15433fde58eb47ad2e429f1f1ae
|
function syn_error_pos()
%% after synchronize, compute the error of position
%
est = load('estimate_07.log'); % load('estimate_06.log');
gt = load('gt_orien_07.log'); % load('gt_orien_06.log');
st_est = 1539612735.666800; %
st_gt = 9.475; %
syn_gt_est = syn_yaw_with_gt(gt, est, st_gt, st_est);
%% find scale
st = 30;
et = 300;
y = syn_gt_est(st:et, 2:4);
x = syn_gt_est(:, 5:7);
x(:,1) = x(:, 1) - mean(x(:,1)) + mean(y(:,1));
x(:,2) = x(:, 2) - mean(x(:,2)) + mean(y(:,2));
x = x(st:et, :);
e = y - x;
ir = find(abs(e(:,2)) < 0.02);
e = e(ir, :);
e = let_smooth(e);
E = diag(e*e');
de = sqrt(sum(E)/size(E,1));
% de = sqrt(dot(e, e)/size(e,1));
disp(['rmse = ' num2str(de)]);
t = 1:size(x,1);
t = t/30;
t = t(ir);
%% plot the result
plot(t, e(:,1), 'r-.');
% plot3(y(:,1), y(:,2), y(:,3), 'g-+');
% plot(y(:,1), y(:,3), 'g-+');
hold on;
% plot(x, 'b--');
% plot3(x(:,1), x(:,2), x(:,3), 'b-*');
% plot(x(:,1), x(:,3), 'b-+');
plot(t, e(:,2), 'g-.');
hold on;
plot(t, e(:,3), 'b-.');
end
function x = let_smooth(x)
x(:,1) = smooth(x(:,1), 7);
x(:,2) = smooth(x(:,2), 7);
x(:,3) = smooth(x(:,3), 7);
end
function [syn_gt] = syn_yaw_with_gt(gt, est, st_gt, st_est)
syn_gt = [];
j = 2;
for i=1:size(est,1)
query_t = est(i,1) - st_est + st_gt;
if query_t < 0
continue;
end
while j < size(gt,1)
if gt(j-1,1) <= query_t && gt(j,1) >= query_t
syn_gt = [syn_gt; query_t-gt(1,1) gt(j,3:5) est(i,5:7)];
break;
end
j = j + 1;
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
syn_error.m
|
.m
|
slam_matlab-master/torso_orien/syn_error.m
| 1,745 |
utf_8
|
fd003193838125b389c6b1332849a522
|
function syn_error()
%% after synchronize, compute the error of orientation
%
est = load('estimate_05.log'); % load('estimate_06.log');
gt = load('gt_orien_05.log'); % load('gt_orien_06.log');
st_est = 1539117466.769190; % 1539117578.592901;
st_gt = 48.825; % 50.75;
syn_gt_est = syn_yaw_with_gt(gt, est, st_gt, st_est);
%% find scale
x = syn_gt_est(130:310,3);
y = syn_gt_est(130:310,2);
x = smooth(x, 9);
%% fit the linear model
% y = a*x+b;
c = polyfit(x, y, 1);
% Display evaluated equation y = m*x + b
disp(['Equation is y = ' num2str(c(1)) '*x + ' num2str(c(2))]);
yy = c(1)*x + c(2);
e = y - yy;
ir = find(abs(e(:)) < 5);
x = x(ir);
e = e(ir);
y = y(ir);
yy = yy(ir);
x = smooth(x, 5);
y = smooth(y, 5);
yy = c(1)*x + c(2);
yy = smooth(yy, 7);
yy = smooth(yy, 7);
e = y - yy;
fprintf('max_e = %f std_e = %f', max(e), std(e));
de = sqrt(dot(e, e)/size(e,1));
disp(['rmse = ' num2str(de)]);
% index = find(yy < 40);
% yy = yy(index);
% y = y(index);
% x = x(index);
t = 1:size(x,1);
t = t/30;
%%
% e = e(ir, :);
% e = let_smooth(e);
%% plot the result
plot(t, y, 'g-.');
hold on;
% plot(x, 'r--');
hold on;
plot(t, yy, 'b-.');
e = y - yy;
plot(t, e, 'r-');
end
function [syn_gt] = syn_yaw_with_gt(gt, est, st_gt, st_est)
syn_gt = [];
j = 2;
for i=1:size(est,1)
query_t = est(i,1) - st_est + st_gt;
if query_t < 0
continue;
end
while j < size(gt,1)
if gt(j-1,1) <= query_t && gt(j,1) >= query_t
if gt(j,2) <= 30 && gt(j,2) >= -30
syn_gt = [syn_gt; query_t-gt(1,1) gt(j,2) est(i,3)];
end
break;
end
j = j + 1;
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
syn_error_z.m
|
.m
|
slam_matlab-master/torso_orien/syn_error_z.m
| 1,419 |
utf_8
|
d7ff4a4c9d65e80395717b4b96c7dca6
|
function syn_error_z()
%% after synchronize, compute the depth error
%
est = load('estimate_07.log'); % load('estimate_06.log');
gt = load('gt_orien_07.log'); % load('gt_orien_06.log');
st_est = 1539612735.666800; %
st_gt = 9.475; %
syn_gt_est = syn_yaw_with_gt(gt, est, st_gt, st_est);
%% find scale
st = 30;
et = 273;
y = syn_gt_est(st:et, 4);
x = syn_gt_est(st:et, 7);
y = y - y(1);
x = x - x(1);
x = smooth(x, 5);
e = y - x;
% ir = find(abs(e(:,2)) < 0.02);
% e = e(ir, :);
% e = let_smooth(e);
E = diag(e*e');
de = sqrt(sum(E)/size(E,1));
% de = sqrt(dot(e, e)/size(e,1));
disp(['rmse = ' num2str(de)]);
t = 1:size(x,1);
t = t/30;
% t = t(ir);
%% plot the result
plot(t, y, 'g-.');
% plot3(y(:,1), y(:,2), y(:,3), 'g-+');
% plot(y(:,1), y(:,3), 'g-+');
hold on;
plot(t, x, 'b-.');
% plot3(x(:,1), x(:,2), x(:,3), 'b-*');
% plot(x(:,1), x(:,3), 'b-+');
% plot(t, e(:,2), 'g-.');
hold on;
plot(t, e, 'r-.');
end
function [syn_gt] = syn_yaw_with_gt(gt, est, st_gt, st_est)
syn_gt = [];
j = 2;
for i=1:size(est,1)
query_t = est(i,1) - st_est + st_gt;
if query_t < 0
continue;
end
while j < size(gt,1)
if gt(j-1,1) <= query_t && gt(j,1) >= query_t
syn_gt = [syn_gt; query_t-gt(1,1) gt(j,3:5) est(i,5:7)];
break;
end
j = j + 1;
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
find_orien_gt.m
|
.m
|
slam_matlab-master/torso_orien/find_orien_gt.m
| 1,941 |
utf_8
|
b8d7bf0923f301abaea67a4802f61dfe
|
function find_orien_gt()
% Oct. 7 2018, He Zhang, [email protected]
% read points tracked by motion capture and estimate the square model in
% the camera coordinate system,
% then compute the normal of the torsor
M = csvread('gt_seq_07.csv');
vt = M(:,1);
pts_T = M(:,2:13);
pts_S = M(:,14:25);
mean_pts_T = mean(pts_T);
T_T2w = compute_transform(mean_pts_T);
T_c2T = [1 0 0 -0.055;
0 1 0 -0.05;
0 0 1 -0.0075;
0 0 0 1;];
T_c2w = T_c2T * T_T2w;
[vyaw, vpos] = compute_yaw_and_pos(pts_S, T_c2w);
D = [vt vyaw vpos];
dlmwrite('gt_orien_07.log', D, 'delimiter', '\t');
end
%% compute yaw
function [vyaw, vpos] = compute_yaw_and_pos(pts_S, T_c2w)
[row, col] = size(pts_S);
N = row*col;
pts_S = reshape(pts_S', [1, N]);
ps = reshape(pts_S, [3, N/3]);
[R, t] = decompose(T_c2w);
ps = R * ps + repmat(t, 1, N/3);
vyaw = zeros(row, 1);
vpos = zeros(row, 3);
%% compute norm
j = 1;
for i = 1:4:size(ps, 2)
psi = ps(:,i:i+3);
ni = compute_normal(psi);
central_pt = mean(psi,2);
vyaw(j) = compute_yaw_norm(ni);
vpos(j, :) = central_pt';
j = j + 1;
end
end
%% compute yaw
function yaw = compute_yaw_norm(n)
yaw = asin(n(1)/sqrt(n(1)*n(1)+n(3)*n(3))) * 180. /pi;
end
%% compute normal
function n = compute_normal(pts)
mean_pt = mean(pts, 2);
pts = pts - mean_pt;
Cov = pts*pts';
[V,D] = eig(Cov);
n = V(:,1);
if n(3) > 0
n= n * -1.;
end
end
%% estimate
function T = compute_transform(p_w)
% T pattern
%
p_world = reshape(p_w, [3, 4]);
p_local = [0, 0, -0.04;
0.03, 0, 0;
0, 0, 0;
-0.06, 0, 0];
[rot, trans] = find_transform_matrix( p_local', p_world);
tmp_p_l = rot * p_world + repmat(trans, 1, 4);
T = combine(rot, trans);
end
function [T] = combine(R, t)
T = [R t; 0 0 0 1];
end
function [R, t] = decompose(T)
R = T(1:3, 1:3);
t = T(1:3, 4);
end
|
github
|
rising-turtle/slam_matlab-master
|
load_camera_frame.m
|
.m
|
slam_matlab-master/graph_slam/load_camera_frame.m
| 2,106 |
utf_8
|
f61def678bbb3739023b59fd0fc7aa40
|
function [img, frm, des, p, ld_err] = load_camera_frame(fid)
%
% David Z, March 3th, 2015
% load camera data:
% img, 2D pixels
% frm,
% p [x y z]; (width, height, 3)
% ld_err = 1, if not exist
global g_data_dir g_data_prefix g_data_suffix g_camera_type
global g_filter_type
ld_err = 0; % TODO: take the load data error into consideration
% now only support SwissRanger
cut_off_boarder = 0; % weather to cut off the boarder pixels
dm = 1; % directory of data?
scale = 1; % scale the intensity image to the range [0~255]
value_type = 'int'; % convert to int, after scaling the image
%% feature has been stored
if file_exist(fid) ~= 0
[img, frm, des, p] = load_feature(fid);
return ;
else
if strcmp(g_camera_type, 'creative')
[img, x, y, z, c] = LoadCreative_dat(g_camera_type, fid);
else
if strcmp(g_data_suffix, 'dat')
[img, x, y, z, c] = LoadSR_no_bpc(g_camera_type, g_filter_type, ...
cut_off_boarder, dm, fid, scale, value_type);
elseif strcmp(g_data_suffix, 'bdat')
[img, x, y, z, c] = LoadSR_no_bpc_time_single_binary(g_camera_type, ...
g_filter_type, cut_off_boarder, dm, fid, scale, value_type);
end
end
if isempty(img)
frm = []; des = []; p =[];
ld_err = 1;
return;
end
end
%% sift feature
global g_sift_threshold
if g_sift_threshold == 0
[frm, des] = sift(img);
else
[frm, des] = sift(img, 'threshold', g_sift_threshold);
end
%% confindence filtering
[frm, des] = confidence_filtering(frm, des, c);
%% construct return value
[m, n] = size(x);
p = zeros(m, n, 3);
p(:,:,1) = x;
p(:,:,2) = y;
p(:,:,3) = z;
%% save it into file
global g_save_vro_middle_result
if g_save_vro_middle_result
save_feature(fid, img, frm, des, p);
end
end
%% check weather this visul feature exist
function [exist_flag] = file_exist(id)
%% get file name
global g_data_dir g_data_prefix g_feature_dir
file_name = sprintf('%s/%s/%s_%04d.mat', g_data_dir, g_feature_dir, g_data_prefix, id);
exist_flag = exist(file_name, 'file');
end
|
github
|
rising-turtle/slam_matlab-master
|
pre_check_dir.m
|
.m
|
slam_matlab-master/graph_slam/pre_check_dir.m
| 547 |
utf_8
|
8a7e9d1ce4f080306bd3b5ee748a06f2
|
%
% David Z, Jan 22th, 2015
% pre-check the save dir, if not exist, create it
%
function pre_check_dir(dir_)
global g_feature_dir g_matched_dir g_pose_std_dir
feature_dir = sprintf('/%s', g_feature_dir);
match_dir = sprintf('/%s', g_matched_dir);
not_exist_then_create(strcat(dir_, feature_dir));
not_exist_then_create(strcat(dir_, match_dir));
% not_exist_then_create(strcat(dir_, '/pose_std'));
not_exist_then_create('./results');
end
function not_exist_then_create(dir_)
if ~isdir(dir_)
mkdir(dir_);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadCreative_dat.m
|
.m
|
slam_matlab-master/graph_slam/LoadCreative_dat.m
| 783 |
utf_8
|
f539355d95dcac539680013bc4ae091c
|
%
% David Z, Jan 22th, 2015
% Load Creative Data
%
function [img, x, y, z, c, time, err] = LoadCreative_dat(data_name, j)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name);
img = []; x = []; y = []; z = []; c = [];
err = 0;
%% time elapse
t_pre = tic;
%% load data file
[file_name, err] = sprintf('%s%d.dat', prefix, j);
if ~exist(file_name, 'file')
fprintf('LoadCreative_dat.m: file not exist: %s\n', file_name);
err = 1;
return ;
end
a = load(file_name); % elapsed time := 0.2 sec
if isempty(a)
fprintf('LoadCreative_dat.m: file is empty!\n');
err = 1;
return;
end
row = size(a, 1);
img = a(1:row/4, :);
x = a((row/4+1):row/2, :);
y= a(row/2+1:3*row/4, :);
z = a(3*row/4+1:row, :);
c = zeros(size(x));
time = toc(t_pre);
end
|
github
|
rising-turtle/slam_matlab-master
|
VRO (2).m
|
.m
|
slam_matlab-master/graph_slam/VRO (2).m
| 9,711 |
utf_8
|
3d1a277522b64445257bd5affbb1e382
|
function [t, pose_std, e] = VRO(id1, id2, img1, img2, des1, frm1, p1, des2, frm2, p2)
%
% March 3th, 2015, David Z
% match two images and return the transformation between img1 and img2
% t : [ phi, theta, psi, trans];
% pose_std: pose covariance
% e : error
%
%% extract features, match img1 to img2
if ~exist('des1','var')
[frm1, des1] = sift(img1);
end
if ~exist('des2','var')
[frm2, des2] = sift(img2);
end
%% pose covariance
pose_std = [];
if file_exist(id1, id2) ~= 0 %% match points stored in a middle file
[op_match, e] = load_matched_points_zh(id1, id2);
if e > 0
[t,e] = error_exist('ransac filter failed!', 2);
return ;
end
else
%% if save the intermiddle data, do it
global g_save_feature_for_debug
if g_save_feature_for_debug
ftar_name = sprintf('tar_nodes/node_%d.log', id1);
fsrc_name = sprintf('src_nodes/node_%d.log', id2);
save_feature(ftar_name, des1, frm1, p1, id1);
save_feature(fsrc_name, des2, frm2, p2, id2);
end
%% first, sift feature match
match = siftmatch(des1, des2, 2.);
% fprintf('VRO.m after siftmatch, matched num: %d\n',size(match,2));
%% valid depth filter match correspondences
global g_depth_filter_max g_minimum_ransac_num
match = depth_filter(match, g_depth_filter_max, 0, frm1, frm2, p1, p2);
% fprintf('VRO.m after depth_filter, matched num: %d\n',size(match,2));
pnum = size(match,2); % pnum: matched feature pairs
if pnum <= g_minimum_ransac_num
[t,e] = error_exist('too few valid sift points for ransac!', 1);
return;
end
%% second, ransac to obtain the final transformation result
[op_match, e] = ransac_filter(match, frm1, frm2, p1, p2);
% op_match = match;
if e > 0
[t,e] = error_exist('ransac filter failed!', 2);
save_matched_points_zh(id1, id2, op_match, e);
return ;
end
%% save the match points
global g_save_vro_middle_result
if g_save_vro_middle_result
save_matched_points_zh(id1, id2, op_match);
end
end
%% lastly, SVD to compute the transformation
[t, pose_std, e] = svd_transformation(op_match, frm1, frm2, p1, p2);
end
%% SVD transformation
function [t, pose_std, e] = svd_transformation(op_match, frm1, frm2, p1, p2)
e = 0;
op_num = size(op_match, 2);
op_pset_cnt = 1;
x1 = p1(:,:,1); y1 = p1(:,:,2); z1 = p1(:,:,3);
x2 = p2(:,:,1); y2 = p2(:,:,2); z2 = p2(:,:,3);
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
end
%% SVD solve
[rot, trans, sta] = find_transform_matrix_e6(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
t = [ phi, theta, psi, trans'];
if sta <= 0
[t,e] = error_exist('no solution in SVD.', 3);
end
%% compute pose convariance
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
end
%% delete the pairs that contain (0,0,0) points
function match = filter_zero_pairs(match, frm1, frm2, p1, p2)
pnum = size(match, 2);
r_match = []; % return match
x1 = p1(:,:,1); y1 = p1(:,:,2); z1 = p1(:,:,3);
x2 = p2(:,:,1); y2 = p2(:,:,2); z2 = p2(:,:,3);
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
p1x=-x1(ROW1, COL1); p1z=z1(ROW1, COL1); p1y=y1(ROW1, COL1);
p2x=-x2(ROW2, COL2); p2z=z2(ROW2, COL2); p2y=y2(ROW2, COL2);
%% deletet the zero pairs
if (p1x + p1z + p1y == 0) || (p2x + p2y + p2z == 0)
continue;
end
r_match = [r_match match(:,i)];
end
match = r_match;
end
%% ransac transformation to get the result
function [op_match, error] = ransac_filter(match, frm1, frm2, p1, p2)
global g_ransac_iteration_limit
% pnum = size(match,2); % number of matched pairs
error = 0;
op_match = [];
%% delete the pairs that contain (0,0,0) points
match = filter_zero_pairs(match, frm1, frm2, p1, p2);
pnum = size(match,2); % number of matched pairs
%% ransac with a limited number
if g_ransac_iteration_limit > 0
% rst = min(g_ransac_iteration_limit, nchoosek(pnum, 4)); % at least C_n^4 times
rst = g_ransac_iteration_limit;
tmp_nmatch = zeros(2, pnum, rst);
tmp_cnum = zeros(rst,1);
for i=1:rst
[n_match, rs_match, cnum, translation] = ransac(frm1, frm2, match, p1(:,:,1),...
p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange', i);
% tmp_nmatch(:,1:cnum, i) = n_match(:,1:cnum);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_cnum(i) = cnum;
if cnum > 0
fprintf('iteration %d inlier num: %d, translation %f %f %f\n', i, cnum, translation);
end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
i=0;
eta_0 = 0.03; % 97 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
max_iteration = 120000;
while eta > eta_0
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, p1(:,:,1),...
p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange');
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
% tmp_nmatch(:,1:cnum,i) = n_match(:,1:cnum);
tmp_cnum(i) = cnum;
if cnum > 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
error = 1;
break;
end
end
ransac_iteration = i;
end
valid_ransac = 3; % this is the least valid number
[rs_max, rs_ind] = max(tmp_cnum);
fprintf('select %d with matched num = %d\n', rs_ind, rs_max);
op_num = tmp_cnum(rs_ind);
if (op_num < valid_ransac || error > 0)
error = 1;
return;
end
%% optimal matched pair set
op_match(:, 1:op_num) = tmp_nmatch(:, 1:op_num, rs_ind);
end
%% error exist
function [t, e] = error_exist(msg_err, e_type)
fprintf('VRO.m: %s\n', msg_err);
e = e_type;
t = zeros(1,6);
end
%% using depth to filter the erroreous matches
% p1 [x1 y1 z1] p2 [x2 y2 z2]
%
function match = depth_filter(m, max_d, min_d, frm1, frm2, p1, p2)
match = [];
m_img1 = [];
m_img2 = [];
m_dpt1 = [];
m_dpt2 = [];
cnt_new = 1;
pnum = size(m,2);
for i=1:pnum
frm1_index = m(1,i); frm2_index = m(2,i);
m_pix1 = frm1(:, frm1_index); m_pix2 = frm2(:, frm2_index);
COL1 = round(m_pix1(1))+1; COL2 = round(m_pix2(1))+1;
ROW1 = round(m_pix1(2))+1; ROW2 = round(m_pix2(2))+1;
%% ? row, col is right?
%% this match is a valid pair, this test is for Kinect
% if z(ROW1, COL1) > min_d && z(ROW1, COL1) < max_d ...
% && z(ROW2, COL2) > min_d && z(ROW2, COL2) < max_d
% ...
% end
temp_pt1=[-p1(ROW1, COL1, 1), p1(ROW1, COL1, 3), p1(ROW1, COL1, 2)];
temp_pt2=[-p2(ROW2, COL2, 1), p2(ROW2, COL2, 3), p2(ROW2, COL2, 2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= min_d && temp_pt1_dist <= max_d ...
&& temp_pt2_dist >= min_d && temp_pt2_dist <= max_d
match(:,cnt_new) = m(:,i);
cnt_new = cnt_new + 1;
end
end
end
%% check weather this matched file exist
function [exist_flag] = file_exist(id1, id2)
%% get file name
global g_data_dir g_data_prefix g_matched_dir
file_name = sprintf('%s/%s/%s_%04d_%04d.mat', g_data_dir, g_matched_dir ...
,g_data_prefix, id1, id2);
exist_flag = exist(file_name, 'file');
end
%% save feature in a style that can be loaded into vo in my sr_slam
function save_feature(fname, des, frm, p, id)
%% open file
fid = fopen(fname, 'w');
%% save feature loaction, size, orientation
M = size(frm, 2);
fprintf(fid, '-1 -1 %d 1 0\n', id);
fprintf(fid, '%d\n', M);
%% sift 2d information
response = zeros(1, M);
octave = zeros(1, M);
class_id = ones(1, M).*-1;
sift_loc_2d = [frm; response; octave; class_id]';
fprintf(fid, '%f %f %f %f %f %d %d \n', sift_loc_2d');
%% sift 3d location
sift_loc_3d = zeros(M, 4);
for i=1:M
m_pix = frm(:, i);
COL = round(m_pix(1))+1;
ROW = round(m_pix(2))+1;
pt =[-p(ROW, COL, 1), p(ROW, COL, 3), p(ROW, COL, 2)];
sift_loc_3d(i,1:3) = pt(1:3); sift_loc_3d(i,4) = 1;
end
fprintf(fid, '%f %f %f %f\n', sift_loc_3d');
%% sift descriptors
D_SIZE = size(des, 1);
fprintf(fid, '%d\n', D_SIZE);
for i=1:M
for j=1:D_SIZE
fprintf(fid, '%f ', des(j,i));
end
fprintf(fid, '\n');
end
fclose(fid);
end
|
github
|
rising-turtle/slam_matlab-master
|
graphslam_addpath.m
|
.m
|
slam_matlab-master/graph_slam/graphslam_addpath.m
| 1,409 |
utf_8
|
503a943bb30b3483282203370b1e5f57
|
% Add the path for graph slam
%
% Author : Soonhac Hong ([email protected])
% Date : 10/16/12
function graphslam_addpath
% addpath('D:\Soonhac\SW\gtsam-toolbox-2.3.0-win64\toolbox');
% addpath('D:\soonhac\SW\kdtree');
% addpath('D:\soonhac\SW\LevenbergMarquardt');
% addpath('D:\soonhac\SW\Localization');
% addpath('D:\soonhac\SW\SIFT\sift-0.9.19-bin\sift');
% addpath('D:\soonhac\SW\slamtoolbox\slamToolbox_11_09_08\FrameTransforms\Rotations');
% addpath('D:\Soonhac\SW\plane_fitting_code');
% addpath('F:\co-worker\soonhac\gtsam-toolbox-2.3.0-win64\toolbox');
% addpath('F:\co-worker\soonhac\SW\kdtree');
% addpath('F:\co-worker\soonhac\LevenbergMarquardt');
% addpath('F:\co-worker\soonhac\Localization');
% addpath('F:\co-worker\soonhac\SIFT\sift-0.9.19-bin\sift');
% addpath('F:\co-worker\soonhac\slamtoolbox\slamToolbox_11_09_08\FrameTransforms\Rotations');
% addpath('F:\co-worker\soonhac\plane_fitting_code');
global g_ws_dir;
addpath(strcat(g_ws_dir, '/gtsam-toolbox-2.3.0-win64/toolbox'));
addpath(strcat(g_ws_dir, '/kdtree'));
addpath(strcat(g_ws_dir, '/LevenbergMarquardt'));
addpath(strcat(g_ws_dir, '/SIFT/sift-0.9.19-bin/sift'));
addpath(strcat(g_ws_dir, '/slamtoolbox/slamToolbox_11_09_08/FrameTransforms/Rotations'));
addpath(strcat(g_ws_dir, '/plane_fitting_code'));
%% modified modules
addpath(strcat(g_ws_dir, '/Localization')); %%
addpath(strcat(g_ws_dir, '/GraphSLAM')); %%
end
|
github
|
rising-turtle/slam_matlab-master
|
plot_graph_trajectory.m
|
.m
|
slam_matlab-master/graph_slam/plot_graph_trajectory.m
| 1,866 |
utf_8
|
57a03921cd0e61d805de50b94592cd8c
|
function plot_graph_trajectory(gtsam_pose_initial, gtsam_pose_result)
%
% David Z, 3/6/2015
% draw the trajectory in the graph structure
%
import gtsam.*
plot_xyz_initial = [];
%% plot the initial pose trajectory : VRO result
keys = KeyVector(gtsam_pose_initial.keys);
initial_max_index = keys.size-1;
for i=0:int32(initial_max_index)
key = keys.at(i);
x = gtsam_pose_initial.at(key);
% T = x.matrix();
% [ry, rx, rz] = rot_to_euler(T(1:3,1:3));
plot_xyz_initial(i+1,:)=[x.x x.y x.z];
end
plot_xyz_result = [];
%% plot the result pose trajectory : GO graph optimization result
if exist('gtsam_pose_result', 'var')
keys = KeyVector(gtsam_pose_result.keys);
initial_max_index = keys.size-1;
for i=0:int32(initial_max_index)
key = keys.at(i);
x = gtsam_pose_result.at(key);
% T = x.matrix();
% [ry, rx, rz] = rot_to_euler(T(1:3,1:3));
plot_xyz_result(i+1,:)=[x.x x.y x.z];
end
end
%% plot them
figure(1);
subplot(1,2,2);
plot(plot_xyz_initial(:,1),plot_xyz_initial(:,2),'b-', 'LineWidth', 2);
legend('VRO');
hold on;
plot_start_point(plot_xyz_initial);
if exist('gtsam_pose_result', 'var')
plot(plot_xyz_result(:,1),plot_xyz_result(:,2),'r-', 'LineWidth', 2);
legend('PGO');
end
xlabel('X');ylabel('Y');
% Modify size of x in the graph
% xlim([-7 15]); % for etas523_exp2
% xlim([-15 5]); % for Amir's exp1
% xlim([-10 10]); % for etas523_exp2_lefthallway
% ylim([-5 15]);
global g_dis_x_min g_dis_x_max g_dis_y_min g_dis_y_max
xlim([g_dis_x_min g_dis_x_max]); % for etas523_exp2_lefthallway
ylim([g_dis_y_min g_dis_y_max]);
hold off;
grid;
axis equal;
end
function plot_start_point(plot_xyz_result)
plot(plot_xyz_result(1,1),plot_xyz_result(1,2),'ko', 'LineWidth', 3,'MarkerSize', 3);
text(plot_xyz_result(1,1)-1.5,plot_xyz_result(1,2)-1.5,'Start','Color',[0 0 0]);
end
|
github
|
rising-turtle/slam_matlab-master
|
img_preprocess.m
|
.m
|
slam_matlab-master/graph_slam/img_preprocess.m
| 1,748 |
utf_8
|
b8de79b4d263155edea6f71fe59278e6
|
function [ img ] = img_preprocess( data_name, old_file_version)
%IMG_PREPROCESS Summary of this function goes here
% Detailed explanation goes here
if nargin < 1
old_file_version = 1; % 1;
% data_name='/home/davidz/work/EmbMess/mesa/pcl_mesa/build/bin/sr_data/d1_0001.bdat';
data_name='/home/davidz/work/data/SwissRanger4000/try/d1_0001.bdat';
end
fileID=fopen(data_name);
if fileID==-1
%disp('File open fails !!');
return;
end
sr4k_image_width = 176;
sr4k_image_height = 144;
if old_file_version
z=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
x=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
y=fread(fileID,[sr4k_image_width,sr4k_image_height],'float');
img=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
% img=fread(fileID,[144,176],'uint16');
else
img=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
dis=fread(fileID,[sr4k_image_width,sr4k_image_height],'uint16');
dis = dis';
dis = scale_image(dis);
imshow(dis);
end
img = img';
img = scale_image(img);
imshow(img);
end
function [img] = scale_image(img)
%% set the pixels that is larger than limit = 65000, to 0
[m, n] = find (img>65000); %????
imgt=img;
num=size(m,1);
for kk=1:num
imgt(m(kk), n(kk))=0;
end
%% set the pixels larger than limit, to max(imgt) value
imax=max(max(imgt));
for kk=1:num
img(m(kk),n(kk))=imax;
end
%% sqrt(img) and rescale to 0-255
img=sqrt(img).*255./sqrt(max(max(img))); %This line degrade the performance of SURF
img = uint8(img);
%% Adaptive histogram equalization
% img = adapthisteq(img);
%% gaussian filter
gaussian_h = fspecial('gaussian',[3 3],1); %sigma = 1
% img=imfilter(img, gaussian_h,'replicate');
end
|
github
|
rising-turtle/slam_matlab-master
|
VRO.m
|
.m
|
slam_matlab-master/graph_slam/VRO.m
| 7,883 |
utf_8
|
375948226a012ecf3f66d09fec7af01c
|
function [t, pose_std, e] = VRO(id1, id2, img1, img2, des1, frm1, p1, des2, frm2, p2)
%
% March 3th, 2015, David Z
% match two images and return the transformation between img1 and img2
% t : [ phi, theta, psi, trans];
% pose_std: pose covariance
% e : error
%
%% extract features, match img1 to img2
if ~exist('des1','var')
[frm1, des1] = sift(img1);
end
if ~exist('des2','var')
[frm2, des2] = sift(img2);
end
%% pose covariance
pose_std = [];
if file_exist(id1, id2) ~= 0 %% match points stored in a middle file
[op_match, e] = load_matched_points_zh(id1, id2);
if e > 0
[t,e] = error_exist('ransac filter failed!', 2);
return ;
end
else
%% first, sift feature match
match = siftmatch(des1, des2);
% fprintf('VRO.m after siftmatch, matched num: %d\n',size(match,2));
%% valid depth filter match correspondences
global g_depth_filter_max g_minimum_ransac_num
match = depth_filter(match, g_depth_filter_max, 0, frm1, frm2, p1, p2);
% fprintf('VRO.m after depth_filter, matched num: %d\n',size(match,2));
pnum = size(match,2); % pnum: matched feature pairs
if pnum <= g_minimum_ransac_num
[t,e] = error_exist('too few valid sift points for ransac!', 1);
return;
end
%% second, ransac to obtain the final transformation result
[op_match, e] = ransac_filter(match, frm1, frm2, p1, p2);
% op_match = match;
if e > 0
[t,e] = error_exist('ransac filter failed!', 2);
save_matched_points_zh(id1, id2, op_match, e);
return ;
end
%% save the match points
save_matched_points_zh(id1, id2, op_match);
end
%% lastly, SVD to compute the transformation
[t, pose_std, e] = svd_transformation(op_match, frm1, frm2, p1, p2);
end
%% SVD transformation
function [t, pose_std, e] = svd_transformation(op_match, frm1, frm2, p1, p2)
e = 0;
op_num = size(op_match, 2);
op_pset_cnt = 1;
x1 = p1(:,:,1); y1 = p1(:,:,2); z1 = p1(:,:,3);
x2 = p2(:,:,1); y2 = p2(:,:,2); z2 = p2(:,:,3);
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
end
%% SVD solve
[rot, trans, sta] = find_transform_matrix_e6(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
t = [ phi, theta, psi, trans'];
if sta <= 0
[t,e] = error_exist('no solution in SVD.', 3);
end
%% compute pose convariance
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
end
%% delete the pairs that contain (0,0,0) points
function match = filter_zero_pairs(match, frm1, frm2, p1, p2)
pnum = size(match, 2);
r_match = []; % return match
x1 = p1(:,:,1); y1 = p1(:,:,2); z1 = p1(:,:,3);
x2 = p2(:,:,1); y2 = p2(:,:,2); z2 = p2(:,:,3);
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
p1x=-x1(ROW1, COL1); p1z=z1(ROW1, COL1); p1y=y1(ROW1, COL1);
p2x=-x2(ROW2, COL2); p2z=z2(ROW2, COL2); p2y=y2(ROW2, COL2);
%% deletet the zero pairs
if (p1x + p1z + p1y == 0) || (p2x + p2y + p2z == 0)
continue;
end
r_match = [r_match match(:,i)];
end
match = r_match;
end
%% ransac transformation to get the result
function [op_match, error] = ransac_filter(match, frm1, frm2, p1, p2)
global g_ransac_iteration_limit
% pnum = size(match,2); % number of matched pairs
error = 0;
op_match = [];
%% delete the pairs that contain (0,0,0) points
match = filter_zero_pairs(match, frm1, frm2, p1, p2);
pnum = size(match,2); % number of matched pairs
%% ransac with a limited number
if g_ransac_iteration_limit > 0
rst = min(g_ransac_iteration_limit, nchoosek(pnum, 4)); % at least C_n^4 times
tmp_nmatch = zeros(2, pnum, rst);
tmp_cnum = zeros(rst,1);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, p1(:,:,1),...
p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange');
% tmp_nmatch(:,1:cnum, i) = n_match(:,1:cnum);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_cnum(i) = cnum;
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
i=0;
eta_0 = 0.03; % 97 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
max_iteration = 120000;
while eta > eta_0
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, p1(:,:,1),...
p1(:,:,2), p1(:,:,3), p2(:,:,1), p2(:,:,2), p2(:,:,3), 'SwissRange');
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
% tmp_nmatch(:,1:cnum,i) = n_match(:,1:cnum);
tmp_cnum(i) = cnum;
if cnum > 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
error = 1;
break;
end
end
ransac_iteration = i;
end
valid_ransac = 3; % this is the least valid number
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if (op_num < valid_ransac || error > 0)
error = 1;
return;
end
%% optimal matched pair set
op_match(:, 1:op_num) = tmp_nmatch(:, 1:op_num, rs_ind);
end
%% error exist
function [t, e] = error_exist(msg_err, e_type)
fprintf('VRO.m: %s\n', msg_err);
e = e_type;
t = zeros(1,6);
end
%% using depth to filter the erroreous matches
% p1 [x1 y1 z1] p2 [x2 y2 z2]
%
function match = depth_filter(m, max_d, min_d, frm1, frm2, p1, p2)
match = [];
m_img1 = [];
m_img2 = [];
m_dpt1 = [];
m_dpt2 = [];
cnt_new = 1;
pnum = size(m,2);
for i=1:pnum
frm1_index = m(1,i); frm2_index = m(2,i);
m_pix1 = frm1(:, frm1_index); m_pix2 = frm2(:, frm2_index);
COL1 = round(m_pix1(1))+1; COL2 = round(m_pix2(1))+1;
ROW1 = round(m_pix1(2))+1; ROW2 = round(m_pix2(2))+1;
%% ? row, col is right?
%% this match is a valid pair, this test is for Kinect
% if z(ROW1, COL1) > min_d && z(ROW1, COL1) < max_d ...
% && z(ROW2, COL2) > min_d && z(ROW2, COL2) < max_d
% ...
% end
temp_pt1=[-p1(ROW1, COL1, 1), p1(ROW1, COL1, 3), p1(ROW1, COL1, 2)];
temp_pt2=[-p2(ROW2, COL2, 1), p2(ROW2, COL2, 3), p2(ROW2, COL2, 2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= min_d && temp_pt1_dist <= max_d ...
&& temp_pt2_dist >= min_d && temp_pt2_dist <= max_d
match(:,cnt_new) = m(:,i);
cnt_new = cnt_new + 1;
end
end
end
%% check weather this matched file exist
function [exist_flag] = file_exist(id1, id2)
%% get file name
global g_data_dir g_data_prefix g_matched_dir
file_name = sprintf('%s/%s/%s_%04d_%04d.mat', g_data_dir, g_matched_dir ...
,g_data_prefix, id1, id2);
exist_flag = exist(file_name, 'file');
end
|
github
|
rising-turtle/slam_matlab-master
|
dump_matrix_2_file.m
|
.m
|
slam_matlab-master/graph_slam/dump_matrix_2_file.m
| 364 |
utf_8
|
ff92d9360b0b19252a256ed0ebd60fd3
|
function dump_matrix_2_file(fname, m)
%
% David Z, Feb 19, 2015
% try to construct a function to dump every kind of matrix into a text file
%
dump_matrix_2_file_wf(fname, m)
end
function dump_matrix_2_file_wf(f, m)
f_id = fopen(f, 'w+');
for i=1:size(m,1)
fprintf(f_id, '%f ', m(i,:));
fprintf(f_id, '\n');
end
fclose(f_id);
end
|
github
|
rising-turtle/slam_matlab-master
|
sampling_vro.m
|
.m
|
slam_matlab-master/Localization/sampling_vro.m
| 1,168 |
utf_8
|
6034c6abcaf471707991c8ae56168921
|
% Sampling VRO with interval
%
% Author : Soonhac Hong ([email protected])
% Date : 12/13/13
function sampling_vro()
% Load data
file_name = '498_frame_abs_intensity_sift_i_r_s_i_t_t_c_i_a_c_c_featureidxfix_fast_fast_dist2_nobpc_20st_gaussian_0.dat';
vro = load(file_name);
% Sample VRO with interval
interval = 15;
new_vro=[];
vro_idx = 1;
success_flag = 1;
while vro_idx <= (max(vro(:,1))-interval)
idx = find(vro(:,1)==vro_idx & vro(:,2) == (vro_idx+interval));
if ~isempty(idx)
new_vro=[new_vro; vro(idx,:)];
vro_idx = vro_idx+interval;
else
success_flag = 0;
disp('Faile to sample vro results');
break;
end
end
% Write results
if success_flag == 1
output_file_name = sprintf('result\\object_recognition\\indoor_monitor_1\\498_frame_abs_intensity_sift_i_r_s_i_t_t_c_i_a_c_c_featureidxfix_fast_fast_dist2_nobpc_20st_gaussian_0_monitor1_s%d.dat', interval);
output_fd = fopen(output_file_name,'w');
fprintf(output_fd,'%d %d %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f %12.8f\n', new_vro');
fclose(output_fd);
end
end
|
github
|
rising-turtle/slam_matlab-master
|
load_pose_std.m
|
.m
|
slam_matlab-master/Localization/load_pose_std.m
| 1,367 |
utf_8
|
329d9ca060491048ca17bf713699f70a
|
% Load matched points from a file
%
% Author : Soonhac Hong ([email protected])
% Date : 3/11/2013
function [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, isgframe, sequence_data)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
if strcmp(isgframe, 'gframe')
file_name = sprintf('%s/pose_std_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
else
file_name = sprintf('%s/pose_std/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
if strcmp(isgframe, 'gframe')
file_name = sprintf('%s/pose_std_gframe/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
else
file_name = sprintf('%s/pose_std/d1_%04d_d%d_%04d.mat',dataset_dir, first_cframe, dm, second_cframe);
end
end
% if strcmp(isgframe, 'gframe')
% file_name = sprintf('%s/matched_points_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% else
% file_name = sprintf('%s/matched_points/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
% end
load(file_name);
end
|
github
|
rising-turtle/slam_matlab-master
|
compute_pose_std.m
|
.m
|
slam_matlab-master/Localization/compute_pose_std.m
| 1,000 |
utf_8
|
92a7ecfe7741a125b61cc27344fc802d
|
% Compute covariance of vro
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
%
% Reference : [cov_pose_shift,q_dpose,T_dpose] = bootstrap_cov_calc(idx1,idx2)
%
function [pose_std] = compute_pose_std(op_pset1,op_pset2,rot_mean, trans_mean)
nData = size(op_pset1,2);
sampleSize = min(40,floor(0.75*nData));
nSamplePossible = factorial(nData)/(factorial(sampleSize)*factorial(nData - sampleSize));
nSample = min(50,nSamplePossible);
pose_std_total=[];
[phi_mean, theta_mean, psi_mean] = rot_to_euler(rot_mean);
pose_mean = [phi_mean, theta_mean, psi_mean, trans_mean'];
legitSamples = 0;
for i=1:nSample
idxRand = randsample(1:size(op_pset1,2),sampleSize);
[rot, trans, sta] = find_transform_matrix(op_pset1(:,idxRand), op_pset2(:,idxRand));
[phi, theta, psi] = rot_to_euler(rot);
pose_std_total(i,:) = [phi, theta, psi, trans'];
end
%pose_std = std(pose_std_total);
pose_std = sqrt((sum((pose_std_total - repmat(pose_mean, nSample, 1)).^2))/(nSample-1));
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_a.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_a.m
| 20,536 |
utf_8
|
73fe356fb62535fac468a5d25f2e87ca
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_a(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
%[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);%% modify for read data from creative !!!
[img1,x1, y1, z1] = load_argos3d(dm, cframe);
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
%[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
%[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
%[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
[img2,x2, y2, z2] = load_argos3d(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
%[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max =1; % [m]
valid_dist_min =0.15; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
%mapped cor_j1 is 320*240 matrix, then know the row and col
%of matched point
%[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
%[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
% temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
% temp_pt1_dist = sqrt(sum(temp_pt1.^2));
% temp_pt2_dist = sqrt(sum(temp_pt2.^2));
%%%%%above comment for creative
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
match_image1(:,cnt_new)=[ROW1 COL1]';
match_image2(:,cnt_new)=[ROW2 COL2]';
match_depth1(:,cnt_new)=[ROW1 COL1]';
match_depth2(:,cnt_new)=[ROW2 COL2]';
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
[n_match, rs_match, cnum] = ransac_argos3d(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
%[n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,match_image1,match_image2,match_depth1,match_depth2, data_name);
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(row1, col1); op_pset1(2,op_pset_cnt)=z1(row1, col1); op_pset1(3,op_pset_cnt)=y1(row1, col1);
op_pset2(1,op_pset_cnt)=-x2(row2, col2); op_pset2(2,op_pset_cnt)=z2(row2, col2); op_pset2(3,op_pset_cnt)=y2(row2, col2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
get_swing_filename.m
|
.m
|
slam_matlab-master/Localization/get_swing_filename.m
| 595 |
utf_8
|
8aea150ea1b5e47239276537edf87afc
|
% Get directory name of motive datasets
%
% Author : Soonhac Hong ([email protected])
% Date : 11/20/13
function motive_filename_lists=get_swing_filename()
motive_filename_lists = {'forward1','forward2','forward3','forward4','forward5','forward6','forward7_10m','forward8_10m', 'forward9_10m','forward10_10m','forward11_10m','forward12_10m','forward13_10m','forward14_10m','forward15_10m','forward16_10m','revisiting1_10m','revisiting2_10m','revisiting3_10m','revisiting4_10m','revisiting5_10m','revisiting6_10m','revisiting7_10m','revisiting8_10m','revisiting9_10m','revisiting10_10m'};
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadSR_no_bpc_wu.m
|
.m
|
slam_matlab-master/Localization/LoadSR_no_bpc_wu.m
| 4,230 |
utf_8
|
3481d9400dbded650f4cbb0568337a7a
|
% Load data from Swiss Ranger
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
% No bad pixel compensation
function [img, x, y, z, c, rtime] = LoadSR_no_bpc_wu(data_name, filter_name, boarder_cut_off, dm, j, scale, type_value)
% if nargin < 6
% scale = 1;
% end
%apitch=-43+3*dm;
%[prefix, err]=sprintf('../data/d%d_%d/d%d', dm, apitch, dm);
%[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
confidence_read=1;
path = 'd:/co_worker/image_';
if j<10
% [s, err]=sprintf('%s_000%d.dat', prefix, j);
s=sprintf('%s%d/d1_000%d.dat',path, dm-1, j);
elseif j<100
% [s, err]=sprintf('%s_00%d.dat', prefix, j);
s=sprintf('%s%d/d1_00%d.dat', path, dm-1,j);
elseif j<1000
% [s, err]=sprintf('%s_0%d.dat', prefix, j);
s=sprintf('%s%d/d1_0%d.dat', path, dm-1,j);
else
% [s, err]=sprintf('%s_%d.dat', prefix, j);
s=sprintf('%s%d/d1_%d.dat',path, dm-1, j);
end
%t_pre = clock; %cputime;
t_pre = tic;
fw=1;
a = load(s); % elapsed time := 0.2 sec
k=144*3+1;
img = double(a(k:k+143, :));
z = a(1:144, :); x = a(145:288, :); y = a(289:144*3, :);
z = medfilt2(z,[fw fw]); x = medfilt2(x, [fw fw]); y = medfilt2(y, [fw fw]);
if confidence_read == 1
c = a(144*4+1:144*5, :);
% Apply median filter to a pixel which confidence leve is zero.
%confidence_cut_off = 1;
%[img, x, y, z, c] = compensate_badpixel(img, x, y, z, c, confidence_cut_off);
else
c = 0;
end
%Cut-off on the horizontal boarder
if boarder_cut_off > 0
img=cut_boarder(img,boarder_cut_off);
x=cut_boarder(x,boarder_cut_off);
y=cut_boarder(y,boarder_cut_off);
z=cut_boarder(z,boarder_cut_off);
end
%Scale intensity image to [0 255]
if scale == 1
img = scale_img(img, fw, type_value, 'intensity');
end
% % Adaptive histogram equalization
img = adapthisteq(img);
%img = histeq(img);
%filtering
%filter_list={'none','median','gaussian'};
gaussian_h = fspecial('gaussian',[3 3],1); %sigma = 1
gaussian_h_5 = fspecial('gaussian',[5 5],1); %sigma = 1
switch filter_name
case 'median'
img=medfilt2(img, [3 3]);
x=medfilt2(x, [3 3]);
y=medfilt2(y, [3 3]);
z=medfilt2(z, [3 3]);
case 'median5'
img=medfilt2(img, [5 5]);
x=medfilt2(x, [5 5]);
y=medfilt2(y, [5 5]);
z=medfilt2(z, [5 5]);
case 'gaussian'
img=imfilter(img, gaussian_h,'replicate');
x=imfilter(x, gaussian_h,'replicate');
y=imfilter(y, gaussian_h,'replicate');
z=imfilter(z, gaussian_h,'replicate');
case 'gaussian_edge_std'
img=imfilter(img, gaussian_h,'replicate');
x_g=imfilter(x, gaussian_h,'replicate');
y_g=imfilter(y, gaussian_h,'replicate');
z_g=imfilter(z, gaussian_h,'replicate');
x = check_edges(x, x_g);
y = check_edges(y, y_g);
z = check_edges(z, z_g);
case 'gaussian5'
img=imfilter(img, gaussian_h_5,'replicate');
x=imfilter(x, gaussian_h_5,'replicate');
y=imfilter(y, gaussian_h_5,'replicate');
z=imfilter(z, gaussian_h_5,'replicate');
end
%rtime = etime(clock, t_pre); %cputime - t_pre;
rtime = toc(t_pre);
end
function [img]=cut_boarder(img, cut_off)
image_size=size(img);
h_cut_off_pixel=round(image_size(2)*cut_off/100);
v_cut_off_pixel=round(image_size(1)*cut_off/100);
img(:,(image_size(2)-h_cut_off_pixel+1):image_size(2))=[]; %right side of Horizontal
img(:,1:h_cut_off_pixel)=[]; %left side of Horizontal
img((image_size(1)-v_cut_off_pixel+1):image_size(1),:)=[]; %up side of vertical
img(1:v_cut_off_pixel,:)=[]; %bottom side of vertical
end
function [data] = check_edges(data, data_g)
%edges = 0;
for i = 2:size(data,1)-1
for j= 2:size(data,2)-1
%if var(data(i-1:i+1,j-1:j+1)) <= 0.001
unit_vector = [data(i-1,j-1:j+1) data(i, j-1:j+1) data(i+1, j-1:j+1)];
%if std(unit_vector)/(max(unit_vector) - min(unit_vector)) <= 0.4
if std(unit_vector) <= 0.1
data(i,j) = data_g(i,j);
%else
% edges = edges + 1;
end
end
end
%edges
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_sr.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_sr.m
| 20,549 |
utf_8
|
963d2b78711e06b32a8bb36c6f2362ae
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_sr(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc_wu(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
%[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);%% modify for read data from creative !!!
%[img1,x1, y1, z1] = load_argos3d(dm, cframe);
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc_wu(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
%[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
%[img2,x2, y2, z2] = load_argos3d(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max =1.5; % [m]
valid_dist_min =0.15; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
%mapped cor_j1 is 320*240 matrix, then know the row and col
%of matched point
%[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
%[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
% temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
% temp_pt1_dist = sqrt(sum(temp_pt1.^2));
% temp_pt2_dist = sqrt(sum(temp_pt2.^2));
%%%%%above comment for creative
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
% match_image1(:,cnt_new)=[ROW1 COL1]';
% match_image2(:,cnt_new)=[ROW2 COL2]';
% match_depth1(:,cnt_new)=[ROW1 COL1]';
% match_depth2(:,cnt_new)=[ROW2 COL2]';
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
[n_match, rs_match, cnum] = ransac_argos3d(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
%[n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,match_image1,match_image2,match_depth1,match_depth2, data_name);
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
%[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
% [row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_pm.m
| 21,689 |
utf_8
|
bec6d7eeeab3f0472b13909cd21b1fea
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_p(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
%if strcmp(data_name, 'kinect_tum')
if strcmp(data_name, 'primesense') % change to primesense by wei wu
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
%[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
%[img1, x1, y1, z1] = load_primesense(dm, cframe);
[img1, x1, y1, z1] = LoadPrimesense_model(dm, cframe);
elapsed_pre=0;
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img1,x1, y1, z1, cor_i1, cor_j1] = load_creative(dm, cframe);
%% modify for read data from creative !!!
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1 %CHANGE BY WEI FROM 1 TO 0
f1 = figure(4);
imagesc(img1);
colormap(gray);
title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
%[frm1, des1] = confidence_filtering(frm1, des1, c1);
%save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
% if strcmp(data_name, 'kinect_tum')
% %[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
% [img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
if strcmp(data_name, 'primesense') % change to primesense by wei wu
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
%[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
%[img2, x2, y2, z2] = load_primesense(dm, cframe);
[img2, x2, y2, z2] = LoadPrimesense_model(dm, cframe);
elapsed_pre2=0;
else
%[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img2,x2, y2, z2, cor_i2, cor_j2] = load_creative(dm, cframe);
elapsed_pre2=0;
%% modify for read data from creative !!!
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
%[frm2, des2] = confidence_filtering(frm2, des2, c2);
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1 %changed from 1 to 0 by wei
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
% f4=figure(7);
% imshow(match);
end
% distance filtering
% if is_10M_data == 1
% valid_dist_max = 8; % 5m
% else
% valid_dist_max = 5; % 5m
% end
% valid_dist_min = 0.8; % 0.8m
%%debugging
% figure;
% imshow(img1);
% figure;
% z1_dis=z1;
% z1_dis_max=max(max(z1));
% idx=find(z1==z1_dis_max);
% z1_dis(idx)=0;
% imshow(z1_dis, [0 255]);
valid_dist_max = 1; % [m]
valid_dist_min = 0.350; % [m]
match_new = [];
match_image1=[];
match_image2=[];
match_depth1=[];
match_depth2=[];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
%if strcmp(data_name, 'kinect_tum')
if strcmp(data_name, 'primesense')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) >valid_dist_min && z2(ROW2, COL2) > valid_dist_min&&z1(ROW1, COL1) <valid_dist_max && z2(ROW2, COL2) <valid_dist_max
%if z1(ROW1, COL1)>valid_dist_min && z2(ROW2, COL2)>0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
% col1=SearchColumn(cor_i1,COL1,10);
% row1=SearchRow(cor_j1,ROW1,10); %ADD BY WEI
% col2=SearchColumn(cor_i2,COL2,10);
% row2=SearchRow(cor_j2,ROW2,10); %ADD BY WEI
[row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
[row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
if col1~=0&&row1~=0&&col2~=0&&row2~=0
temp_pt1=[-x1(row1, col1), z1(row1, col1), y1(row1, col1)];
temp_pt2=[-x2(row2, col2), z2(row2, col2), y2(row2, col2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
% end
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
match_image1(:,cnt_new)=[ROW1 COL1]';
match_image2(:,cnt_new)=[ROW2 COL2]';
match_depth1(:,cnt_new)=[row1 col1]';
match_depth2(:,cnt_new)=[row2 col2]';
cnt_new = cnt_new + 1;
end
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2,match_image1,match_image2,match_depth1,match_depth2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
%[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_creative(frm1, frm2, match, x1, y1, z1, x2, y2, z2,cor_i1,cor_j1,cor_i2,cor_j2, data_name);
[n_match, rs_match, cnum] = ransac_primesense(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
cnum
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
% f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
% if strcmp(data_name, 'kinect_tum')
if strcmp(data_name, 'primesense')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
% [row1,col1]=Search_RowandCol(cor_j1,ROW1,cor_i1,COL1);
% [row2,col2]=Search_RowandCol(cor_j2,ROW2,cor_i2,COL2);
% if col1~=0&&row1~=0&&col2~=0&&row2~=0
% [row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row1,col1]=match_rowandcol(match_image1,match_depth1,ROW1,COL1);
[row2,col2]=match_rowandcol(match_image2,match_depth2,ROW2,COL2);
op_pset1(1,op_pset_cnt)=-x1(row1, col1); op_pset1(2,op_pset_cnt)=z1(row1, col1); op_pset1(3,op_pset_cnt)=-y1(row1, col1);
op_pset2(1,op_pset_cnt)=-x2(row2, col2); op_pset2(2,op_pset_cnt)=z2(row2, col2); op_pset2(3,op_pset_cnt)=-y2(row2, col2);
op_pset_cnt = op_pset_cnt + 1; %changed by wu
%end
% end
%% Modify coordinate according to Creative !! done
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
% if strcmp(data_name, 'kinect_tum')
% elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
if strcmp(data_name, 'primesense')
% elapsed = [ elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
% if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% % save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
save_visual_features.m
|
.m
|
slam_matlab-master/Localization/save_visual_features.m
| 1,181 |
utf_8
|
ba22c81ae039ca48c4065d21de093e35
|
% Save sift visual feature into a file
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function save_visual_features(data_name, dm, cframe, frm, des, elapsed_sift, img, x, y, z, c, elapsed_pre, sequence_data, image_name)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
if strcmp(image_name, 'depth')
file_name = sprintf('%s/depth_feature/d1_%04d.mat',dataset_dir, cframe);
else
file_name = sprintf('%s/visual_feature/d1_%04d.mat',dataset_dir, cframe);
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
if strcmp(image_name, 'depth')
file_name = sprintf('%s/depth_feature/d%d_%04d.mat',dataset_dir, dm, cframe);
else
file_name = sprintf('%s/visual_feature/d%d_%04d.mat',dataset_dir, dm, cframe);
end
end
%file_name = sprintf('%s/visual_feature/d1_%04d.mat',dataset_dir, cframe);
save(file_name, 'frm', 'des', 'elapsed_sift', 'img', 'x', 'y', 'z', 'c', 'elapsed_pre');
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_c2.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_c2.m
| 17,776 |
utf_8
|
577e5b47084e3aab212e2ee92834b933
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_c2(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
%[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img1, x1, y1, z1] = load_creative_binary(dm, cframe);
elapsed_pre=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
% [frm1, des1] = confidence_filtering(frm1, des1, c1);
% save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
%
% else
% [frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
%if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
% [img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
[img2, x2, y2, z2] = load_creative_binary(dm, cframe);
elapsed_pre2=0;
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
% [frm2, des2] = confidence_filtering(frm2, des2, c2);
%
% save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
%
% else
% [frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
% end
%if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% distance filtering
if is_10M_data == 1
valid_dist_max = 8; % 5m
else
valid_dist_max = 1; % 5m
end
valid_dist_min = 0.15; % 0.8m
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
% save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
%
% else
% [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% t_svd = tic;
% end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
%if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
% save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
% else
% [pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
% end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast.m
| 16,231 |
utf_8
|
84b24dd4aa8859f73260befb87e72c1e
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, dis)
if nargin < 13
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none') == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none');
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none');
t_svd = tic;
end
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta == 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadPrimesense_newmodel1.m
|
.m
|
slam_matlab-master/Localization/LoadPrimesense_newmodel1.m
| 2,543 |
utf_8
|
7ec641cc6b0375f05707697ba5146dc8
|
% Load data from Kinect
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
function [img, X, Y, Z] = LoadPrimesense_model(dm, file_index)
if file_index<11
z_file_name=sprintf('D:/image/prime/image%d/depth/00%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/prime/image%d/rgb/00%d.png',dm-1,file_index-1);
elseif file_index<101
z_file_name=sprintf('D:/image/prime/image%d/depth/0%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/prime/image%d/rgb/0%d.png',dm-1,file_index-1);
elseif file_index<605
z_file_name=sprintf('D:/image/prime/image%d/depth/%d.png',dm-1,file_index-1);
img_file_name=sprintf('D:/image/prime/image%d/rgb/%d.png',dm-1,file_index-1);
end
depth_img=imread(z_file_name);
depth_img=double(depth_img);
img1=imread(img_file_name);
img=rgb2gray(img1);
gaussian_h = fspecial('gaussian',[3 3],1);
img=imfilter(img, gaussian_h,'replicate');
%img=im2double(img);
%Rt=[ 0.99977 0.010962 -0.018654 0.023278;
% -0.010059 0.9988 0.047831 -0.0097038;
% 0.019156 -0.047632 0.99868 -0.0093007 ]; % add calibration R and T
R=[ 1.0000 -0.0033 0.0028; %-26.87065;
0.0033 1.0000 0.0043; %0.94765;
-0.0028 -0.0042 1.0000 ] ; % 6.74013]; % add calibration R and T
T=[-26.9 0.9, 6.7]';
Kr=[543 0 318;
0 543 231;
0 0 1];
[imh, imw] = size(depth_img);
X=zeros(imh,imw);
Y=zeros(imh,imw);
Z=zeros(imh,imw);
fx = 570; %# focal length x 551.0/420
fy = 570; %# focal length y 548.0/420
cx = 320; %# optical center x //319.5
cy = 240; %# optical center y ///239.5
ds = 1.0; %# depth scaling
factor = 1; %# for the 16-bit PNG files
for v=1:size(depth_img,1) %height
for u=1:size(depth_img,2) %width
z = (depth_img(v,u) / factor) * ds;
x = (u - cx) * z / fx;
y = (v - cy) * z / fy;
% X(v,u) = x;
% Y(v,u) = y;
% Z(v,u) = z;
Pr=R*[x y z ]'+T;
Z(v,u)=Pr(3,:);
X(v,u)=(u-318)*Z(v,u)/541;
Y(v,u)=(v-231)*Z(v,u)/541;
%
%u_vector=round(uv_vector(1,:)/uv_vector(3,:));
%v_vector=round(uv_vector(2,:)/uv_vector(3,:));
%if u_vector>0 && u_vector<640 &&v_vector>0 && v_vector<480
% X(v_vector,u_vector)=x;
% Y(v_vector,u_vector)=y;
% Z(v_vector,u_vector)=z;
%end
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
scale_img.m
|
.m
|
slam_matlab-master/Localization/scale_img.m
| 1,061 |
utf_8
|
9c5217d62c210a4383e5c109eb4964c6
|
% Scale and smoothing image
%
% Parameters
% img : input image
% fw : the size of median filter
%
% Author : Soonhac Hong ([email protected])
% Date : 4/21/11
function [img] = scale_img(img, fw, value_type, data_type)
[m, n, v] = find (img>65000); %????
imgt=img;
num=size(m,1);
for kk=1:num
imgt(m(kk), n(kk))=0;
end
imax=max(max(imgt));
for kk=1:num
img(m(kk),n(kk))=imax;
end
min_v = min(min(img));
max_v = max(max(img));
sqt_max = sqrt(max_v);
sqt_min = sqrt(min_v);
% img=uint8(sqrt(img).*255./sqrt(max(max(img))));
if strcmp(data_type, 'intensity')
% img=sqrt(img).*255./sqrt(max(max(img))); %This line degrade the performance of SURF
% img = (sqrt(img)-sqt_min).*255./(sqt_max-sqt_min);
img = sqrt(img).*255./(sqt_max);
elseif strcmp(data_type, 'range')
img_max = max(max(img));
if img_max <= 5.0
img_max = 5.0;
end
img=sqrt(abs(img)).*255./sqrt(img_max); %This line degrade the performance of SURF
end
if strcmp(value_type, 'int')
img = uint8(img);
end
% img=medfilt2(img, [fw fw]);
end
|
github
|
rising-turtle/slam_matlab-master
|
compensate_badpixel.m
|
.m
|
slam_matlab-master/Localization/compensate_badpixel.m
| 1,844 |
utf_8
|
f28d56efdbf5d1e06c25dd3f07945a90
|
% Compenstate the bad pixel with low confidence by median filter
% Date : 3/13/12
% Author : Soonhac Hong ([email protected])
function [img, x, y, z, c] = compensate_badpixel(img, x, y, z, c, confidence_cut_off)
e_index = c < confidence_cut_off;
for i = 1:size(img,1) % row
for j=1:size(img,2) % column
if e_index(i,j) == 1
start_i = i-1;
end_i = i+1;
start_j = j-1;
end_j = j+1;
point_i = 2;
point_j = 2;
if i == 1
start_i = i;
point_i = 1;
if j == 1
point_j = 1;
end
end
if i == size(img,1)
end_i = i;
if j == 1
point_j = 1;
end
end
if j == 1
start_j = j;
if i == 1
point_i = 1;
end
end
if j == size(img,2)
end_j = j;
if i == 1
point_i = 1;
end
end
img_unit=medfilt2(img(start_i:end_i,start_j:end_j), [3 3],'symmetric');
x_unit=medfilt2(x(start_i:end_i,start_j:end_j), [3 3],'symmetric');
y_unit=medfilt2(y(start_i:end_i,start_j:end_j), [3 3],'symmetric');
z_unit=medfilt2(z(start_i:end_i,start_j:end_j), [3 3],'symmetric');
img(i,j) = img_unit(point_i,point_j);
x(i,j) = x_unit(point_i,point_j);
y(i,j) = y_unit(point_i,point_j);
z(i,j) = z_unit(point_i,point_j);
end
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
check_stored_depth_feature.m
|
.m
|
slam_matlab-master/Localization/check_stored_depth_feature.m
| 812 |
utf_8
|
a037ad501e066d47ebf04737a0196091
|
% Check if there is the stored visual feature
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function [exist_flag] = check_stored_depth_feature(data_name, dm, cframe)
exist_flag = 0;
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
dataset_dir = strrep(prefix, '/d1','');
dataset_dir = sprintf('%s/depth_feature',dataset_dir);
file_name = sprintf('d1_%04d.mat',cframe);
dirData = dir(dataset_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
if isempty(file_list)
return;
else
for i=1:size(file_list,1)
if strcmp(file_list{i}, file_name)
exist_flag = 1;
break;
end
end
end
dirData=[];
dirIndex=[];
file_list=[];
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_icp2_cov_fast.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_icp2_cov_fast.m
| 17,406 |
utf_8
|
b03f8f6fe4f24a2e9865f15785efe46f
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 8/30/12
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_icp2_cov_fast(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, icp_mode, dis)
if nargin < 14
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') % Dynamic data
cframe = sframe;
else
cframe = j;
end
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type);
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
%[frm1,des1] = vl_sift(single(img1)) ;
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe);
end
%Read second Data set
if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature')% Dynamic data
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
if check_stored_visual_feature(data_name, dm, cframe) == 0
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type);
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
%[frm2,des2] = vl_sift(single(img2)) ;
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe);
end
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%[match, scores] = vl_ubcmatch(des1,des2) ;
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% Eliminate pairwises which have zero in depth image of kinect or less 100 gray level in image of SR4000
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if img1(ROW1, COL1) >= 0 && img2(ROW2, COL2) >= 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
% stdev_threshold = 0.1;
% stdev_count = 0;
% count_threshold = 15;
% mean_threshold = 0.1;
% mean_count = 0;
% window_size = 30;
% debug_data=[];
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% if cnum >= valid_ransac
% break;
% end
% if cnum/pnum >= inlier_ratio
% break;
% enddynamic_data_index
% total_cnum(i)=cnum;
% if i > window_size && inliers_std ~= 0
% inliers_std_prev = inliers_std;
% inliers_std = std(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_std_delta = abs(inliers_std - inliers_std_prev)/inliers_std_prev;
%
% inliers_mean_prev = inliers_mean;
% inliers_mean = mean(total_cnum(i-window_size:i)); %Moving STDEV
% inliers_mean_delta = abs(inliers_mean - inliers_mean_prev)/inliers_mean_prev;
%
% if inliers_std_delta < stdev_threshold
% stdev_count = stdev_count + 1;
% else
% stdev_count = 0;
% end
%
% if inliers_mean_delta < mean_threshold
% mean_count = mean_count + 1;
% else
% mean_count = 0;
% end
%
% inlier_ratio = max(total_cnum)/pnum;
% % count_threshold = 120000 / ((inlier_ratio*100)^2); %-26 * (inlier_ratio*100 - 20) + 800;
%
% if stdev_count > count_threshold %&& mean_count > count_threshold
% break;
% end
% else
% inliers_std = std(total_cnum);
% inliers_mean = mean(total_cnum);
% end
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%% Run SVD
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Test LM
%[rot_lm, trans_lm] = lm_point(op_pset1, op_pset2);
% [rot_lm, trans_lm] = lm_point2plane(op_pset1, op_pset2);
% [phi_lm, theta_lm, psi_lm] = rot_to_euler(rot_lm);
% [theta*180/pi theta_lm*180/pi]
% [phi*180/pi phi_lm*180/pi]
% [psi*180/pi psi_lm*180/pi]
% Save feature points
%feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
% Compute RMSE
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse = rmse + unit_rmse;
% end
% rmse_feature = rmse / size(op_pset1,2);
%rmse_feature = rms_error(op_pset1, op_pset2_transed);
% Show correspondent points
% plot3(op_pset1(1,:),op_pset1(2,:),op_pset1(3,:),'b*-');
% hold on;
% plot3(op_pset2(1,:),op_pset2(2,:),op_pset2(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
%Compute the elapsed time
%rt_total = etime(clock,t);
%elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
%% Run ICP
%[phi_icp, theta_icp, psi_icp, trans_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_2(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_3(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_4(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_5(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
if strcmp(icp_mode, 'icp_ch')
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_9_cov_tol_batch(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
else
[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error, pose_std] = vro_icp_6_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2);
end
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_10(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%[phi_icp, theta_icp, psi_icp, trans_icp, rmse_icp, match_num, elapsed_icp, sta_icp, error] = vro_icp_13(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, x2, y2, z2, img2);
%Check status of SVD
if sta_icp == 0 || error ~= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
elseif sta_icp == 2
fprintf('Points are in co-planar.\n');
error=4;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%elapsed_icp = toc(t_icp);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; elapsed_icp(5)];
%rot = rot_icp;
% [rmse_feature rmse_icp]
% [theta*180/pi theta_icp*180/pi]
% [trans(1) trans_icp(1)]
%if rmse_icp <= rmse_feature
trans = trans_icp;
phi = phi_icp;
theta = theta_icp;
psi = psi_icp;
%end
%convert degree
% r2d=180.0/pi;
% phi=phi*r2d;
% theta=theta*r2d;
% psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
LoadKinect_depthbased.m
|
.m
|
slam_matlab-master/Localization/LoadKinect_depthbased.m
| 2,589 |
utf_8
|
eda775a4e73610c0ffdbdb3d7c327da6
|
% Load data from Kinect
%
% Parameters
% data_name : the directory name of data
% dm : index of directory of data
% j : index of frame
%
% Author : Soonhac Hong ([email protected])
% Date : 4/20/11
function [img, X, Y, Z, rtime, depth_time_stamp] = LoadKinect_depthbased(dm, j)
t_load = tic;
dir_name_list = get_kinect_tum_dir_name();
dir_name = dir_name_list{dm};
% Load depth image
[depth_data_dir, err] = sprintf('D:/Soonhac/Data/kinect_tum/%s/depth',dir_name);
dirData = dir(depth_data_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
[file_name_full, err]=sprintf('%s/%s',depth_data_dir,file_list{j});
[file_name, err] = sprintf('%s',file_list{j});
depth_time_stamp = str2double(strrep(file_name, '.png',''));
depth_img = imread(file_name_full);
%figure;imshow(depth_img);
depth_img = double(depth_img);
[rgb_data_dir, err] = sprintf('D:/Soonhac/Data/kinect_tum/%s/rgb',dir_name);
dirData = dir(rgb_data_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
for i=1:size(file_list,1)
[color_file_name, err]=sprintf('%s',file_list{i});
color_time_stamp(i,1) = str2double(strrep(color_file_name, '.png',''));
end
% find nearest tiem stamp of color image
color_file_nearest_index = find(color_time_stamp > depth_time_stamp, 1);
if color_file_nearest_index ~= 1 && ((color_time_stamp(color_file_nearest_index,1) - depth_time_stamp) > (depth_time_stamp - color_time_stamp(color_file_nearest_index-1,1)))
color_file_nearest_index = color_file_nearest_index - 1;
end
[file_name, err]=sprintf('%s/%s',rgb_data_dir,file_list{color_file_nearest_index});
rgb_img = imread(file_name);
img = rgb2gray(rgb_img);
%figure;imshow(rgb_img);
%figure;imshow(img);
%Noise reduction by Gaussian filter
gaussian_h = fspecial('gaussian',[3 3],1);
img=imfilter(img, gaussian_h,'replicate');
fx = 525.0; %# focal length x
fy = 525.0; %# focal length y
cx = 319.5; %# optical center x
cy = 239.5; %# optical center y
ds = 1.0; %# depth scaling
factor = 5000.0; %# for the 16-bit PNG files
%# OR: factor = 1 %# for the 32-bit float images in the ROS bag files
for v=1:size(depth_img,1) %height
for u=1:size(depth_img,2) %width
z = (depth_img(v,u) / factor) * ds;
x = (u - cx) * z / fx;
y = (v - cy) * z / fy;
X(v,u) = x;
Y(v,u) = y;
Z(v,u) = z;
end
end
rtime = toc(t_load);
%figure;imagesc(X);
%figure;imagesc(Y);
%figure;imagesc(Z);
end
|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_9_cov.m
|
.m
|
slam_matlab-master/Localization/vro_icp_9_cov.m
| 10,624 |
utf_8
|
e5d049b0e1df183d4947e039b8a2e8bf
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
% ICP6 + convexhull = ICP9
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_9_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
if size(op_pset1,2) < 10
fprintf('Error in less point for convex hull.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% compute 3D convex hull
t_convex = tic;
convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
convexhull_1_x =[];
convexhull_1_y =[];
convexhull_1_z =[];
for i=1:size(convexhull_1,1)
for j=1:3
convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
end
end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z,'d-');
% grid;
% axis equal;
%draw_data = [convexhull_1_x' convexhull_1_y' convexhull_1_z'];
%mesh(draw_data);
%M = op_pset1;
%D = op_pset2;
M_k = 1;
D_k = 1;
M=[];
D=[];
convex_check = 1; % check convex hull
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M_test = [-x1(i,j) z1(i,j) y1(i,j)];
M_in_flag = inhull(M_test,op_pset1',convexhull_1);
D_test = [-x2(i,j) z2(i,j) y2(i,j)];
D_in_flag = inhull(D_test,op_pset2',convexhull_2);
if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
M_k = M_k + 1;
end
end
if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
D_k = D_k + 1;
end
end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
end
end
elapsed_convex = toc(t_convex);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
pose_std = pose_std';
M = [];
D = [];
pt1 = [];
pt2 = [];
op_pset1_icp = [];
op_pset2_icp = [];
tree = [];
end
|
github
|
rising-turtle/slam_matlab-master
|
check_stored_visual_feature.m
|
.m
|
slam_matlab-master/Localization/check_stored_visual_feature.m
| 1,230 |
utf_8
|
08b710330ed346960fc4aa626de7a5d7
|
% Check if there is the stored visual feature
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function [exist_flag] = check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name)
exist_flag = 0;
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
file_name = sprintf('d1_%04d.mat',cframe);
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
file_name = sprintf('d%d_%04d.mat',dm,cframe);
end
if strcmp(image_name, 'depth')
dataset_dir = sprintf('%s/depth_feature',dataset_dir);
else
dataset_dir = sprintf('%s/visual_feature',dataset_dir);
end
%file_name = sprintf('d1_%04d.mat',cframe);
dirData = dir(dataset_dir); %# Get the data for the current directory
dirIndex = [dirData.isdir]; %# Find the index for directories
file_list = {dirData(~dirIndex).name}';
if isempty(file_list)
return;
else
for i=1:size(file_list,1)
if strcmp(file_list{i}, file_name)
exist_flag = 1;
break;
end
end
end
end
|
github
|
rising-turtle/slam_matlab-master
|
localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_svde6.m
|
.m
|
slam_matlab-master/Localization/localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_svde6.m
| 17,644 |
utf_8
|
59d68df885879e92e4bb12165cf177a0
|
% This function computes the pose of the sensor between two data set from
% SR400 using SIFT . The orignial function was vot.m in the ASEE/pitch_4_plot1.
%
% Parameters :
% dm : number of prefix of directory containing the first data set.
% inc : relative number of prefix of directory containing the second data set.
% The number of prefix of data set 2 will be dm+inc.
% j : index of frame for data set 1 and data set 2
% dis : index to display logs and images [1 = display][0 = no display]
%
% Author : Soonhac Hong ([email protected])
% Date : 3/10/11
% localization_sift_ransac_limit + covariance
% No bad pixel compensation
function [phi, theta, psi, trans, error, elapsed, match_num, feature_points, pose_std] = localization_sift_ransac_limit_cov_fast_fast_dist2_nobpc_svde6(image_name, data_name, filter_name, boarder_cut_off, ransac_iteration_limit, valid_ransac, scale, value_type, dm, inc, j, sframe, sequence_data, is_10M_data, dis)
if nargin < 15
dis = 0;
end
%Initilize parameters
error = 0;
sift_threshold = 0;
%t = clock;
%Read first data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
cframe = sframe;
else
cframe = j;
end
first_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img1, x1, y1, z1, elapsed_pre] = LoadKinect(dm, cframe);
[img1, x1, y1, z1, elapsed_pre, time_stamp1] = LoadKinect_depthbased(dm, cframe);
else
[img1, x1, y1, z1, c1, elapsed_pre] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img1 = scale_img(z1, 1, value_type,'range');
end
if dis == 1
f1 = figure(4); imagesc(img1); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift = tic;
[frm1, des1] = sift(img1, 'Verbosity', 1);
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
plotsiftframe(frm1);
else
%t_sift = clock;
t_sift = tic;
if sift_threshold == 0
[frm1, des1] = sift(img1);
else
[frm1, des1] = sift(img1, 'threshold', sift_threshold);
end
%elapsed_sift = etime(clock,t_sift);
elapsed_sift = toc(t_sift);
end
% confidence filtering
[frm1, des1] = confidence_filtering(frm1, des1, c1);
save_visual_features(data_name, dm, cframe, frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre, sequence_data, image_name);
else
[frm1, des1, elapsed_sift, img1, x1, y1, z1, c1, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
end
%Read second Data set
%if strcmp(data_name, 'm') || strcmp(data_name, 'etas') || strcmp(data_name, 'loops') || strcmp(data_name, 'kinect_tum') || strcmp(data_name, 'loops2') || strcmp(data_name, 'sparse_feature') || strcmp(data_name, 'swing') % Dynamic data
if sequence_data == true
%cframe = j + sframe;
%cframe = sframe+1;
cframe = sframe + j; % Generate constraints
else
dm=dm+inc;
cframe = j;
end
second_cframe = cframe;
if check_stored_visual_feature(data_name, dm, cframe, sequence_data, image_name) == 0
if strcmp(data_name, 'kinect_tum')
%[img2, x2, y2, z2, elapsed_pre2] = LoadKinect(dm, cframe);
[img2, x2, y2, z2, elapsed_pre2, time_stamp2] = LoadKinect_depthbased(dm, cframe);
else
[img2, x2, y2, z2, c2, elapsed_pre2] = LoadSR_no_bpc(data_name, filter_name, boarder_cut_off, dm, cframe, scale, value_type);
end
if strcmp(image_name, 'depth') %image_name == 'depth'
%Assign depth image to img1
img2 = scale_img(z2, 1, value_type, 'range');
end
if dis == 1
f2=figure(5); imagesc(img2); colormap(gray); title(['frame ', int2str(j)]);
%t_sift = clock;
t_sift2 = tic;
[frm2, des2] = sift(img2, 'Verbosity', 1);
%elapsed_sift2 = etime(clock, t_sift);
elapsed_sift2 = toc(t_sift2);
plotsiftframe(frm2);
else
%t_sift = clock;
t_sift2 = tic;
if sift_threshold == 0
[frm2, des2] = sift(img2);
else
[frm2, des2] = sift(img2,'threshold', sift_threshold);
end
%elapsed_sift2 = etime(clock,t_sift);
elapsed_sift2 = toc(t_sift2);
end
% confidence filtering
[frm2, des2] = confidence_filtering(frm2, des2, c2);
save_visual_features(data_name, dm, cframe, frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2, sequence_data, image_name);
else
[frm2, des2, elapsed_sift2, img2, x2, y2, z2, c2, elapsed_pre2] = load_visual_features(data_name, dm, cframe, sequence_data, image_name);
end
if check_stored_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
%t_match = clock;
t_match = tic;
match = siftmatch(des1, des2);
%elapsed_match = etime(clock,t_match);
elapsed_match = toc(t_match);
if dis == 1
f3=figure(6);
plotmatches(img1,img2,frm1,frm2,match); title('Match of SIFT');
end
% distance filtering
if is_10M_data == 1
valid_dist_max = 8; % 5m
else
valid_dist_max = 5; % 5m
end
valid_dist_min = 0.8; % 0.8m
match_new = [];
cnt_new = 1;
pnum = size(match, 2);
intensity_threshold = 0;
if strcmp(data_name, 'kinect_tum')
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
if z1(ROW1, COL1) > 0 && z2(ROW2, COL2) > 0
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
else
for i=1:pnum
frm1_index=match(1, i); frm2_index=match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
temp_pt1=[-x1(ROW1, COL1), z1(ROW1, COL1), y1(ROW1, COL1)];
temp_pt2=[-x2(ROW2, COL2), z2(ROW2, COL2), y2(ROW2, COL2)];
temp_pt1_dist = sqrt(sum(temp_pt1.^2));
temp_pt2_dist = sqrt(sum(temp_pt2.^2));
if temp_pt1_dist >= valid_dist_min && temp_pt1_dist <= valid_dist_max && temp_pt2_dist >= valid_dist_min && temp_pt2_dist <= valid_dist_max
%if img1(ROW1, COL1) >= intensity_threshold && img2(ROW2, COL2) >= intensity_threshold
match_new(:,cnt_new) = match(:,i);
cnt_new = cnt_new + 1;
end
end
end
match = match_new;
%find the matched two point sets.
%match = [4 6 21 18; 3 7 19 21];
pnum = size(match, 2);
if pnum <= 12 % 39
fprintf('too few sift points for ransac.\n');
error=1;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; 0];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; 0];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
else
%t_ransac = clock; %cputime;
t_ransac = tic;
%Eliminate outliers by geometric constraints
% for i=1:pnum
% frm1_index=match(1, i); frm2_index=match(2, i);
% matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1)); ROW1=round(matched_pix1(2));
% matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1)); ROW2=round(matched_pix2(2));
% pset1(1,i)=-x1(ROW1, COL1); pset1(2,i)=z1(ROW1, COL1); pset1(3,i)=y1(ROW1, COL1);
% pset2(1,i)=-x2(ROW2, COL2); pset2(2,i)=z2(ROW2, COL2); pset2(3,i)=y2(ROW2, COL2);
% pset1_index(1,i) = ROW1;
% pset1_index(2,i) = COL1;
% pset2_index(1,i) = ROW2;
% pset2_index(2,i) = COL2;
% end
%
% [match] = gc_distance(match, pset1,pset2);
%
% Eliminate outlier by confidence map
% [match] = confidence_filter(match, pset1_index, pset2_index, c1, c2);
if ransac_iteration_limit ~= 0
% Fixed Iteration limit
% rst = min(700, nchoosek(pnum, 4));
rst = min(ransac_iteration_limit, nchoosek(pnum, 4));
% rst = nchoosek(pnum, 4);
% valid_ransac = 3;
% stdev_threshold = 0.5;
% stdev_threshold_min_iteration = 30;
tmp_nmatch=zeros(2, pnum, rst);
for i=1:rst
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
% total_cnum(i)=cnum;
% inliers_std = std(total_cnum);
% if i > stdev_threshold_min_iteration && inliers_std < stdev_threshold
% break;
% end
end
else
%Standard termination criterion
inlier_ratio = 0.15; % 14 percent
% valid_ransac = 3; %inlier_ratio * pnum;
i=0;
eta_0 = 0.01; % 99 percent confidence
cur_p = 4 / pnum;
eta = (1-cur_p^4)^i;
ransac_error = 0;
max_iteration = 120000;
while eta > eta_0
% t_ransac_internal = clock; %cputime;
i = i+1;
[n_match, rs_match, cnum] = ransac(frm1, frm2, match, x1, y1, z1, x2, y2, z2, data_name);
% [n_match, rs_match, cnum] = ransac_3point(frm1, frm2, match, x1, y1, z1, x2, y2, z2);
%ct_internal = cputime - t_ransac_internal;
% ct_internal = etime(clock, t_ransac_internal);
for k=1:cnum
tmp_nmatch(:,k,i) = n_match(:,k);
end
tmp_rsmatch(:, :, i) = rs_match; tmp_cnum(i) = cnum;
if cnum ~= 0
cur_p = cnum/pnum;
eta = (1-cur_p^4)^i;
end
if i > max_iteration
ransac_error = 1;
break;
end
% debug_data(i,:)=[cnum, cur_p, eta, ct_internal];
end
ransac_iteration = i;
end
[rs_max, rs_ind] = max(tmp_cnum);
op_num = tmp_cnum(rs_ind);
if(op_num<valid_ransac || ransac_error == 1)
fprintf('no consensus found, ransac fails.\n');
error=2;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
match_num = [pnum; op_num];
%rt_total = etime(clock,t);
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
for k=1:op_num
op_match(:, k) = tmp_nmatch(:, k, rs_ind);
end
if dis == 1
f4=figure(7); plotmatches(img1,img2,frm1,frm2,tmp_rsmatch(:,:,rs_ind)); title('Feature points for RANSAC');
f5=figure(8); plotmatches(img1,img2,frm1,frm2,op_match); title('Match after RANSAC');
f6=figure(9); plotmatches_multi(img1,img2,frm1,frm2,op_match,match); title('Match after SIFT');
end
%elapsed_ransac = etime(clock, t_ransac); %cputime - t_ransac;
elapsed_ransac = toc(t_ransac);
match_num = [pnum; op_num];
end
%t_svd = clock;
t_svd = tic;
op_pset_cnt = 1;
for i=1:op_num
frm1_index=op_match(1, i); frm2_index=op_match(2, i);
matched_pix1=frm1(:, frm1_index); COL1=round(matched_pix1(1))+1; ROW1=round(matched_pix1(2))+1;
matched_pix2=frm2(:, frm2_index); COL2=round(matched_pix2(1))+1; ROW2=round(matched_pix2(2))+1;
op_pset1_image_index(i,:) = [matched_pix1(1), matched_pix1(2)]; %[COL1, ROW1];
op_pset2_image_index(i,:) = [matched_pix2(1), matched_pix2(2)]; %[COL2, ROW2];
if strcmp(data_name, 'kinect_tum')
%op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=-y1(ROW1, COL1);
%op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=-y2(ROW2, COL2);
op_pset1(1,op_pset_cnt)=x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=y1(ROW1, COL1); op_pset1(3,op_pset_cnt)=z1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=y2(ROW2, COL2); op_pset2(3,op_pset_cnt)=z2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
else
%if img1(ROW1, COL1) >= 100 && img2(ROW2, COL2) >= 100
op_pset1(1,op_pset_cnt)=-x1(ROW1, COL1); op_pset1(2,op_pset_cnt)=z1(ROW1, COL1); op_pset1(3,op_pset_cnt)=y1(ROW1, COL1);
op_pset2(1,op_pset_cnt)=-x2(ROW2, COL2); op_pset2(2,op_pset_cnt)=z2(ROW2, COL2); op_pset2(3,op_pset_cnt)=y2(ROW2, COL2);
op_pset_cnt = op_pset_cnt + 1;
%end
end
% op_pset1(1,i)=x1(ROW1, COL1); op_pset1(2,i)=y1(ROW1, COL1); op_pset1(3,i)=z1(ROW1, COL1);
% op_pset2(1,i)=x2(ROW2, COL2); op_pset2(2,i)=y2(ROW2, COL2); op_pset2(3,i)=z2(ROW2, COL2);
end
save_matched_points(data_name, dm, first_cframe, second_cframe, match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2, 'none', sequence_data);
else
[match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
t_svd = tic;
end
%[op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index] = check_feature_distance(op_pset1, op_pset2, op_pset_cnt, op_pset1_image_index, op_pset2_image_index);
%[rot, trans, sta] = find_transform_matrix(op_pset1, op_pset2);
[rot, trans, sta] = find_transform_matrix_e6(op_pset1, op_pset2);
[phi, theta, psi] = rot_to_euler(rot);
%elapsed_svd = etime(clock, t_svd);
elapsed_svd = toc(t_svd);
%Check status of SVD
if sta <= 0 % No Solution
fprintf('no solution in SVD.\n');
error=3;
phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
elapsed_ransac = 0.0;
elapsed_svd = 0.0;
%elapsed_icp = 0.0;
%match_num = [pnum; gc_num; op_num];
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
feature_points = [];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
% elseif sta == 2
% fprintf('Points are in co-planar.\n');
% error=4;
% phi=0.0; theta=0.0; psi=0.0; trans=[0.0; 0.0; 0.0];
% elapsed_ransac = 0.0;
% elapsed_svd = 0.0;
% %elapsed_icp = 0.0;
% %match_num = [pnum; gc_num; op_num];
% elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
% feature_points = [];
% pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
% return;
end
% Save feature points
%feature_points_1 =[repmat(1,[op_num 1]) op_pset1'];
%feature_points_2 =[repmat(2,[op_num 1]) op_pset2'];
feature_points_1 =[repmat(1,[op_pset_cnt-1 1]) op_pset1' op_pset1_image_index];
feature_points_2 =[repmat(2,[op_pset_cnt-1 1]) op_pset2' op_pset2_image_index];
feature_points = [feature_points_1; feature_points_2];
%Compute the elapsed time
%rt_total = etime(clock,t);
if strcmp(data_name, 'kinect_tum')
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; time_stamp1; ransac_iteration];
else
elapsed = [elapsed_pre; elapsed_sift; elapsed_pre2; elapsed_sift2; elapsed_match; elapsed_ransac; elapsed_svd; ransac_iteration];
end
%Compute covariane
if check_stored_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data) == 0
[pose_std] = compute_pose_std(op_pset1,op_pset2, rot, trans);
pose_std = pose_std';
save_pose_std(data_name, dm, first_cframe, second_cframe, pose_std, 'none', sequence_data);
else
[pose_std] = load_pose_std(data_name, dm, first_cframe, second_cframe, 'none', sequence_data);
end
%convert degree
%r2d=180.0/pi;
%phi=phi*r2d;
%theta=theta*r2d;
%psi=psi*r2d;
%trans';
end
|
github
|
rising-turtle/slam_matlab-master
|
check_feature_distance_icp.m
|
.m
|
slam_matlab-master/Localization/check_feature_distance_icp.m
| 781 |
utf_8
|
04b938571127b8ecb8e8139ba603a597
|
% Check the distance of feaure points
%
% Author : Soonhac Hong ([email protected])
% Date : 4/5/13
function [op_pset1, op_pset2] = check_feature_distance_icp(op_pset1, op_pset2)
distance_min = 0.8;
distance_max = 5;
op_pset1_distance = sqrt(sum(op_pset1.^2));
op_pset2_distance = sqrt(sum(op_pset2.^2));
op_pset1_distance_flag = (op_pset1_distance < distance_min | op_pset1_distance > distance_max);
op_pset2_distance_flag = (op_pset2_distance < distance_min | op_pset2_distance > distance_max);
%debug
% if sum(op_pset1_distance_flag) > 0 || sum(op_pset2_distance_flag) > 0
% disp('Distance filter is working');
% end
op_pset1(:, op_pset1_distance_flag)=[]; % delete invalid feature points
op_pset2(:, op_pset2_distance_flag)=[]; % delete invalid feature points
end
|
github
|
rising-turtle/slam_matlab-master
|
load_visual_features.m
|
.m
|
slam_matlab-master/Localization/load_visual_features.m
| 1,115 |
utf_8
|
b287b4545e4f246bec0e76880f2e3716
|
% Load sift visual feature from a file
%
% Author : Soonhac Hong ([email protected])
% Date : 2/13/2013
function [frm, des, elapsed_sift, img, x, y, z, c, elapsed_pre] = load_visual_features(data_name, dm, cframe, sequence_data, image_name)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
if strcmp(image_name, 'depth')
file_name = sprintf('%s/depth_feature/d1_%04d.mat',dataset_dir, cframe);
else
file_name = sprintf('%s/visual_feature/d1_%04d.mat',dataset_dir, cframe);
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
if strcmp(image_name, 'depth')
file_name = sprintf('%s/depth_feature/d%d_%04d.mat',dataset_dir, dm, cframe);
else
file_name = sprintf('%s/visual_feature/d%d_%04d.mat',dataset_dir, dm, cframe);
end
end
%file_name = sprintf('%s/visual_feature/d1_%04d.mat',dataset_dir, cframe);
load(file_name);
end
|
github
|
rising-turtle/slam_matlab-master
|
load_matched_points.m
|
.m
|
slam_matlab-master/Localization/load_matched_points.m
| 950 |
utf_8
|
1a99af336cb68c960b51337530b7259d
|
% Load matched points from a file
%
% Author : Soonhac Hong ([email protected])
% Date : 3/11/2013
function [match_num, ransac_iteration, op_pset1_image_index, op_pset2_image_index, op_pset_cnt, elapsed_match, elapsed_ransac, op_pset1, op_pset2] = load_matched_points(data_name, dm, first_cframe, second_cframe, isgframe, sequence_data)
[prefix, confidence_read] = get_sr4k_dataset_prefix(data_name, dm);
if sequence_data == true
if strcmp(data_name, 'object_recognition')
dataset_dir = strrep(prefix, '/f1','');
else
dataset_dir = strrep(prefix, '/d1','');
end
else
dataset_dir = prefix(1:max(strfind(prefix,sprintf('/d%d',dm)))-1);
end
if strcmp(isgframe, 'gframe')
file_name = sprintf('%s/matched_points_gframe/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
else
file_name = sprintf('%s/matched_points/d1_%04d_%04d.mat',dataset_dir, first_cframe, second_cframe);
end
load(file_name);
end
|
github
|
rising-turtle/slam_matlab-master
|
vro_icp_6_cov.m
|
.m
|
slam_matlab-master/Localization/vro_icp_6_cov.m
| 10,511 |
utf_8
|
641524042e16a232c87308d355249f26
|
% This function compute the transformation of two 3D point clouds by ICP
%
% Parameters :
%
% Author : Soonhac Hong ([email protected])
% Date : 9/20/12
function [phi_icp, theta_icp, psi_icp, trans_icp, match_rmse, match_num, elapsed_time, sta_icp, error, pose_std] = vro_icp_6_cov(op_pset1, op_pset2, rot, trans, x1, y1, z1, img1, c1, x2, y2, z2, img2, c2)
error = 0;
sta_icp = 1;
t_icp = tic;
% test for local minimum in optimization
%trans = [0; 0; 0];
%rot = euler_to_rot(0, 27, 0);
% if size(op_pset1,2) < 5
% fprintf('Error in less point for convex hull.\n');
% error=6;
% phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
% elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
% match_rmse = 0.0;
% match_num = [0; 0];
% return;
% end
% compute 3D convex hull
t_convex = tic;
% convexhull_1 = convhulln(op_pset1',{'Qt','Pp'});
% convexhull_2 = convhulln(op_pset2',{'Qt','Pp'});
% %show convexhull
% convexhull_1_x =[];
% convexhull_1_y =[];
% convexhull_1_z =[];
%
% for i=1:size(convexhull_1,1)
% for j=1:3
% convexhull_1_x = [convexhull_1_x op_pset1(1,convexhull_1(i,j))];
% convexhull_1_y = [convexhull_1_y op_pset1(2,convexhull_1(i,j))];
% convexhull_1_z = [convexhull_1_z op_pset1(3,convexhull_1(i,j))];
% end
% end
% plot3(convexhull_1_x, convexhull_1_y, convexhull_1_z);
%M = op_pset1;
%D = op_pset2;
M_k = 1;
D_k = 1;
M=[];
D=[];
convex_check = 0; % check convex hull
max_confidence_1 = max(c1(:));
max_confidence_2 = max(c2(:));
threshold = 0.5;
confidence_thresh_1 = threshold * max_confidence_1;
confidence_thresh_2 = threshold * max_confidence_2;
%Initialize data by trans
subsampling_factor = 2;
h_border_cutoff = round(size(x1,2)*0.1/2);
v_border_cutoff = round(size(x1,1)*0.1/2);
for i=1+v_border_cutoff:subsampling_factor:size(x1,1)-v_border_cutoff
for j=1+h_border_cutoff:subsampling_factor:size(x1,2)-h_border_cutoff
M_test = [-x1(i,j) z1(i,j) y1(i,j)];
% M_in_flag = inhull(M_test,op_pset1',convexhull_1);
D_test = [-x2(i,j) z2(i,j) y2(i,j)];
% D_in_flag = inhull(D_test,op_pset2',convexhull_2);
% if M_in_flag == 1 || convex_check == 0 % test point locates in the convex hull
%if img1(i,j) >= 50 %100 % intensity filtering for less noise
if c1(i,j) >= confidence_thresh_1 % confidence filtering
M(:,M_k) = M_test'; %[-x1(i,j); z1(i,j); y1(i,j)];
M_k = M_k + 1;
end
% end
% if D_in_flag == 1 || convex_check == 0
%if img2(i,j) >= 50 %100 % intensity filtering for less noise
if c2(i,j) >= confidence_thresh_2 % confidence filtering
D(:,D_k) = D_test'; %[-x2(i,j); z2(i,j); y2(i,j)];
D_k = D_k + 1;
end
% end
%temp_pt2 = [-x2(i,j); z2(i,j); y2(i,j)];
%D(:,k) = rot*temp_pt2 + trans;
%transed_pt1 = rot*temp_pt + trans;
%k = k + 1;
end
end
elapsed_convex = toc(t_convex);
ap_size=size(M,2);
if isempty(M) || isempty(D)
fprintf('Error in less point for ICP.\n');
error=6;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num = [0; 0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
%t_icp = tic;
%[Ricp, Ticp, ER, t]=icp(M, D,'Minimize','plane');
%elapsed_icp = toc(t_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
%Transform data-matrix using ICP result
%Dicp = Ricp * D + repmat(Ticp, 1, n);
t_icp_icp = tic;
converged = 0;
rmse_total=[];
rot_total=[];
trans_total=[];
match_num_total=[];
while_cnt = 1;
while converged == 0
% find correspondent assoicate
Dicp = rot * D + repmat(trans, 1, size(D,2));
%p = rand( 20, 2 ); % input data (m x n); n dimensionality
%q = rand( 10, 2 ); % query data (d x n)
t_kdtree = tic;
pt1=[];
pt2=[];
if size(M,2) > size (D,2)
tree = kdtree_build( M' );
correspondent_idxs = kdtree_nearest_neighbor(tree, Dicp');
pt2 = D;
for i=1:size(correspondent_idxs,1)
pt1(:,i) = M(:,correspondent_idxs(i));
end
else
tree = kdtree_build( Dicp' );
correspondent_idxs = kdtree_nearest_neighbor(tree, M');
pt1 = M;
for i=1:size(correspondent_idxs,1)
pt2(:,i) = D(:,correspondent_idxs(i));
end
end
elapsed_kdtree = toc(t_kdtree);
%[R_icp, trans_icp, ER, t]=icp(pt1, pt2,'Minimize','plane','WorstRejection',0.1);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(R_icp);
% Outlier removal
% Compute error
t_icp_ransac = tic;
pt2_transed= rot * pt2 + repmat(trans, 1, size(pt2,2));
new_cnt = 1;
pt1_new=[];
pt2_new=[];
correspondent_idxs_new=[];
for i=1:size(pt1,2)
unit_rmse = sqrt(sum((pt2_transed(:,i) - pt1(:,i)).^2));
if unit_rmse < 0.03
pt1_new(:,new_cnt) = pt1(:,i);
pt2_new(:,new_cnt) = pt2(:,i);
correspondent_idxs_new(new_cnt) = correspondent_idxs(i);
new_cnt = new_cnt + 1;
end
end
pt1 = pt1_new;
pt2 = pt2_new;
correspondent_idxs = correspondent_idxs_new';
% Delete duplicates in correspondent points
% correspondent_unique = unique(correspondent_idxs);
% correspondent_unique_idx = ones(size(correspondent_idxs));
% for i=1:length(correspondent_unique)
% unit_idx = find(correspondent_idxs == correspondent_unique(i));
% if length(unit_idx) > 1
% correspondent_unique_idx(unit_idx)=0;
% end
% end
%
% correspondent_delete_idx=find(correspondent_unique_idx == 0);
% pt1(:,correspondent_delete_idx') = [];
% pt2(:,correspondent_delete_idx') = [];
% correspondent_idxs(correspondent_delete_idx,:) = [];
if isempty(pt1) || isempty(pt2)
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
match_num=[ap_size;0];
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
% op_pset1_icp = pt1_new;
% op_pset2_icp = pt2_new;
% elapsed_icp_ransac = toc(t_icp_ransac);
%
%t_icp_ransac = tic;
[op_match, match_num, rtime, error_ransac] = run_ransac_points(pt1, pt2, correspondent_idxs', 0);
if error_ransac ~= 0 % Error in RANSAC
fprintf('Error in RANSAC with additional points.\n');
error=5;
phi_icp = 0.0; theta_icp = 0.0; psi_icp = 0.0; trans_icp = [0.0; 0.0; 0.0];
elapsed_time = [0.0, 0.0, 0.0, 0.0, 0.0]; sta_icp = 0;
match_rmse = 0.0;
pose_std = [0.0; 0.0; 0.0; 0.0; 0.0; 0.0];
return;
end
op_pset1_icp = [];
op_pset2_icp = [];
for i=1:match_num(2)
op_pset1_icp(:,i) = pt1(:,op_match(1,i));
op_pset2_icp(:,i) = pt2(:,op_match(2,i));
end
elapsed_icp_ransac = toc(t_icp_ransac);
% SVD
t_svd_icp = tic;
%[rot_icp, trans_icp, sta_icp] = find_transform_matrix(op_pset1_icp, op_pset2_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
%elapsed_svd = etime(clock, t_svd);
sta_icp =1;
t_init = zeros(6,1);
[t_init(2), t_init(1), t_init(3)] = rot_to_euler(rot);
t_init(4:6) = trans;
[rot_icp, trans_icp] = lm_point(op_pset1_icp, op_pset2_icp, t_init);
%[rot_icp, trans_icp] = lm_point2plane(op_pset1, op_pset2, t_init);
elapsed_svd = toc(t_svd_icp);
% M = op_pset1_icp;
% D = op_pset2_icp;
rot = rot_icp;
trans = trans_icp;
rot_total(:,:,while_cnt) = rot;
trans_total(:,:,while_cnt) = trans;
match_num_total(while_cnt) = size(op_pset1_icp,2);
% Plot
% figure;
% plot3(op_pset1_icp(1,:),op_pset1_icp(2,:),op_pset1_icp(3,:),'b*-');
% hold on;
% plot3(op_pset2_icp(1,:),op_pset2_icp(2,:),op_pset2_icp(3,:),'ro-');
% xlabel('X');
% ylabel('Y');
% zlabel('Z');
% grid;
% hold off;
% Compute error
op_pset1_icp_normal = lsqnormest(op_pset1_icp,4);
op_pset2_icp_transed= rot * op_pset2_icp + repmat(trans, 1, size(op_pset2_icp,2));
% rmse_icp = 0;
% for i=1:size(M,2)
% unit_rmse = sqrt(sum((D_transed(:,i) - M(:,i)).^2)/3);
% rmse_icp = rmse_icp + unit_rmse;
% end
% rmse_icp = rmse_icp / size(M,2);
%rmse_icp = rms_error(op_pset1_icp, op_pset2_icp_transed);
rmse_icp = rms_error_normal(op_pset1_icp, op_pset2_icp_transed, op_pset1_icp_normal); % point-to-plain
op_pset2_transed= rot * op_pset2 + repmat(trans, 1, size(op_pset2,2));
% rmse_feature = 0;
% for i=1:size(op_pset1,2)
% unit_rmse = sqrt(sum((op_pset2_transed(:,i) - op_pset1(:,i)).^2)/3);
% rmse_feature = rmse_feature + unit_rmse;
% end
% rmse_feature = rmse_feature / size(op_pset1,2);
rmse_feature= rms_error(op_pset1,op_pset2_transed);
rmse_total = [rmse_total (rmse_icp+rmse_feature)/2];
%rmse_total = [rmse_total rmse_icp];
rmse_thresh = 0.001;
if length(rmse_total) > 3
rmse_diff = abs(diff(rmse_total));
rmse_diff_length = length(rmse_diff);
if rmse_diff(rmse_diff_length) < rmse_thresh && rmse_diff(rmse_diff_length-1) < rmse_thresh && rmse_diff(rmse_diff_length-2) < rmse_thresh
converged = 1;
end
end
while_cnt = while_cnt + 1;
end
[match_rmse match_rmse_idx] = min(rmse_total);
%match_rmse = rmse_total(end);
%match_rmse_idx = size(rmse_total,2);
match_num = [ap_size; match_num_total(match_rmse_idx)];
rot_icp = rot_total(:,:,match_rmse_idx);
trans_icp = trans_total(:,:,match_rmse_idx);
[phi_icp, theta_icp, psi_icp] = rot_to_euler(rot_icp);
elapsed_icp_icp = toc(t_icp_icp);
%t_icp_icp = tic;
%[Ricp, trans_icp, ER, t]=icp(op_pset1_icp, op_pset2_icp,'Minimize','plane');
%elapsed_icp_icp = toc(t_icp_icp);
%[phi_icp, theta_icp, psi_icp] = rot_to_euler(Ricp);
elapsed_icp = toc(t_icp);
elapsed_time = [elapsed_convex, elapsed_kdtree, elapsed_icp_ransac, elapsed_icp_icp, elapsed_icp];
%Compute covariane
[pose_std] = compute_pose_std(op_pset1_icp,op_pset2_icp, rot_icp, trans_icp);
pose_std = pose_std';
M = [];
D = [];
pt1 = [];
pt2 = [];
op_pset1_icp = [];
op_pset2_icp = [];
tree = [];
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.