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
|
siam1251/Fast-SeqSLAM-master
|
crop_borders.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/crop_borders.m
| 4,855 |
utf_8
|
28cc044092bcab4daa2a35a4434fa835
|
function [A, vA, vB, bb_rel] = crop_borders(A, bcol, padding, crop_amounts)
%CROP_BORDERS Crop the borders of an image or stack of images
%
% [B, vA, vB, bb_rel] = crop_borders(A, bcol, [padding])
%
%IN:
% A - HxWxCxN stack of images.
% bcol - Cx1 background colour vector.
% padding - scalar indicating how much padding to have in relation to
% the cropped-image-size (0<=padding<=1). Default: 0
% crop_amounts - 4-element vector of crop amounts: [top,right,bottom,left]
% where NaN/Inf indicate auto-cropping, 0 means no cropping,
% and any other value mean cropping in pixel amounts.
%
%OUT:
% B - JxKxCxN cropped stack of images.
% vA - coordinates in A that contain the cropped image
% vB - coordinates in B where the cropped version of A is placed
% bb_rel - relative bounding box (used for eps-cropping)
%{
% 06/03/15: Improved image cropping thanks to Oscar Hartogensis
% 08/06/15: Fixed issue #76: case of transparent figure bgcolor
% 21/02/16: Enabled specifying non-automated crop amounts
% 04/04/16: Fix per Luiz Carvalho for old Matlab releases
%}
if nargin < 3
padding = 0;
end
if nargin < 4
crop_amounts = nan(1,4); % =auto-cropping
end
crop_amounts(end+1:4) = NaN; % fill missing values with NaN
[h, w, c, n] = size(A);
if isempty(bcol) % case of transparent bgcolor
bcol = A(ceil(end/2),1,:,1);
end
if isscalar(bcol)
bcol = bcol(ones(c, 1));
end
% Crop margin from left
if ~isfinite(crop_amounts(4))
bail = false;
for l = 1:w
for a = 1:c
if ~all(col(A(:,l,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
l = 1 + abs(crop_amounts(4));
end
% Crop margin from right
if ~isfinite(crop_amounts(2))
bcol = A(ceil(end/2),w,:,1);
bail = false;
for r = w:-1:l
for a = 1:c
if ~all(col(A(:,r,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
r = w - abs(crop_amounts(2));
end
% Crop margin from top
if ~isfinite(crop_amounts(1))
bcol = A(1,ceil(end/2),:,1);
bail = false;
for t = 1:h
for a = 1:c
if ~all(col(A(t,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
t = 1 + abs(crop_amounts(1));
end
% Crop margin from bottom
bcol = A(h,ceil(end/2),:,1);
if ~isfinite(crop_amounts(3))
bail = false;
for b = h:-1:t
for a = 1:c
if ~all(col(A(b,:,a,:)) == bcol(a))
bail = true;
break;
end
end
if bail
break;
end
end
else
b = h - abs(crop_amounts(3));
end
if padding == 0 % no padding
if ~isequal([t b l r], [1 h 1 w]) % Check if we're actually croppping
padding = 1; % Leave one boundary pixel to avoid bleeding on resize
end
elseif abs(padding) < 1 % pad value is a relative fraction of image size
padding = sign(padding)*round(mean([b-t r-l])*abs(padding)); % ADJUST PADDING
else % pad value is in units of 1/72" points
padding = round(padding); % fix cases of non-integer pad value
end
if padding > 0 % extra padding
% Create an empty image, containing the background color, that has the
% cropped image size plus the padded border
B = repmat(bcol,[(b-t)+1+padding*2,(r-l)+1+padding*2,1,n]); % Fix per Luiz Carvalho
% vA - coordinates in A that contain the cropped image
vA = [t b l r];
% vB - coordinates in B where the cropped version of A will be placed
vB = [padding+1, (b-t)+1+padding, padding+1, (r-l)+1+padding];
% Place the original image in the empty image
B(vB(1):vB(2), vB(3):vB(4), :, :) = A(vA(1):vA(2), vA(3):vA(4), :, :);
A = B;
else % extra cropping
vA = [t-padding b+padding l-padding r+padding];
A = A(vA(1):vA(2), vA(3):vA(4), :, :);
vB = [NaN NaN NaN NaN];
end
% For EPS cropping, determine the relative BoundingBox - bb_rel
bb_rel = [l-1 h-b-1 r+1 h-t+1]./[w h w h];
end
function A = col(A)
A = A(:);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
isolate_axes.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/isolate_axes.m
| 4,851 |
utf_8
|
611d9727e84ad6ba76dcb3543434d0ce
|
function fh = isolate_axes(ah, vis)
%ISOLATE_AXES Isolate the specified axes in a figure on their own
%
% Examples:
% fh = isolate_axes(ah)
% fh = isolate_axes(ah, vis)
%
% This function will create a new figure containing the axes/uipanels
% specified, and also their associated legends and colorbars. The objects
% specified must all be in the same figure, but they will generally only be
% a subset of the objects in the figure.
%
% IN:
% ah - An array of axes and uipanel handles, which must come from the
% same figure.
% vis - A boolean indicating whether the new figure should be visible.
% Default: false.
%
% OUT:
% fh - The handle of the created figure.
% Copyright (C) Oliver Woodford 2011-2013
% Thank you to Rosella Blatt for reporting a bug to do with axes in GUIs
% 16/03/12: Moved copyfig to its own function. Thanks to Bob Fratantonio
% for pointing out that the function is also used in export_fig.m
% 12/12/12: Add support for isolating uipanels. Thanks to michael for suggesting it
% 08/10/13: Bug fix to allchildren suggested by Will Grant (many thanks!)
% 05/12/13: Bug fix to axes having different units. Thanks to Remington Reid for reporting
% 21/04/15: Bug fix for exporting uipanels with legend/colorbar on HG1 (reported by Alvaro
% on FEX page as a comment on 24-Apr-2014); standardized indentation & help section
% 22/04/15: Bug fix: legends and colorbars were not exported when exporting axes handle in HG2
% Make sure we have an array of handles
if ~all(ishandle(ah))
error('ah must be an array of handles');
end
% Check that the handles are all for axes or uipanels, and are all in the same figure
fh = ancestor(ah(1), 'figure');
nAx = numel(ah);
for a = 1:nAx
if ~ismember(get(ah(a), 'Type'), {'axes', 'uipanel'})
error('All handles must be axes or uipanel handles.');
end
if ~isequal(ancestor(ah(a), 'figure'), fh)
error('Axes must all come from the same figure.');
end
end
% Tag the objects so we can find them in the copy
old_tag = get(ah, 'Tag');
if nAx == 1
old_tag = {old_tag};
end
set(ah, 'Tag', 'ObjectToCopy');
% Create a new figure exactly the same as the old one
fh = copyfig(fh); %copyobj(fh, 0);
if nargin < 2 || ~vis
set(fh, 'Visible', 'off');
end
% Reset the object tags
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Find the objects to save
ah = findall(fh, 'Tag', 'ObjectToCopy');
if numel(ah) ~= nAx
close(fh);
error('Incorrect number of objects found.');
end
% Set the axes tags to what they should be
for a = 1:nAx
set(ah(a), 'Tag', old_tag{a});
end
% Keep any legends and colorbars which overlap the subplots
% Note: in HG1 these are axes objects; in HG2 they are separate objects, therefore we
% don't test for the type, only the tag (hopefully nobody but Matlab uses them!)
lh = findall(fh, 'Tag', 'legend', '-or', 'Tag', 'Colorbar');
nLeg = numel(lh);
if nLeg > 0
set([ah(:); lh(:)], 'Units', 'normalized');
try
ax_pos = get(ah, 'OuterPosition'); % axes and figures have the OuterPosition property
catch
ax_pos = get(ah, 'Position'); % uipanels only have Position, not OuterPosition
end
if nAx > 1
ax_pos = cell2mat(ax_pos(:));
end
ax_pos(:,3:4) = ax_pos(:,3:4) + ax_pos(:,1:2);
try
leg_pos = get(lh, 'OuterPosition');
catch
leg_pos = get(lh, 'Position'); % No OuterPosition in HG2, only in HG1
end
if nLeg > 1;
leg_pos = cell2mat(leg_pos);
end
leg_pos(:,3:4) = leg_pos(:,3:4) + leg_pos(:,1:2);
ax_pos = shiftdim(ax_pos, -1);
% Overlap test
M = bsxfun(@lt, leg_pos(:,1), ax_pos(:,:,3)) & ...
bsxfun(@lt, leg_pos(:,2), ax_pos(:,:,4)) & ...
bsxfun(@gt, leg_pos(:,3), ax_pos(:,:,1)) & ...
bsxfun(@gt, leg_pos(:,4), ax_pos(:,:,2));
ah = [ah; lh(any(M, 2))];
end
% Get all the objects in the figure
axs = findall(fh);
% Delete everything except for the input objects and associated items
delete(axs(~ismember(axs, [ah; allchildren(ah); allancestors(ah)])));
end
function ah = allchildren(ah)
ah = findall(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
end
function ph = allancestors(ah)
ph = [];
for a = 1:numel(ah)
h = get(ah(a), 'parent');
while h ~= 0
ph = [ph; h];
h = get(h, 'parent');
end
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
im2gif.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/im2gif.m
| 6,234 |
utf_8
|
8ee74d7d94e524410788276aa41dd5f1
|
%IM2GIF Convert a multiframe image to an animated GIF file
%
% Examples:
% im2gif infile
% im2gif infile outfile
% im2gif(A, outfile)
% im2gif(..., '-nocrop')
% im2gif(..., '-nodither')
% im2gif(..., '-ncolors', n)
% im2gif(..., '-loops', n)
% im2gif(..., '-delay', n)
%
% This function converts a multiframe image to an animated GIF.
%
% To create an animation from a series of figures, export to a multiframe
% TIFF file using export_fig, then convert to a GIF, as follows:
%
% for a = 2 .^ (3:6)
% peaks(a);
% export_fig test.tif -nocrop -append
% end
% im2gif('test.tif', '-delay', 0.5);
%
%IN:
% infile - string containing the name of the input image.
% outfile - string containing the name of the output image (must have the
% .gif extension). Default: infile, with .gif extension.
% A - HxWxCxN array of input images, stacked along fourth dimension, to
% be converted to gif.
% -nocrop - option indicating that the borders of the output are not to
% be cropped.
% -nodither - option indicating that dithering is not to be used when
% converting the image.
% -ncolors - option pair, the value of which indicates the maximum number
% of colors the GIF can have. This can also be a quantization
% tolerance, between 0 and 1. Default/maximum: 256.
% -loops - option pair, the value of which gives the number of times the
% animation is to be looped. Default: 65535.
% -delay - option pair, the value of which gives the time, in seconds,
% between frames. Default: 1/15.
% Copyright (C) Oliver Woodford 2011
function im2gif(A, varargin)
% Parse the input arguments
[A, options] = parse_args(A, varargin{:});
if options.crop ~= 0
% Crop
A = crop_borders(A, A(ceil(end/2),1,:,1));
end
% Convert to indexed image
[h, w, c, n] = size(A);
A = reshape(permute(A, [1 2 4 3]), h, w*n, c);
map = unique(reshape(A, h*w*n, c), 'rows');
if size(map, 1) > 256
dither_str = {'dither', 'nodither'};
dither_str = dither_str{1+(options.dither==0)};
if options.ncolors <= 1
[B, map] = rgb2ind(A, options.ncolors, dither_str);
if size(map, 1) > 256
[B, map] = rgb2ind(A, 256, dither_str);
end
else
[B, map] = rgb2ind(A, min(round(options.ncolors), 256), dither_str);
end
else
if max(map(:)) > 1
map = double(map) / 255;
A = double(A) / 255;
end
B = rgb2ind(im2double(A), map);
end
B = reshape(B, h, w, 1, n);
% Bug fix to rgb2ind
map(B(1)+1,:) = im2double(A(1,1,:));
% Save as a gif
imwrite(B, map, options.outfile, 'LoopCount', round(options.loops(1)), 'DelayTime', options.delay);
end
%% Parse the input arguments
function [A, options] = parse_args(A, varargin)
% Set the defaults
options = struct('outfile', '', ...
'dither', true, ...
'crop', true, ...
'ncolors', 256, ...
'loops', 65535, ...
'delay', 1/15);
% Go through the arguments
a = 0;
n = numel(varargin);
while a < n
a = a + 1;
if ischar(varargin{a}) && ~isempty(varargin{a})
if varargin{a}(1) == '-'
opt = lower(varargin{a}(2:end));
switch opt
case 'nocrop'
options.crop = false;
case 'nodither'
options.dither = false;
otherwise
if ~isfield(options, opt)
error('Option %s not recognized', varargin{a});
end
a = a + 1;
if ischar(varargin{a}) && ~ischar(options.(opt))
options.(opt) = str2double(varargin{a});
else
options.(opt) = varargin{a};
end
end
else
options.outfile = varargin{a};
end
end
end
if isempty(options.outfile)
if ~ischar(A)
error('No output filename given.');
end
% Generate the output filename from the input filename
[path, outfile] = fileparts(A);
options.outfile = fullfile(path, [outfile '.gif']);
end
if ischar(A)
% Read in the image
A = imread_rgb(A);
end
end
%% Read image to uint8 rgb array
function [A, alpha] = imread_rgb(name)
% Get file info
info = imfinfo(name);
% Special case formats
switch lower(info(1).Format)
case 'gif'
[A, map] = imread(name, 'frames', 'all');
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
A = permute(A, [1 2 5 4 3]);
end
case {'tif', 'tiff'}
A = cell(numel(info), 1);
for a = 1:numel(A)
[A{a}, map] = imread(name, 'Index', a, 'Info', info);
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A{a} = reshape(map(uint32(A{a})+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
end
if size(A{a}, 3) == 4
% TIFF in CMYK colourspace - convert to RGB
if isfloat(A{a})
A{a} = A{a} * 255;
else
A{a} = single(A{a});
end
A{a} = 255 - A{a};
A{a}(:,:,4) = A{a}(:,:,4) / 255;
A{a} = uint8(A(:,:,1:3) .* A{a}(:,:,[4 4 4]));
end
end
A = cat(4, A{:});
otherwise
[A, map, alpha] = imread(name);
A = A(:,:,:,1); % Keep only first frame of multi-frame files
if ~isempty(map)
map = uint8(map * 256 - 0.5); % Convert to uint8 for storage
A = reshape(map(uint32(A)+1,:), [size(A) size(map, 2)]); % Assume indexed from 0
elseif size(A, 3) == 4
% Assume 4th channel is an alpha matte
alpha = A(:,:,4);
A = A(:,:,1:3);
end
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
read_write_entire_textfile.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/read_write_entire_textfile.m
| 961 |
utf_8
|
775aa1f538c76516c7fb406a4f129320
|
%READ_WRITE_ENTIRE_TEXTFILE Read or write a whole text file to/from memory
%
% Read or write an entire text file to/from memory, without leaving the
% file open if an error occurs.
%
% Reading:
% fstrm = read_write_entire_textfile(fname)
% Writing:
% read_write_entire_textfile(fname, fstrm)
%
%IN:
% fname - Pathname of text file to be read in.
% fstrm - String to be written to the file, including carriage returns.
%
%OUT:
% fstrm - String read from the file. If an fstrm input is given the
% output is the same as that input.
function fstrm = read_write_entire_textfile(fname, fstrm)
modes = {'rt', 'wt'};
writing = nargin > 1;
fh = fopen(fname, modes{1+writing});
if fh == -1
error('Unable to open file %s.', fname);
end
try
if writing
fwrite(fh, fstrm, 'char*1');
else
fstrm = fread(fh, '*char')';
end
catch ex
fclose(fh);
rethrow(ex);
end
fclose(fh);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
pdf2eps.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/pdf2eps.m
| 1,522 |
utf_8
|
4c8f0603619234278ed413670d24bdb6
|
%PDF2EPS Convert a pdf file to eps format using pdftops
%
% Examples:
% pdf2eps source dest
%
% This function converts a pdf file to eps format.
%
% This function requires that you have pdftops, from the Xpdf suite of
% functions, installed on your system. This can be downloaded from:
% http://www.foolabs.com/xpdf
%
%IN:
% source - filename of the source pdf file to convert. The filename is
% assumed to already have the extension ".pdf".
% dest - filename of the destination eps file. The filename is assumed to
% already have the extension ".eps".
% Copyright (C) Oliver Woodford 2009-2010
% Thanks to Aldebaro Klautau for reporting a bug when saving to
% non-existant directories.
function pdf2eps(source, dest)
% Construct the options string for pdftops
options = ['-q -paper match -eps -level2 "' source '" "' dest '"'];
% Convert to eps using pdftops
[status, message] = pdftops(options);
% Check for error
if status
% Report error
if isempty(message)
error('Unable to generate eps. Check destination directory is writable.');
else
error(message);
end
end
% Fix the DSC error created by pdftops
fid = fopen(dest, 'r+');
if fid == -1
% Cannot open the file
return
end
fgetl(fid); % Get the first line
str = fgetl(fid); % Get the second line
if strcmp(str(1:min(13, end)), '% Produced by')
fseek(fid, -numel(str)-1, 'cof');
fwrite(fid, '%'); % Turn ' ' into '%'
end
fclose(fid);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
print2array.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/print2array.m
| 9,613 |
utf_8
|
e398a6296734121e6e1983a45298549a
|
function [A, bcol] = print2array(fig, res, renderer, gs_options)
%PRINT2ARRAY Exports a figure to an image array
%
% Examples:
% A = print2array
% A = print2array(figure_handle)
% A = print2array(figure_handle, resolution)
% A = print2array(figure_handle, resolution, renderer)
% A = print2array(figure_handle, resolution, renderer, gs_options)
% [A bcol] = print2array(...)
%
% This function outputs a bitmap image of the given figure, at the desired
% resolution.
%
% If renderer is '-painters' then ghostcript needs to be installed. This
% can be downloaded from: http://www.ghostscript.com
%
% IN:
% figure_handle - The handle of the figure to be exported. Default: gcf.
% resolution - Resolution of the output, as a factor of screen
% resolution. Default: 1.
% renderer - string containing the renderer paramater to be passed to
% print. Default: '-opengl'.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
%
% OUT:
% A - MxNx3 uint8 image of the figure.
% bcol - 1x3 uint8 vector of the background color
% Copyright (C) Oliver Woodford 2008-2014, Yair Altman 2015-
%{
% 05/09/11: Set EraseModes to normal when using opengl or zbuffer
% renderers. Thanks to Pawel Kocieniewski for reporting the issue.
% 21/09/11: Bug fix: unit8 -> uint8! Thanks to Tobias Lamour for reporting it.
% 14/11/11: Bug fix: stop using hardcopy(), as it interfered with figure size
% and erasemode settings. Makes it a bit slower, but more reliable.
% Thanks to Phil Trinh and Meelis Lootus for reporting the issues.
% 09/12/11: Pass font path to ghostscript.
% 27/01/12: Bug fix affecting painters rendering tall figures. Thanks to
% Ken Campbell for reporting it.
% 03/04/12: Bug fix to median input. Thanks to Andy Matthews for reporting it.
% 26/10/12: Set PaperOrientation to portrait. Thanks to Michael Watts for
% reporting the issue.
% 26/02/15: If temp dir is not writable, use the current folder for temp
% EPS/TIF files (Javier Paredes)
% 27/02/15: Display suggested workarounds to internal print() error (issue #16)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 10/03/15: Fixed minor warning reported by Paul Soderlind; fixed code indentation
% 28/05/15: Fixed issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() func)
% 07/07/15: Fixed issue #83: use numeric handles in HG1
%}
% Generate default input arguments, if needed
if nargin < 2
res = 1;
if nargin < 1
fig = gcf;
end
end
% Warn if output is large
old_mode = get(fig, 'Units');
set(fig, 'Units', 'pixels');
px = get(fig, 'Position');
set(fig, 'Units', old_mode);
npx = prod(px(3:4)*res)/1e6;
if npx > 30
% 30M pixels or larger!
warning('MATLAB:LargeImage', 'print2array generating a %.1fM pixel image. This could be slow and might also cause memory problems.', npx);
end
% Retrieve the background colour
bcol = get(fig, 'Color');
% Set the resolution parameter
res_str = ['-r' num2str(ceil(get(0, 'ScreenPixelsPerInch')*res))];
% Generate temporary file name
tmp_nam = [tempname '.tif'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam); % cleanup
isTempDirOk = true;
catch
% Temp dir is not writable, so use the current folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = pwd;
tmp_nam = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 3 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
else
gs_options = '';
end
if nargin > 2 && strcmp(renderer, '-painters')
% Print to eps file
if isTempDirOk
tmp_eps = [tempname '.eps'];
else
tmp_eps = fullfile(fpath,[fname '.eps']);
end
print2eps(tmp_eps, fig, 0, renderer, '-loose');
try
% Initialize the command to export to tiff using ghostscript
cmd_str = ['-dEPSCrop -q -dNOPAUSE -dBATCH ' res_str ' -sDEVICE=tiff24nc'];
% Set the font path
fp = font_path();
if ~isempty(fp)
cmd_str = [cmd_str ' -sFONTPATH="' fp '"'];
end
% Add the filenames
cmd_str = [cmd_str ' -sOutputFile="' tmp_nam '" "' tmp_eps '"' gs_options];
% Execute the ghostscript command
ghostscript(cmd_str);
catch me
% Delete the intermediate file
delete(tmp_eps);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_eps);
% Read in the generated bitmap
A = imread(tmp_nam);
% Delete the temporary bitmap file
delete(tmp_nam);
% Set border pixels to the correct colour
if isequal(bcol, 'none')
bcol = [];
elseif isequal(bcol, [1 1 1])
bcol = uint8([255 255 255]);
else
for l = 1:size(A, 2)
if ~all(reshape(A(:,l,:) == 255, [], 1))
break;
end
end
for r = size(A, 2):-1:l
if ~all(reshape(A(:,r,:) == 255, [], 1))
break;
end
end
for t = 1:size(A, 1)
if ~all(reshape(A(t,:,:) == 255, [], 1))
break;
end
end
for b = size(A, 1):-1:t
if ~all(reshape(A(b,:,:) == 255, [], 1))
break;
end
end
bcol = uint8(median(single([reshape(A(:,[l r],:), [], size(A, 3)); reshape(A([t b],:,:), [], size(A, 3))]), 1));
for c = 1:size(A, 3)
A(:,[1:l-1, r+1:end],c) = bcol(c);
A([1:t-1, b+1:end],:,c) = bcol(c);
end
end
else
if nargin < 3
renderer = '-opengl';
end
err = false;
% Set paper size
old_pos_mode = get(fig, 'PaperPositionMode');
old_orientation = get(fig, 'PaperOrientation');
set(fig, 'PaperPositionMode', 'auto', 'PaperOrientation', 'portrait');
try
% Workaround for issue #69: patches with LineWidth==0.75 appear wide (internal bug in Matlab's print() function)
fp = []; % in case we get an error below
fp = findall(fig, 'Type','patch', 'LineWidth',0.75);
set(fp, 'LineWidth',0.5);
% Fix issue #83: use numeric handles in HG1
if ~using_hg2(fig), fig = double(fig); end
% Print to tiff file
print(fig, renderer, res_str, '-dtiff', tmp_nam);
% Read in the printed file
A = imread(tmp_nam);
% Delete the temporary file
delete(tmp_nam);
catch ex
err = true;
end
set(fp, 'LineWidth',0.75); % restore original figure appearance
% Reset paper size
set(fig, 'PaperPositionMode', old_pos_mode, 'PaperOrientation', old_orientation);
% Throw any error that occurred
if err
% Display suggested workarounds to internal print() error (issue #16)
fprintf(2, 'An error occured with Matlab''s builtin print function.\nTry setting the figure Renderer to ''painters'' or use opengl(''software'').\n\n');
rethrow(ex);
end
% Set the background color
if isequal(bcol, 'none')
bcol = [];
else
bcol = bcol * 255;
if isequal(bcol, round(bcol))
bcol = uint8(bcol);
else
bcol = squeeze(A(1,1,:));
end
end
end
% Check the output size is correct
if isequal(res, round(res))
px = round([px([4 3])*res 3]); % round() to avoid an indexing warning below
if ~isequal(size(A), px)
% Correct the output size
A = A(1:min(end,px(1)),1:min(end,px(2)),:);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
append_pdfs.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/append_pdfs.m
| 2,759 |
utf_8
|
9b52be41aff48bea6f27992396900640
|
%APPEND_PDFS Appends/concatenates multiple PDF files
%
% Example:
% append_pdfs(output, input1, input2, ...)
% append_pdfs(output, input_list{:})
% append_pdfs test.pdf temp1.pdf temp2.pdf
%
% This function appends multiple PDF files to an existing PDF file, or
% concatenates them into a PDF file if the output file doesn't yet exist.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% IN:
% output - string of output file name (including the extension, .pdf).
% If it exists it is appended to; if not, it is created.
% input1 - string of an input file name (including the extension, .pdf).
% All input files are appended in order.
% input_list - cell array list of input file name strings. All input
% files are appended in order.
% Copyright: Oliver Woodford, 2011
% Thanks to Reinhard Knoll for pointing out that appending multiple pdfs in
% one go is much faster than appending them one at a time.
% Thanks to Michael Teo for reporting the issue of a too long command line.
% Issue resolved on 5/5/2011, by passing gs a command file.
% Thanks to Martin Wittmann for pointing out the quality issue when
% appending multiple bitmaps.
% Issue resolved (to best of my ability) 1/6/2011, using the prepress
% setting
% 26/02/15: If temp dir is not writable, use the output folder for temp
% files when appending (Javier Paredes); sanity check of inputs
function append_pdfs(varargin)
if nargin < 2, return; end % sanity check
% Are we appending or creating a new file
append = exist(varargin{1}, 'file') == 2;
output = [tempname '.pdf'];
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(output,'w');
fwrite(fid,1);
fclose(fid);
delete(output);
isTempDirOk = true;
catch
% Temp dir is not writable, so use the output folder
[dummy,fname,fext] = fileparts(output); %#ok<ASGLU>
fpath = fileparts(varargin{1});
output = fullfile(fpath,[fname fext]);
isTempDirOk = false;
end
if ~append
output = varargin{1};
varargin = varargin(2:end);
end
% Create the command file
if isTempDirOk
cmdfile = [tempname '.txt'];
else
cmdfile = fullfile(fpath,[fname '.txt']);
end
fh = fopen(cmdfile, 'w');
fprintf(fh, '-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="%s" -f', output);
fprintf(fh, ' "%s"', varargin{:});
fclose(fh);
% Call ghostscript
ghostscript(['@"' cmdfile '"']);
% Delete the command file
delete(cmdfile);
% Rename the file if needed
if append
movefile(output, varargin{1});
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
using_hg2.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/using_hg2.m
| 1,037 |
utf_8
|
3303caab5694b040103ccb6b689387bf
|
%USING_HG2 Determine if the HG2 graphics engine is used
%
% tf = using_hg2(fig)
%
%IN:
% fig - handle to the figure in question.
%
%OUT:
% tf - boolean indicating whether the HG2 graphics engine is being used
% (true) or not (false).
% 19/06/2015 - Suppress warning in R2015b; cache result for improved performance
function tf = using_hg2(fig)
persistent tf_cached
if isempty(tf_cached)
try
if nargin < 1, fig = figure('visible','off'); end
oldWarn = warning('off','MATLAB:graphicsversion:GraphicsVersionRemoval');
try
% This generates a [supressed] warning in R2015b:
tf = ~graphicsversion(fig, 'handlegraphics');
catch
tf = verLessThan('matlab','8.4'); % =R2014b
end
warning(oldWarn);
catch
tf = false;
end
if nargin < 1, delete(fig); end
tf_cached = tf;
else
tf = tf_cached;
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
eps2pdf.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/eps2pdf.m
| 8,624 |
utf_8
|
24048681d3f737f221497896307fd2f1
|
function eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%EPS2PDF Convert an eps file to pdf format using ghostscript
%
% Examples:
% eps2pdf source dest
% eps2pdf(source, dest, crop)
% eps2pdf(source, dest, crop, append)
% eps2pdf(source, dest, crop, append, gray)
% eps2pdf(source, dest, crop, append, gray, quality)
% eps2pdf(source, dest, crop, append, gray, quality, gs_options)
%
% This function converts an eps file to pdf format. The output can be
% optionally cropped and also converted to grayscale. If the output pdf
% file already exists then the eps file can optionally be appended as a new
% page on the end of the eps file. The level of bitmap compression can also
% optionally be set.
%
% This function requires that you have ghostscript installed on your
% system. Ghostscript can be downloaded from: http://www.ghostscript.com
%
% Inputs:
% source - filename of the source eps file to convert. The filename is
% assumed to already have the extension ".eps".
% dest - filename of the destination pdf file. The filename is assumed
% to already have the extension ".pdf".
% crop - boolean indicating whether to crop the borders off the pdf.
% Default: true.
% append - boolean indicating whether the eps should be appended to the
% end of the pdf as a new page (if the pdf exists already).
% Default: false.
% gray - boolean indicating whether the output pdf should be grayscale
% or not. Default: false.
% quality - scalar indicating the level of image bitmap quality to
% output. A larger value gives a higher quality. quality > 100
% gives lossless output. Default: ghostscript prepress default.
% gs_options - optional ghostscript options (e.g.: '-dNoOutputFonts'). If
% multiple options are needed, enclose in call array: {'-a','-b'}
% Copyright (C) Oliver Woodford 2009-2014, Yair Altman 2015-
% Suggestion of appending pdf files provided by Matt C at:
% http://www.mathworks.com/matlabcentral/fileexchange/23629
% Thank you to Fabio Viola for pointing out compression artifacts, leading
% to the quality setting.
% Thank you to Scott for pointing out the subsampling of very small images,
% which was fixed for lossless compression settings.
% 9/12/2011 Pass font path to ghostscript.
% 26/02/15: If temp dir is not writable, use the dest folder for temp
% destination files (Javier Paredes)
% 28/02/15: Enable users to specify optional ghostscript options (issue #36)
% 01/03/15: Upon GS error, retry without the -sFONTPATH= option (this might solve
% some /findfont errors according to James Rankin, FEX Comment 23/01/15)
% 23/06/15: Added extra debug info in case of ghostscript error; code indentation
% 04/10/15: Suggest a workaround for issue #41 (missing font path; thanks Mariia Fedotenkova)
% 22/02/16: Bug fix from latest release of this file (workaround for issue #41)
% Intialise the options string for ghostscript
options = ['-q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '"'];
% Set crop option
if nargin < 3 || crop
options = [options ' -dEPSCrop'];
end
% Set the font path
fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end
% Set the grayscale option
if nargin > 4 && gray
options = [options ' -sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray'];
end
% Set the bitmap quality
if nargin > 5 && ~isempty(quality)
options = [options ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false'];
if quality > 100
options = [options ' -dColorImageFilter=/FlateEncode -dGrayImageFilter=/FlateEncode -c ".setpdfwrite << /ColorImageDownsampleThreshold 10 /GrayImageDownsampleThreshold 10 >> setdistillerparams"'];
else
options = [options ' -dColorImageFilter=/DCTEncode -dGrayImageFilter=/DCTEncode'];
v = 1 + (quality < 80);
quality = 1 - quality / 100;
s = sprintf('<< /QFactor %.2f /Blend 1 /HSample [%d 1 1 %d] /VSample [%d 1 1 %d] >>', quality, v, v, v, v);
options = sprintf('%s -c ".setpdfwrite << /ColorImageDict %s /GrayImageDict %s >> setdistillerparams"', options, s, s);
end
end
% Enable users to specify optional ghostscript options (issue #36)
if nargin > 6 && ~isempty(gs_options)
if iscell(gs_options)
gs_options = sprintf(' %s',gs_options{:});
elseif ~ischar(gs_options)
error('gs_options input argument must be a string or cell-array of strings');
else
gs_options = [' ' gs_options];
end
options = [options gs_options];
end
% Check if the output file exists
if nargin > 3 && append && exist(dest, 'file') == 2
% File exists - append current figure to the end
tmp_nam = tempname;
try
% Ensure that the temp dir is writable (Javier Paredes 26/2/15)
fid = fopen(tmp_nam,'w');
fwrite(fid,1);
fclose(fid);
delete(tmp_nam);
catch
% Temp dir is not writable, so use the dest folder
[dummy,fname,fext] = fileparts(tmp_nam); %#ok<ASGLU>
fpath = fileparts(dest);
tmp_nam = fullfile(fpath,[fname fext]);
end
% Copy the file
copyfile(dest, tmp_nam);
% Add the output file names
options = [options ' -f "' tmp_nam '" "' source '"'];
try
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
catch me
% Delete the intermediate file
delete(tmp_nam);
rethrow(me);
end
% Delete the intermediate file
delete(tmp_nam);
else
% File doesn't exist or should be over-written
% Add the output file names
options = [options ' -f "' source '"'];
% Convert to pdf using ghostscript
[status, message] = ghostscript(options);
end
% Check for error
if status
% Retry without the -sFONTPATH= option (this might solve some GS
% /findfont errors according to James Rankin, FEX Comment 23/01/15)
orig_options = options;
if ~isempty(fp)
options = regexprep(options, ' -sFONTPATH=[^ ]+ ',' ');
status = ghostscript(options);
if ~status, return; end % hurray! (no error)
end
% Report error
if isempty(message)
error('Unable to generate pdf. Check destination directory is writable.');
elseif ~isempty(strfind(message,'/typecheck in /findfont'))
% Suggest a workaround for issue #41 (missing font path)
font_name = strtrim(regexprep(message,'.*Operand stack:\s*(.*)\s*Execution.*','$1'));
fprintf(2, 'Ghostscript error: could not find the following font(s): %s\n', font_name);
fpath = fileparts(mfilename('fullpath'));
gs_fonts_file = fullfile(fpath, '.ignore', 'gs_font_path.txt');
fprintf(2, ' try to add the font''s folder to your %s file\n\n', gs_fonts_file);
error('export_fig error');
else
fprintf(2, '\nGhostscript error: perhaps %s is open by another application\n', dest);
if ~isempty(gs_options)
fprintf(2, ' or maybe the%s option(s) are not accepted by your GS version\n', gs_options);
end
fprintf(2, 'Ghostscript options: %s\n\n', orig_options);
error(message);
end
end
end
% Function to return (and create, where necessary) the font path
function fp = font_path()
fp = user_string('gs_font_path');
if ~isempty(fp)
return
end
% Create the path
% Start with the default path
fp = getenv('GS_FONTPATH');
% Add on the typical directories for a given OS
if ispc
if ~isempty(fp)
fp = [fp ';'];
end
fp = [fp getenv('WINDIR') filesep 'Fonts'];
else
if ~isempty(fp)
fp = [fp ':'];
end
fp = [fp '/usr/share/fonts:/usr/local/share/fonts:/usr/share/fonts/X11:/usr/local/share/fonts/X11:/usr/share/fonts/truetype:/usr/local/share/fonts/truetype'];
end
user_string('gs_font_path', fp);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
ghostscript.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/ghostscript.m
| 7,902 |
utf_8
|
ff62a40d651197dbea5d3c39998b3bad
|
function varargout = ghostscript(cmd)
%GHOSTSCRIPT Calls a local GhostScript executable with the input command
%
% Example:
% [status result] = ghostscript(cmd)
%
% Attempts to locate a ghostscript executable, finally asking the user to
% specify the directory ghostcript was installed into. The resulting path
% is stored for future reference.
%
% Once found, the executable is called with the input command string.
%
% This function requires that you have Ghostscript installed on your
% system. You can download this from: http://www.ghostscript.com
%
% IN:
% cmd - Command string to be passed into ghostscript.
%
% OUT:
% status - 0 iff command ran without problem.
% result - Output from ghostscript.
% Copyright: Oliver Woodford, 2009-2015, Yair Altman 2015-
%{
% Thanks to Jonas Dorn for the fix for the title of the uigetdir window on Mac OS.
% Thanks to Nathan Childress for the fix to default location on 64-bit Windows systems.
% 27/04/11 - Find 64-bit Ghostscript on Windows. Thanks to Paul Durack and
% Shaun Kline for pointing out the issue
% 04/05/11 - Thanks to David Chorlian for pointing out an alternative
% location for gs on linux.
% 12/12/12 - Add extra executable name on Windows. Thanks to Ratish
% Punnoose for highlighting the issue.
% 28/06/13 - Fix error using GS 9.07 in Linux. Many thanks to Jannick
% Steinbring for proposing the fix.
% 24/10/13 - Fix error using GS 9.07 in Linux. Many thanks to Johannes
% for the fix.
% 23/01/14 - Add full path to ghostscript.txt in warning. Thanks to Koen
% Vermeer for raising the issue.
% 27/02/15 - If Ghostscript croaks, display suggested workarounds
% 30/03/15 - Improved performance by caching status of GS path check, if ok
% 14/05/15 - Clarified warning message in case GS path could not be saved
% 29/05/15 - Avoid cryptic error in case the ghostscipt path cannot be saved (issue #74)
% 10/11/15 - Custom GS installation webpage for MacOS. Thanks to Andy Hueni via FEX
%}
try
% Call ghostscript
[varargout{1:nargout}] = system([gs_command(gs_path()) cmd]);
catch err
% Display possible workarounds for Ghostscript croaks
url1 = 'https://github.com/altmany/export_fig/issues/12#issuecomment-61467998'; % issue #12
url2 = 'https://github.com/altmany/export_fig/issues/20#issuecomment-63826270'; % issue #20
hg2_str = ''; if using_hg2, hg2_str = ' or Matlab R2014a'; end
fprintf(2, 'Ghostscript error. Rolling back to GS 9.10%s may possibly solve this:\n * <a href="%s">%s</a> ',hg2_str,url1,url1);
if using_hg2
fprintf(2, '(GS 9.10)\n * <a href="%s">%s</a> (R2014a)',url2,url2);
end
fprintf('\n\n');
if ismac || isunix
url3 = 'https://github.com/altmany/export_fig/issues/27'; % issue #27
fprintf(2, 'Alternatively, this may possibly be due to a font path issue:\n * <a href="%s">%s</a>\n\n',url3,url3);
% issue #20
fpath = which(mfilename);
if isempty(fpath), fpath = [mfilename('fullpath') '.m']; end
fprintf(2, 'Alternatively, if you are using csh, modify shell_cmd from "export..." to "setenv ..."\nat the bottom of <a href="matlab:opentoline(''%s'',174)">%s</a>\n\n',fpath,fpath);
end
rethrow(err);
end
end
function path_ = gs_path
% Return a valid path
% Start with the currently set path
path_ = user_string('ghostscript');
% Check the path works
if check_gs_path(path_)
return
end
% Check whether the binary is on the path
if ispc
bin = {'gswin32c.exe', 'gswin64c.exe', 'gs'};
else
bin = {'gs'};
end
for a = 1:numel(bin)
path_ = bin{a};
if check_store_gs_path(path_)
return
end
end
% Search the obvious places
if ispc
default_location = 'C:\Program Files\gs\';
dir_list = dir(default_location);
if isempty(dir_list)
default_location = 'C:\Program Files (x86)\gs\'; % Possible location on 64-bit systems
dir_list = dir(default_location);
end
executable = {'\bin\gswin32c.exe', '\bin\gswin64c.exe'};
ver_num = 0;
% If there are multiple versions, use the newest
for a = 1:numel(dir_list)
ver_num2 = sscanf(dir_list(a).name, 'gs%g');
if ~isempty(ver_num2) && ver_num2 > ver_num
for b = 1:numel(executable)
path2 = [default_location dir_list(a).name executable{b}];
if exist(path2, 'file') == 2
path_ = path2;
ver_num = ver_num2;
end
end
end
end
if check_store_gs_path(path_)
return
end
else
executable = {'/usr/bin/gs', '/usr/local/bin/gs'};
for a = 1:numel(executable)
path_ = executable{a};
if check_store_gs_path(path_)
return
end
end
end
% Ask the user to enter the path
while true
if strncmp(computer, 'MAC', 3) % Is a Mac
% Give separate warning as the uigetdir dialogue box doesn't have a
% title
uiwait(warndlg('Ghostscript not found. Please locate the program.'))
end
base = uigetdir('/', 'Ghostcript not found. Please locate the program.');
if isequal(base, 0)
% User hit cancel or closed window
break;
end
base = [base filesep]; %#ok<AGROW>
bin_dir = {'', ['bin' filesep], ['lib' filesep]};
for a = 1:numel(bin_dir)
for b = 1:numel(bin)
path_ = [base bin_dir{a} bin{b}];
if exist(path_, 'file') == 2
if check_store_gs_path(path_)
return
end
end
end
end
end
if ismac
error('Ghostscript not found. Have you installed it (http://pages.uoregon.edu/koch)?');
else
error('Ghostscript not found. Have you installed it from www.ghostscript.com?');
end
end
function good = check_store_gs_path(path_)
% Check the path is valid
good = check_gs_path(path_);
if ~good
return
end
% Update the current default path to the path found
if ~user_string('ghostscript', path_)
filename = fullfile(fileparts(which('user_string.m')), '.ignore', 'ghostscript.txt');
warning('Path to ghostscript installation could not be saved in %s (perhaps a permissions issue). You can manually create this file and set its contents to %s, to improve performance in future invocations (this warning is safe to ignore).', filename, path_);
return
end
end
function good = check_gs_path(path_)
persistent isOk
if isempty(path_)
isOk = false;
elseif ~isequal(isOk,true)
% Check whether the path is valid
[status, message] = system([gs_command(path_) '-h']); %#ok<ASGLU>
isOk = status == 0;
end
good = isOk;
end
function cmd = gs_command(path_)
% Initialize any required system calls before calling ghostscript
% TODO: in Unix/Mac, find a way to determine whether to use "export" (bash) or "setenv" (csh/tcsh)
shell_cmd = '';
if isunix
shell_cmd = 'export LD_LIBRARY_PATH=""; '; % Avoids an error on Linux with GS 9.07
end
if ismac
shell_cmd = 'export DYLD_LIBRARY_PATH=""; '; % Avoids an error on Mac with GS 9.07
end
% Construct the command string
cmd = sprintf('%s"%s" ', shell_cmd, path_);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
fix_lines.m
|
.m
|
Fast-SeqSLAM-master/graphs/altmany-export_fig-113e357/fix_lines.m
| 6,441 |
utf_8
|
ffda929ebad8144b1e72d528fa5d9460
|
%FIX_LINES Improves the line style of eps files generated by print
%
% Examples:
% fix_lines fname
% fix_lines fname fname2
% fstrm_out = fixlines(fstrm_in)
%
% This function improves the style of lines in eps files generated by
% MATLAB's print function, making them more similar to those seen on
% screen. Grid lines are also changed from a dashed style to a dotted
% style, for greater differentiation from dashed lines.
%
% The function also places embedded fonts after the postscript header, in
% versions of MATLAB which place the fonts first (R2006b and earlier), in
% order to allow programs such as Ghostscript to find the bounding box
% information.
%
%IN:
% fname - Name or path of source eps file.
% fname2 - Name or path of destination eps file. Default: same as fname.
% fstrm_in - File contents of a MATLAB-generated eps file.
%
%OUT:
% fstrm_out - Contents of the eps file with line styles fixed.
% Copyright: (C) Oliver Woodford, 2008-2014
% The idea of editing the EPS file to change line styles comes from Jiro
% Doke's FIXPSLINESTYLE (fex id: 17928)
% The idea of changing dash length with line width came from comments on
% fex id: 5743, but the implementation is mine :)
% Thank you to Sylvain Favrot for bringing the embedded font/bounding box
% interaction in older versions of MATLAB to my attention.
% Thank you to D Ko for bringing an error with eps files with tiff previews
% to my attention.
% Thank you to Laurence K for suggesting the check to see if the file was
% opened.
% 01/03/15: Issue #20: warn users if using this function in HG2 (R2014b+)
% 27/03/15: Fixed out of memory issue with enormous EPS files (generated by print() with OpenGL renderer), related to issue #39
function fstrm = fix_lines(fstrm, fname2)
% Issue #20: warn users if using this function in HG2 (R2014b+)
if using_hg2
warning('export_fig:hg2','The fix_lines function should not be used in this Matlab version.');
end
if nargout == 0 || nargin > 1
if nargin < 2
% Overwrite the input file
fname2 = fstrm;
end
% Read in the file
fstrm = read_write_entire_textfile(fstrm);
end
% Move any embedded fonts after the postscript header
if strcmp(fstrm(1:15), '%!PS-AdobeFont-')
% Find the start and end of the header
ind = regexp(fstrm, '[\n\r]%!PS-Adobe-');
[ind2, ind2] = regexp(fstrm, '[\n\r]%%EndComments[\n\r]+');
% Put the header first
if ~isempty(ind) && ~isempty(ind2) && ind(1) < ind2(1)
fstrm = fstrm([ind(1)+1:ind2(1) 1:ind(1) ind2(1)+1:end]);
end
end
% Make sure all line width commands come before the line style definitions,
% so that dash lengths can be based on the correct widths
% Find all line style sections
ind = [regexp(fstrm, '[\n\r]SO[\n\r]'),... % This needs to be here even though it doesn't have dots/dashes!
regexp(fstrm, '[\n\r]DO[\n\r]'),...
regexp(fstrm, '[\n\r]DA[\n\r]'),...
regexp(fstrm, '[\n\r]DD[\n\r]')];
ind = sort(ind);
% Find line width commands
[ind2, ind3] = regexp(fstrm, '[\n\r]\d* w[\n\r]');
% Go through each line style section and swap with any line width commands
% near by
b = 1;
m = numel(ind);
n = numel(ind2);
for a = 1:m
% Go forwards width commands until we pass the current line style
while b <= n && ind2(b) < ind(a)
b = b + 1;
end
if b > n
% No more width commands
break;
end
% Check we haven't gone past another line style (including SO!)
if a < m && ind2(b) > ind(a+1)
continue;
end
% Are the commands close enough to be confident we can swap them?
if (ind2(b) - ind(a)) > 8
continue;
end
% Move the line style command below the line width command
fstrm(ind(a)+1:ind3(b)) = [fstrm(ind(a)+4:ind3(b)) fstrm(ind(a)+1:ind(a)+3)];
b = b + 1;
end
% Find any grid line definitions and change to GR format
% Find the DO sections again as they may have moved
ind = int32(regexp(fstrm, '[\n\r]DO[\n\r]'));
if ~isempty(ind)
% Find all occurrences of what are believed to be axes and grid lines
ind2 = int32(regexp(fstrm, '[\n\r] *\d* *\d* *mt *\d* *\d* *L[\n\r]'));
if ~isempty(ind2)
% Now see which DO sections come just before axes and grid lines
ind2 = repmat(ind2', [1 numel(ind)]) - repmat(ind, [numel(ind2) 1]);
ind2 = any(ind2 > 0 & ind2 < 12); % 12 chars seems about right
ind = ind(ind2);
% Change any regions we believe to be grid lines to GR
fstrm(ind+1) = 'G';
fstrm(ind+2) = 'R';
end
end
% Define the new styles, including the new GR format
% Dot and dash lengths have two parts: a constant amount plus a line width
% variable amount. The constant amount comes after dpi2point, and the
% variable amount comes after currentlinewidth. If you want to change
% dot/dash lengths for a one particular line style only, edit the numbers
% in the /DO (dotted lines), /DA (dashed lines), /DD (dot dash lines) and
% /GR (grid lines) lines for the style you want to change.
new_style = {'/dom { dpi2point 1 currentlinewidth 0.08 mul add mul mul } bdef',... % Dot length macro based on line width
'/dam { dpi2point 2 currentlinewidth 0.04 mul add mul mul } bdef',... % Dash length macro based on line width
'/SO { [] 0 setdash 0 setlinecap } bdef',... % Solid lines
'/DO { [1 dom 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dotted lines
'/DA { [4 dam 1.5 dam] 0 setdash 0 setlinecap } bdef',... % Dashed lines
'/DD { [1 dom 1.2 dom 4 dam 1.2 dom] 0 setdash 0 setlinecap } bdef',... % Dot dash lines
'/GR { [0 dpi2point mul 4 dpi2point mul] 0 setdash 1 setlinecap } bdef'}; % Grid lines - dot spacing remains constant
% Construct the output
% This is the original (memory-intensive) code:
%first_sec = strfind(fstrm, '% line types:'); % Isolate line style definition section
%[second_sec, remaining] = strtok(fstrm(first_sec+1:end), '/');
%[remaining, remaining] = strtok(remaining, '%');
%fstrm = [fstrm(1:first_sec) second_sec sprintf('%s\r', new_style{:}) remaining];
fstrm = regexprep(fstrm,'(% line types:.+?)/.+?%',['$1',sprintf('%s\r',new_style{:}),'%']);
% Write the output file
if nargout == 0 || nargin > 1
read_write_entire_textfile(fname2, fstrm);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_search.m
|
.m
|
Fast-SeqSLAM-master/flann/flann_search.m
| 3,506 |
utf_8
|
cffd29579f0290f0f680a3f12cb7a671
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function [indices, dists] = flann_search(data, testset, n, search_params)
%NN_SEARCH Fast approximate nearest neighbors search
%
% Performs a fast approximate nearest neighbor search using an
% index constructed using flann_build_index or directly a
% dataset.
% Marius Muja, January 2008
algos = struct( 'linear', 0, 'kdtree', 1, 'kmeans', 2, 'composite', 3, 'saved', 254, 'autotuned', 255 );
center_algos = struct('random', 0, 'gonzales', 1, 'kmeanspp', 2 );
log_levels = struct('none', 0, 'fatal', 1, 'error', 2, 'warning', 3, 'info', 4);
function value = id2value(map, id)
fields = fieldnames(map);
for i = 1:length(fields),
val = cell2mat(fields(i));
if map.(val) == id
value = val;
break;
end
end
end
function id = value2id(map,value)
id = map.(value);
end
default_params = struct('algorithm', 'kdtree' ,'checks', 32, 'trees', 4, 'branching', 32, 'iterations', 5, 'centers_init', 'random', 'cb_index', 0.4, 'target_precision', -1, 'build_weight', 0.01, 'memory_weight', 0, 'sample_fraction', 0.1, 'log_level', 'warning', 'random_seed', 0);
if ~isstruct(search_params)
error('The "search_params" argument must be a structure');
end
params = default_params;
fn = fieldnames(search_params);
for i = [1:length(fn)],
name = cell2mat(fn(i));
params.(name) = search_params.(name);
end
if ~isnumeric(params.algorithm),
params.algorithm = value2id(algos,params.algorithm);
end
if ~isnumeric(params.centers_init),
params.centers_init = value2id(center_algos,params.centers_init);
end
if ~isnumeric(params.log_level),
params.log_level = value2id(log_levels,params.log_level);
end
if (size(data,1)==1 && size(data,2)==1)
% we already have an index
[indices,dists] = nearest_neighbors('index_find_nn', data, testset, n, params);
else
% create the index and search
[indices,dists] = nearest_neighbors('find_nn', data, testset, n, params);
end
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_load_index.m
|
.m
|
Fast-SeqSLAM-master/flann/flann_load_index.m
| 1,578 |
utf_8
|
f9bcc41fd5972c5c987d6a4d41bdc796
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function index = flann_load_index(filename, dataset)
%FLANN_LOAD_INDEX Loads an index from disk
%
% Marius Muja, March 2009
index = nearest_neighbors('load_index', filename, dataset);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
test_flann.m
|
.m
|
Fast-SeqSLAM-master/flann/test_flann.m
| 10,100 |
utf_8
|
d65a8eac8c411227a355b4ddbe6de38a
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function test_flann
data_path = './';
outcome = {'FAILED!!!!!!!!!', 'PASSED'};
failed = 0;
passed = 0;
cnt = 0;
ok = 1;
function assert(condition)
if (~condition)
ok = 0;
end
end
function run_test(name, test)
ok = 1;
cnt = cnt + 1;
tic;
fprintf('Test %d: %s...',cnt,name);
test();
time = toc;
if (ok)
passed = passed + 1;
else
failed = failed + 1;
end
fprintf('done (%g sec) : %s\n',time,cell2mat(outcome(ok+1)))
end
function status
fprintf('-----------------\n');
fprintf('Passed: %d/%d\nFailed: %d/%d\n',passed,cnt,failed,cnt);
end
dataset = [];
testset = [];
function test_load_data
% load the datasets and testsets
% use single precision for better memory efficiency
% store the features one per column because MATLAB
% uses column major ordering
dataset = single(load([data_path 'dataset.dat']))';
testset = single(load([data_path 'testset.dat']))';
assert(size(dataset,1) == size(testset,1));
end
run_test('Load data',@test_load_data);
match = [];
dists = [];
function test_linear_search
[match,dists] = flann_search(dataset, testset, 10, struct('algorithm','linear'));
assert(size(match,1) ==10 && size(match,2) == size(testset,2));
end
run_test('Linear search',@test_linear_search);
function test_kdtree_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kdtree',...
'trees',8,...
'checks',64));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('kd-tree search',@test_kdtree_search);
function test_kmeans_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('k-means search',@test_kmeans_search);
function test_composite_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','composite',...
'branching',32,...
'iterations',3,...
'trees', 1,...
'checks',64));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('composite search',@test_composite_search);
function test_autotune_search
[result, ndists] = flann_search(dataset, testset, 10, struct('algorithm','autotuned',...
'target_precision',0.95,...
'build_weight',0.01,...
'memory_weight',0));
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('search with autotune',@test_autotune_search);
function test_index_kdtree_search
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kdtree', 'trees',8,...
'checks',64));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kd-tree search',@test_index_kdtree_search);
function test_index_kmeans_search
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search',@test_index_kmeans_search);
function test_index_kmeans_search_gonzales
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120,...
'centers_init','gonzales'));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search gonzales',@test_index_kmeans_search_gonzales);
function test_index_kmeans_search_kmeanspp
[index, search_params ] = flann_build_index(dataset, struct('algorithm','kmeans',...
'branching',32,...
'iterations',3,...
'checks',120,...
'centers_init','kmeanspp'));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index kmeans search kmeanspp',@test_index_kmeans_search_kmeanspp);
function test_index_composite_search
[index, search_params ] = flann_build_index(dataset,struct('algorithm','composite',...
'branching',32,...
'iterations',3,...
'trees', 1,...
'checks',64));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index composite search',@test_index_composite_search);
function test_index_autotune_search
[index, search_params, speedup ] = flann_build_index(dataset,struct('algorithm','autotuned',...
'target_precision',0.95,...
'build_weight',0.01,...
'memory_weight',0));
[result, ndists] = flann_search(index, testset, 10, search_params);
n = size(match,2);
precision = (n-sum(abs(result(1,:)-match(1,:))>0))/n;
assert(precision>0.9);
assert(sum(~(match(1,:)-result(1,:)).*(dists(1,:)-ndists(1,:)))==0);
end
run_test('index autotune search',@test_index_autotune_search);
status();
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_free_index.m
|
.m
|
Fast-SeqSLAM-master/flann/flann_free_index.m
| 1,614 |
utf_8
|
5d719d8d60539b6c90bee08d01e458b5
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function flann_free_index(index_id)
%FLANN_FREE_INDEX Deletes the nearest-neighbors index
%
% Deletes an index constructed using flann_build_index.
% Marius Muja, January 2008
nearest_neighbors('free_index',index_id);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_save_index.m
|
.m
|
Fast-SeqSLAM-master/flann/flann_save_index.m
| 1,563 |
utf_8
|
5a44d911827fba5422041529b3c01cf6
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function flann_save_index(index_id, filename)
%FLANN_SAVE_INDEX Saves an index to disk
%
% Marius Muja, March 2010
nearest_neighbors('save_index',index_id, filename);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
flann_set_distance_type.m
|
.m
|
Fast-SeqSLAM-master/flann/flann_set_distance_type.m
| 1,926 |
utf_8
|
8ba72989a4ac1bd6b30bec841b9def25
|
%Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved.
%Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved.
%
%THE BSD LICENSE
%
%Redistribution and use in source and binary forms, with or without
%modification, are permitted provided that the following conditions
%are met:
%
%1. Redistributions of source code must retain the above copyright
% notice, this list of conditions and the following disclaimer.
%2. Redistributions in binary form must reproduce the above copyright
% notice, this list of conditions and the following disclaimer in the
% documentation and/or other materials provided with the distribution.
%
%THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
%IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
%OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
%IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
%INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
%NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
%DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
%THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
%(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
%THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
function flann_set_distance_type(type, order)
%FLANN_LOAD_INDEX Loads an index from disk
%
% Marius Muja, March 2009
distances = struct('euclidean', 1, 'manhattan', 2, 'minkowski', 3, 'max_dist', 4, 'hik', 5, 'hellinger', 6, 'chi_square', 7, 'cs', 7, 'kullback_leibler', 8, 'kl', 8);
function id = value2id(map,value)
id = map.(value);
end
if ~isnumeric(type),
type = value2id(distances,type);
end
if type~=3
order = 0;
end
nearest_neighbors('set_distance_type', type, order);
end
|
github
|
siam1251/Fast-SeqSLAM-master
|
sift.m
|
.m
|
Fast-SeqSLAM-master/draw_features/sift.m
| 2,466 |
utf_8
|
414f6d11875ffa2761038d8b112488e5
|
% [image, descriptors, locs] = sift(imageFile)
%
% This function reads an image and returns its SIFT keypoints.
% Input parameters:
% imageFile: the file name for the image.
%
% Returned:
% image: the image array in double format
% descriptors: a K-by-128 matrix, where each row gives an invariant
% descriptor for one of the K keypoints. The descriptor is a vector
% of 128 values normalized to unit length.
% locs: K-by-4 matrix, in which each row has the 4 values for a
% keypoint location (row, column, scale, orientation). The
% orientation is in the range [-PI, PI] radians.
%
% Credits: Thanks for initial version of this program to D. Alvaro and
% J.J. Guerrero, Universidad de Zaragoza (modified by D. Lowe)
function [image, descriptors, locs] = sift(imageFile)
% Load image
image = imread(imageFile);
% If you have the Image Processing Toolbox, you can uncomment the following
% lines to allow input of color images, which will be converted to grayscale.
image = rgb2gray(image);
[rows, cols] = size(image);
% Convert into PGM imagefile, readable by "keypoints" executable
f = fopen('tmp.pgm', 'w');
if f == -1
error('Could not create file tmp.pgm.');
end
fprintf(f, 'P5\n%d\n%d\n255\n', cols, rows);
fwrite(f, image', 'uint8');
fclose(f);
% Call keypoints executable
if isunix
command = '!./sift ';
else
command = '!siftWin32 ';
end
command = [command ' <tmp.pgm >tmp.key'];
eval(command);
% Open tmp.key and check its header
g = fopen('tmp.key', 'r');
if g == -1
error('Could not open file tmp.key.');
end
[header, count] = fscanf(g, '%d %d', [1 2]);
if count ~= 2
error('Invalid keypoint file beginning.');
end
num = header(1);
len = header(2);
if len ~= 128
error('Keypoint descriptor length invalid (should be 128).');
end
% Creates the two output matrices (use known size for efficiency)
locs = double(zeros(num, 4));
descriptors = double(zeros(num, 128));
% Parse tmp.key
for i = 1:num
[vector, count] = fscanf(g, '%f %f %f %f', [1 4]); %row col scale ori
if count ~= 4
error('Invalid keypoint file format');
end
locs(i, :) = vector(1, :);
[descrip, count] = fscanf(g, '%d', [1 len]);
if (count ~= 128)
error('Invalid keypoint file value.');
end
% Normalize each input vector to unit length
descrip = descrip / sqrt(sum(descrip.^2));
descriptors(i, :) = descrip(1, :);
end
fclose(g);
|
github
|
siam1251/Fast-SeqSLAM-master
|
appendimages.m
|
.m
|
Fast-SeqSLAM-master/draw_features/siftDemoV4/appendimages.m
| 461 |
utf_8
|
a7ad42558236d4f7bd90dc6e72631d54
|
% im = appendimages(image1, image2)
%
% Return a new image that appends the two images side-by-side.
function im = appendimages(image1, image2)
% Select the image with the fewest rows and fill in enough empty rows
% to make it the same height as the other image.
rows1 = size(image1,1);
rows2 = size(image2,1);
if (rows1 < rows2)
image1(rows2,1) = 0;
else
image2(rows1,1) = 0;
end
% Now append both images side-by-side.
im = [image1 image2];
|
github
|
siam1251/Fast-SeqSLAM-master
|
showkeys.m
|
.m
|
Fast-SeqSLAM-master/draw_features/siftDemoV4/showkeys.m
| 1,699 |
utf_8
|
4e67466c0fd7739350cb2af5767e10a4
|
% showkeys(image, locs)
%
% This function displays an image with SIFT keypoints overlayed.
% Input parameters:
% image: the file name for the image (grayscale)
% locs: matrix in which each row gives a keypoint location (row,
% column, scale, orientation)
function showkeys(image, locs)
disp('Drawing SIFT keypoints ...');
% Draw image with keypoints
figure('Position', [50 50 size(image,2) size(image,1)]);
colormap('gray');
imagesc(image);
hold on;
imsize = size(image);
for i = 1: size(locs,1)
% Draw an arrow, each line transformed according to keypoint parameters.
TransformLine(imsize, locs(i,:), 0.0, 0.0, 1.0, 0.0);
TransformLine(imsize, locs(i,:), 0.85, 0.1, 1.0, 0.0);
TransformLine(imsize, locs(i,:), 0.85, -0.1, 1.0, 0.0);
end
hold off;
% ------ Subroutine: TransformLine -------
% Draw the given line in the image, but first translate, rotate, and
% scale according to the keypoint parameters.
%
% Parameters:
% Arrays:
% imsize = [rows columns] of image
% keypoint = [subpixel_row subpixel_column scale orientation]
%
% Scalars:
% x1, y1; begining of vector
% x2, y2; ending of vector
function TransformLine(imsize, keypoint, x1, y1, x2, y2)
% The scaling of the unit length arrow is set to approximately the radius
% of the region used to compute the keypoint descriptor.
len = 6 * keypoint(3);
% Rotate the keypoints by 'ori' = keypoint(4)
s = sin(keypoint(4));
c = cos(keypoint(4));
% Apply transform
r1 = keypoint(1) - len * (c * y1 + s * x1);
c1 = keypoint(2) + len * (- s * y1 + c * x1);
r2 = keypoint(1) - len * (c * y2 + s * x2);
c2 = keypoint(2) + len * (- s * y2 + c * x2);
line([c1 c2], [r1 r2], 'Color', 'c');
|
github
|
siam1251/Fast-SeqSLAM-master
|
sift.m
|
.m
|
Fast-SeqSLAM-master/draw_features/siftDemoV4/sift.m
| 2,466 |
utf_8
|
414f6d11875ffa2761038d8b112488e5
|
% [image, descriptors, locs] = sift(imageFile)
%
% This function reads an image and returns its SIFT keypoints.
% Input parameters:
% imageFile: the file name for the image.
%
% Returned:
% image: the image array in double format
% descriptors: a K-by-128 matrix, where each row gives an invariant
% descriptor for one of the K keypoints. The descriptor is a vector
% of 128 values normalized to unit length.
% locs: K-by-4 matrix, in which each row has the 4 values for a
% keypoint location (row, column, scale, orientation). The
% orientation is in the range [-PI, PI] radians.
%
% Credits: Thanks for initial version of this program to D. Alvaro and
% J.J. Guerrero, Universidad de Zaragoza (modified by D. Lowe)
function [image, descriptors, locs] = sift(imageFile)
% Load image
image = imread(imageFile);
% If you have the Image Processing Toolbox, you can uncomment the following
% lines to allow input of color images, which will be converted to grayscale.
image = rgb2gray(image);
[rows, cols] = size(image);
% Convert into PGM imagefile, readable by "keypoints" executable
f = fopen('tmp.pgm', 'w');
if f == -1
error('Could not create file tmp.pgm.');
end
fprintf(f, 'P5\n%d\n%d\n255\n', cols, rows);
fwrite(f, image', 'uint8');
fclose(f);
% Call keypoints executable
if isunix
command = '!./sift ';
else
command = '!siftWin32 ';
end
command = [command ' <tmp.pgm >tmp.key'];
eval(command);
% Open tmp.key and check its header
g = fopen('tmp.key', 'r');
if g == -1
error('Could not open file tmp.key.');
end
[header, count] = fscanf(g, '%d %d', [1 2]);
if count ~= 2
error('Invalid keypoint file beginning.');
end
num = header(1);
len = header(2);
if len ~= 128
error('Keypoint descriptor length invalid (should be 128).');
end
% Creates the two output matrices (use known size for efficiency)
locs = double(zeros(num, 4));
descriptors = double(zeros(num, 128));
% Parse tmp.key
for i = 1:num
[vector, count] = fscanf(g, '%f %f %f %f', [1 4]); %row col scale ori
if count ~= 4
error('Invalid keypoint file format');
end
locs(i, :) = vector(1, :);
[descrip, count] = fscanf(g, '%d', [1 len]);
if (count ~= 128)
error('Invalid keypoint file value.');
end
% Normalize each input vector to unit length
descrip = descrip / sqrt(sum(descrip.^2));
descriptors(i, :) = descrip(1, :);
end
fclose(g);
|
github
|
siam1251/Fast-SeqSLAM-master
|
match.m
|
.m
|
Fast-SeqSLAM-master/draw_features/siftDemoV4/match.m
| 1,941 |
utf_8
|
8b21ce74b4e02359b997273701345d26
|
% num = match(image1, image2)
%
% This function reads two images, finds their SIFT features, and
% displays lines connecting the matched keypoints. A match is accepted
% only if its distance is less than distRatio times the distance to the
% second closest match.
% It returns the number of matches displayed.
%
% Example: match('scene.pgm','book.pgm');
function num = match(image1, image2)
% Find SIFT keypoints for each image
[im1, des1, loc1] = sift(image1);
[im2, des2, loc2] = sift(image2);
% For efficiency in Matlab, it is cheaper to compute dot products between
% unit vectors rather than Euclidean distances. Note that the ratio of
% angles (acos of dot products of unit vectors) is a close approximation
% to the ratio of Euclidean distances for small angles.
%
% distRatio: Only keep matches in which the ratio of vector angles from the
% nearest to second nearest neighbor is less than distRatio.
distRatio = 0.6;
% For each descriptor in the first image, select its match to second image.
des2t = des2'; % Precompute matrix transpose
for i = 1 : size(des1,1)
dotprods = des1(i,:) * des2t; % Computes vector of dot products
[vals,indx] = sort(acos(dotprods)); % Take inverse cosine and sort results
% Check if nearest neighbor has angle less than distRatio times 2nd.
if (vals(1) < distRatio * vals(2))
match(i) = indx(1);
else
match(i) = 0;
end
end
% Create a new image showing the two images side by side.
im3 = appendimages(im1,im2);
% Show a figure with lines joining the accepted matches.
figure('Position', [100 100 size(im3,2) size(im3,1)]);
colormap('gray');
imagesc(im3);
hold on;
cols1 = size(im1,2);
for i = 1: size(des1,1)
if (match(i) > 0)
line([loc1(i,2) loc2(match(i),2)+cols1], ...
[loc1(i,1) loc2(match(i),1)], 'Color', 'c');
end
end
hold off;
num = sum(match > 0);
fprintf('Found %d matches.\n', num);
|
github
|
jianxiongxiao/ProfXkit-master
|
points2normals.m
|
.m
|
ProfXkit-master/points2normals.m
| 2,552 |
utf_8
|
dfc71c0533d195b17cabe47cc78b496b
|
function normals = points2normals(points)
% estimating a normal vector based on nearby 100 points
% points is 3 * n matrix for n points
if size(points,2)==3 && size(points,1)~=3
points = points';
end
normals = lsqnormest(points, 100);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% functions from http://www.mathworks.com/matlabcentral/fileexchange/27804-iterative-closest-point
% Least squares normal estimation from point clouds using PCA
%
% H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle.
% Surface reconstruction from unorganized points.
% In Proceedings of ACM Siggraph, pages 71:78, 1992.
%
% p should be a matrix containing the horizontally concatenated column
% vectors with points. k is a scalar indicating how many neighbors the
% normal estimation is based upon.
%
% Note that for large point sets, the function performs significantly
% faster if Statistics Toolbox >= v. 7.3 is installed.
%
% Jakob Wilm 2010
function n = lsqnormest(p, k)
m = size(p,2);
n = zeros(3,m);
v = ver('stats');
if str2double(v.Version) >= 7.5
neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1));
else
neighbors = k_nearest_neighbors(p, p, k+1);
end
for i = 1:m
x = p(:,neighbors(2:end, i));
p_bar = 1/k * sum(x,2);
P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P
%P = 2*cov(x);
[V,D] = eig(P);
[~, idx] = min(diag(D)); % choses the smallest eigenvalue
n(:,i) = V(:,idx); % returns the corresponding eigenvector
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Program to find the k - nearest neighbors (kNN) within a set of points.
% Distance metric used: Euclidean distance
%
% Note that this function makes repetitive use of min(), which seems to be
% more efficient than sort() for k < 30.
function [neighborIds,neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k)
numDataPoints = size(dataMatrix,2);
numQueryPoints = size(queryMatrix,2);
neighborIds = zeros(k,numQueryPoints);
neighborDistances = zeros(k,numQueryPoints);
D = size(dataMatrix, 1); %dimensionality of points
for i=1:numQueryPoints
d=zeros(1,numDataPoints);
for t=1:D % this is to avoid slow repmat()
d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2;
end
for j=1:k
[s,t] = min(d);
neighborIds(j,i)=t;
neighborDistances(j,i)=sqrt(s);
d(t) = NaN; % remove found number from d
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
PCAvertex.m
|
.m
|
ProfXkit-master/obj2off/PCAvertex.m
| 659 |
utf_8
|
6c8fef996f6c810adad6b830ef0800e1
|
function vmatOut = PCAvertex(vmat)
% vmat: 3xN
[C,V]= PCA(vmat(1:2,:),2);
Vproj = C'*vmat(1:2,:);
vmatOut = [Vproj;vmat(3,:)];
end
function [C,V]= PCA(data,num)
%data 300*N, C vector , V value
data(sum(isnan(data),2)>0,:)=[];
[~,N] = size(data);
mn = mean(data,2);
data = data - repmat(mn,1,N);
covariance = 1 / (N-1) * data * data';
[PC, V] = eigs(covariance);
V = real(diag(V));
% sort the value in decreasing order
[~, rindices] = sort(-1*V);
V = V(rindices);
C =PC(:,rindices);
C =C(:,1:num);
end
|
github
|
jianxiongxiao/ProfXkit-master
|
read_wobj.m
|
.m
|
ProfXkit-master/obj2off/read_wobj.m
| 14,369 |
utf_8
|
1dac5218ab27b8c13898d49a05d9a637
|
function OBJ=read_wobj(fullfilename)
% Read the objects from a Wavefront OBJ file
%
% OBJ=read_wobj(filename);
%
% OBJ struct containing:
%
% OBJ.vertices : Vertices coordinates
% OBJ.vertices_texture: Texture coordinates
% OBJ.vertices_normal : Normal vectors
% OBJ.vertices_point : Vertice data used for points and lines
% OBJ.material : Parameters from external .MTL file, will contain parameters like
% newmtl, Ka, Kd, Ks, illum, Ns, map_Ka, map_Kd, map_Ks,
% example of an entry from the material object:
% OBJ.material(i).type = newmtl
% OBJ.material(i).data = 'vase_tex'
% OBJ.objects : Cell object with all objects in the OBJ file,
% example of a mesh object:
% OBJ.objects(i).type='f'
% OBJ.objects(i).data.vertices: [n x 3 double]
% OBJ.objects(i).data.texture: [n x 3 double]
% OBJ.objects(i).data.normal: [n x 3 double]
%
% Example,
% OBJ=read_wobj('examples\example10.obj');
% FV.vertices=OBJ.vertices;
% FV.faces=OBJ.objects(3).data.vertices;
% figure, patch(FV,'facecolor',[1 0 0]); camlight
%
% Function is written by D.Kroon University of Twente (June 2010)
verbose=true;
if(exist('fullfilename','var')==0)
[filename, filefolder] = uigetfile('*.obj', 'Read obj-file');
fullfilename = [filefolder filename];
end
filefolder = fileparts( fullfilename);
if(verbose),disp(['Reading Object file : ' fullfilename]); end
% Read the DI3D OBJ textfile to a cell array
file_words = file2cellarray( fullfilename);
% Remove empty cells, merge lines split by "\" and convert strings with values to double
[ftype fdata]= fixlines(file_words);
% Vertex data
vertices=[]; nv=0;
vertices_texture=[]; nvt=0;
vertices_point=[]; nvp=0;
vertices_normal=[]; nvn=0;
material=[];
% Surface data
no=0;
% Loop through the Wavefront object file
for iline=1:length(ftype)
if(mod(iline,10000)==0),
if(verbose),disp(['Lines processed : ' num2str(iline)]); end
end
type=ftype{iline}; data=fdata{iline};
% Switch on data type line
switch(type)
case{'mtllib'}
if(iscell(data))
datanew=[];
for i=1:length(data)
datanew=[datanew data{i}];
if(i<length(data)), datanew=[datanew ' ']; end
end
data=datanew;
end
filename_mtl=fullfile(filefolder,data);
material=readmtl(filename_mtl,verbose);
case('v') % vertices
nv=nv+1;
if(length(data)==3)
% Reserve block of memory
if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:3)=0; end
% Add to vertices list X Y Z
vertices(nv,1:3)=data;
else
% Reserve block of memory
if(mod(nv,10000)==1), vertices(nv+1:nv+10001,1:4)=0; end
% Add to vertices list X Y Z W
vertices(nv,1:4)=data;
end
case('vp')
% Specifies a point in the parameter space of curve or surface
nvp=nvp+1;
if(length(data)==1)
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1)=0; end
% Add to vertices point list U
vertices_point(nvp,1)=data;
elseif(length(data)==2)
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:2)=0; end
% Add to vertices point list U V
vertices_point(nvp,1:2)=data;
else
% Reserve block of memory
if(mod(nvp,10000)==1), vertices_point(nvp+1:nvp+10001,1:3)=0; end
% Add to vertices point list U V W
vertices_point(nvp,1:3)=data;
end
case('vn')
% A normal vector
nvn=nvn+1; if(mod(nvn,10000)==1), vertices_normal(nvn+1:nvn+10001,1:3)=0; end
% Add to vertices list I J K
vertices_normal(nvn,1:3)=data;
case('vt')
% Vertices Texture Coordinate in photo
% U V W
nvt=nvt+1;
if(length(data)==1)
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1)=0; end
% Add to vertices texture list U
vertices_texture(nvt,1)=data;
elseif(length(data)==2)
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:2)=0; end
% Add to vertices texture list U V
vertices_texture(nvt,1:2)=data;
else
% Reserve block of memory
if(mod(nvt,10000)==1), vertices_texture(nvt+1:nvt+10001,1:3)=0; end
% Add to vertices texture list U V W
vertices_texture(nvt,1:3)=data;
end
case('l')
no=no+1;
%if(mod(no,10000)==1)
% objects(no+10001).data=0;
%end
array_vertices=[];
array_texture=[];
for i=1:length(data),
switch class(data)
case 'cell'
tvals=str2double(stringsplit(data{i},'/'));
case 'string'
tvals=str2double(stringsplit(data,'/'));
otherwise
tvals=data(i);
end
val=tvals(1);
if(val<0), val=val+1+nv; end
array_vertices(i)=val;
if(length(tvals)>1),
val=tvals(2);
if(val<0), val=val+1+nvt; end
array_texture(i)=val;
end
end
objects(no).type='l';
objects(no).data.vertices=array_vertices;
objects(no).data.texture=array_texture;
case('f')
no=no+1;
%if(mod(no,10000)==1)
% objects(no+10001).data=0;
%end
array_vertices=[];
array_texture=[];
array_normal=[];
for i=1:length(data);
switch class(data)
case 'cell'
tvals=str2double(stringsplit(data{i},'/'));
case 'string'
tvals=str2double(stringsplit(data,'/'));
otherwise
tvals=data(i);
end
val=tvals(1);
if(val<0), val=val+1+nv; end
array_vertices(i)=val;
if(length(tvals)>1),
if(isfinite(tvals(2)))
val=tvals(2);
if(val<0), val=val+1+nvt; end
array_texture(i)=val;
end
end
if(length(tvals)>2),
val=tvals(3);
if(val<0), val=val+1+nvn; end
array_normal(i)=val;
end
end
% A face of more than 3 indices is always split into
% multiple faces of only 3 indices.
objects(no).type='f';
findex=1:min (3,length(array_vertices));
objects(no).data.vertices=array_vertices(findex);
if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end
if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end
for i=1:length(array_vertices)-3;
no=no+1; %if(mod(no,10000)==1), objects(no+10001).data=0; end
findex=[1 2+i 3+i];
findex(findex>length(array_vertices))=findex(findex>length(array_vertices))-length(array_vertices);
objects(no).type='f';
objects(no).data.vertices=array_vertices(findex);
if(~isempty(array_texture)),objects(no).data.texture=array_texture(findex); end
if(~isempty(array_normal)),objects(no).data.normal=array_normal(findex); end
end
case{'#','$'}
% Comment
tline=' %';
if(iscell(data))
for i=1:length(data), tline=[tline ' ' data{i}]; end
else
tline=[tline data];
end
if(verbose), disp(tline); end
case{''}
otherwise
no=no+1;
%if(mod(no,10000)==1), objects(no+10001).data=0; end
objects(no).type=type;
objects(no).data=data;
end
end
% Initialize new object list, which will contain the "collapsed" objects
objects2(no).data=0;
index=0;
i=0;
while (i<no), i=i+1;
type=objects(i).type;
% First face found
if((length(type)==1)&&(type(1)=='f'))
% Get number of faces
for j=i:no
type=objects(j).type;
if((length(type)~=1)||(type(1)~='f'))
j=j-1; break;
end
end
numfaces=(j-i)+1;
index=index+1;
objects2(index).type='f';
% Process last face first to allocate memory
objects2(index).data.vertices(numfaces,:)= objects(i).data.vertices;
if(isfield(objects(i).data,'texture'))
objects2(index).data.texture(numfaces,:) = objects(i).data.texture;
else
objects2(index).data.texture=[];
end
if(isfield(objects(i).data,'normal'))
objects2(index).data.normal(numfaces,:) = objects(i).data.normal;
else
objects2(index).data.normal=[];
end
% All faces to arrays
for k=1:numfaces
objects2(index).data.vertices(k,:)= objects(i+k-1).data.vertices;
if(isfield(objects(i).data,'texture'))
objects2(index).data.texture(k,:) = objects(i+k-1).data.texture;
end
if(isfield(objects(i).data,'normal'))
objects2(index).data.normal(k,:) = objects(i+k-1).data.normal;
end
end
i=j;
else
index=index+1;
objects2(index).type=objects(i).type;
objects2(index).data=objects(i).data;
end
end
% Add all data to output struct
OBJ.objects=objects2(1:index);
OBJ.material=material;
OBJ.vertices=vertices(1:nv,:);
OBJ.vertices_point=vertices_point(1:nvp,:);
OBJ.vertices_normal=vertices_normal(1:nvn,:);
OBJ.vertices_texture=vertices_texture(1:nvt,:);
if(verbose),disp('Finished Reading Object file'); end
function twords=stringsplit(tline,tchar)
% Get start and end position of all "words" separated by a char
i=find(tline(2:end-1)==tchar)+1; i_start=[1 i+1]; i_end=[i-1 length(tline)];
% Create a cell array of the words
twords=cell(1,length(i_start)); for j=1:length(i_start), twords{j}=tline(i_start(j):i_end(j)); end
function file_words=file2cellarray(filename)
% Open a DI3D OBJ textfile
fid=fopen(filename,'r');
file_text=fread(fid, inf, 'uint8=>char')';
fclose(fid);
file_lines = regexp(file_text, '\n+', 'split');
file_words = regexp(file_lines, '\s+', 'split');
function [ftype fdata]=fixlines(file_words)
ftype=cell(size(file_words));
fdata=cell(size(file_words));
iline=0; jline=0;
while(iline<length(file_words))
iline=iline+1;
twords=removeemptycells(file_words{iline});
if(~isempty(twords))
% Add next line to current line when line end with '\'
while(strcmp(twords{end},'\')&&iline<length(file_words))
iline=iline+1;
twords(end)=[];
twords=[twords removeemptycells(file_words{iline})];
end
% Values to double
type=twords{1};
stringdold=true;
j=0;
switch(type)
case{'#','$'}
for i=2:length(twords)
j=j+1; twords{j}=twords{i};
end
otherwise
for i=2:length(twords)
str=twords{i};
val=str2double(str);
stringd=~isfinite(val);
if(stringd)
j=j+1; twords{j}=str;
else
if(stringdold)
j=j+1; twords{j}=val;
else
twords{j}=[twords{j} val];
end
end
stringdold=stringd;
end
end
twords(j+1:end)=[];
jline=jline+1;
ftype{jline}=type;
if(length(twords)==1), twords=twords{1}; end
fdata{jline}=twords;
end
end
ftype(jline+1:end)=[];
fdata(jline+1:end)=[];
function b=removeemptycells(a)
j=0; b={};
for i=1:length(a);
if(~isempty(a{i})),j=j+1; b{j}=a{i}; end;
end
function objects=readmtl(filename_mtl,verbose)
if(verbose),disp(['Reading Material file : ' filename_mtl]); end
file_words=file2cellarray(filename_mtl);
% Remove empty cells, merge lines split by "\" and convert strings with values to double
[ftype fdata]= fixlines(file_words);
% Surface data
objects.type(length(ftype))=0;
objects.data(length(ftype))=0;
no=0;
% Loop through the Wavefront object file
for iline=1:length(ftype)
type=ftype{iline}; data=fdata{iline};
% Switch on data type line
switch(type)
case{'#','$'}
% Comment
tline=' %';
if(iscell(data))
for i=1:length(data), tline=[tline ' ' data{i}]; end
else
tline=[tline data];
end
if(verbose), disp(tline); end
case{''}
otherwise
no=no+1;
if(mod(no,10000)==1), objects(no+10001).data=0; end
objects(no).type=type;
objects(no).data=data;
end
end
objects=objects(1:no);
if(verbose),disp('Finished Reading Material file'); end
|
github
|
jianxiongxiao/ProfXkit-master
|
quaternion.m
|
.m
|
ProfXkit-master/rectifyroom/quaternion.m
| 85,196 |
utf_8
|
2aebad0378f433bf4d26b837b20047a3
|
classdef quaternion
% classdef quaternion, implements quaternion mathematics and 3D rotations
%
% Properties (SetAccess = protected):
% e(4,1) components, basis [1; i; j; k]: e(1) + i*e(2) + j*e(3) + k*e(4)
% i*j=k, j*i=-k, j*k=i, k*j=-i, k*i=j, i*k=-j, i*i = j*j = k*k = -1
%
% Constructors:
% q = quaternion scalar zero quaternion, q.e = [0;0;0;0]
% q = quaternion(x) x is a matrix size [4,s1,s2,...] or [s1,4,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% x(1:4,i1,i2,...) or x(i1,1:4,i2,...).'
% q = quaternion(v) v is a matrix size [3,s1,s2,...] or [s1,3,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% [0;v(1:3,i1,i2,...)] or [0;v(i1,1:3,i2,...).']
% q = quaternion(c) c is a complex matrix size [s1,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% [real(c(i1,i2,...));imag(c(i1,i2,...));0;0]
% q = quaternion(x1,x2) x1,x2 are matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [x1(i1,i2,...);x2(i1,i2,...);0;0]
% q = quaternion(v1,v2,v3) v1,v2,v3 matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [0;v1(i1,i2,...);v2(i1,i2,...);...
% v3(i1,i2,...)]
% q = quaternion(x1,x2,x3,x4) x1,x2,x3,x4 matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [x1(i1,i2,...);x2(i1,i2,...);...
% x3(i1,i2,...);x4(i1,i2,...)]
%
% Quaternion array constructor methods:
% q = quaternion.eye(N) quaternion NxN identity matrix
% q = quaternion.nan(siz) q(:).e = [NaN;NaN;NaN;NaN]
% q = quaternion.ones(siz) q(:).e = [1;0;0;0]
% q = quaternion.rand(siz) uniform random quaternions, NOT normalized
% to 1, 0 <= q.e(1) <= 1, -1 <= q.e(2:4) <= 1
% q = quaternion.randRot(siz) random quaternions uniform in rotation space
% q = quaternion.zeros(siz) q(:).e = [0;0;0;0]
%
% Rotation constructor methods (all lower case):
% q = quaternion.angleaxis(angle,axis)
% angle is an array in radians, axis is an array
% of vectors size [3,s1,s2,...] or [s1,3,s2,...],
% q is size [s1,s2,...], quaternions normalized to 1
% equivalent to rotations about axis by angle
% q = quaternion.eulerangles(axes,angles) or
% q = quaternion.eulerangles(axes,ang1,ang2,ang3)
% axes is a string array or cell string array,
% '123' = 'xyz' = 'XYZ' = 'ijk', etc.,
% angles is an array of Euler angles in radians,
% size [3,s1,s2,...] or [s1,3,s2,...], or
% (ang1, ang2, ang3) are arrays or scalars of
% Euler angles in radians, q is size
% [s1,s2,...], quaternions normalized to 1
% equivalent to Euler Angle rotations
% q = quaternion.rotateutov(u,v,dimu,dimv)
% quaternions normalized to 1 that rotate 3
% element vectors u into the directions of 3
% element vectors v
% q = quaternion.rotationmatrix(R)
% R is an array of rotation or Direction Cosine
% Matrices size [3,3,s1,s2,...] with det(R) == 1,
% q(i1,i2,...) = quaternions normalized to 1,
% equivalent to R(1:3,1:3,i1,i2,...)
%
% Rotation methods (Mixed Case):
% [angle,axis] = AngleAxis(q) angles in radians, unit vector rotation axes
% equivalent to q
% qd = Derivative(q,w) quaternion derivatives, w are 3 component
% angular velocity vectors, qd = 0.5*q*quaternion(w)
% angles = EulerAngles(q,axes) angles are 3 Euler angles equivalent to q, axes
% are strings or cell strings, '123' = 'xyz', etc.
% [omega,axis] = OmegaAxis(q,t,dim)
% instantaneous angular velocities and rotation axes
% PlotRotation(q,interval) plot columns of rotation matrices of q,
% pause interval between figure updates in seconds
% [q1,w1,t1] = PropagateEulerEq(q0,w0,I,t,@torque,odeoptions)
% Euler equation numerical propagator, see
% help quaternion.PropagateEulerEq
% vp = RotateVector(q,v,dim) vp are 3 component vectors, rotations q acting
% on vectors v, uses rotation matrix multiplication
% vp = RotateVectorQ(q,v,dim) vp are 3 component vectors, rotations q acting
% on vectors v, uses quaternion multiplication,
% RotateVector is 7 times faster than RotateVectorQ
% R = RotationMatrix(q) 3x3 rotation matrices equivalent to q
%
% Note:
% In all rotation operations, the rotations operate from left to right on
% 3x1 column vectors and create rotated vectors, not representations of
% those vectors in rotated coordinate systems.
% For Euler angles, '123' means rotate the vector about x first, about y
% second, about z third, i.e.:
% vp = rotate(z,angle(3)) * rotate(y,angle(2)) * rotate(x,angle(1)) * v
%
% Ordinary methods:
% n = abs(q) quaternion norm, n = sqrt( sum( q.e.^2 ))
% q3 = bsxfun(func,q1,q2) binary singleton expansion of operation func
% c = complex(q) complex( real(q), imag(q) )
% qc = conj(q) quaternion conjugate, qc.e =
% [q.e(1);-q.e(2);-q.e(3);-q.e(4)]
% qt = ctranspose(q) qt = q'; quaternion conjugate transpose,
% 2-D (or scalar) q only
% qp = cumprod(q,dim) cumulative quaternion array product over
% dimension dim
% qs = cumsum(q,dim) cumulative quaternion array sum over dimension dim
% qd = diff(q,ord,dim) quaternion array difference, order ord, over
% dimension dim
% ans = display(q) 'q = ( e(1) ) + i( e(2) ) + j( e(3) ) + k( e(4) )'
% d = dot(q1,q2) quaternion element dot product, d = dot(q1.e,q2.e)
% d = double(q) d = q.e; if size(q) == [s1,s2,...], size(d) ==
% [4,s1,s2,...]
% l = eq(q1,q2) quaternion equality, l = all( q1.e == q2.e )
% l = equiv(q1,q2,tol) quaternion rotational equivalence, within
% tolerance tol, l = (q1 == q2) | (q1 == -q2)
% qe = exp(q) quaternion exponential, v = q.e(2:4), qe.e =
% exp(q.e(1))*[cos(|v|);v.*sin(|v|)./|v|]
% ei = imag(q) imaginary e(2) components
% qi = interp1(t,q,ti,method) interpolate quaternion array
% qi = inverse(q) quaternion inverse, qi = conj(q)./norm(q).^2,
% q .* qi = qi .*.q = 1 for q ~= 0
% l = isequal(q1,q2,...) true if equal sizes and values
% l = isequaln(q1,q2,...) true if equal including NaNs
% l = isequalwithequalnans(q1,q2,...) true if equal including NaNs
% l = isfinite(q) true if all( isfinite( q.e ))
% l = isinf(q) true if any( isinf( q.e ))
% l = isnan(q) true if any( isnan( q.e ))
% ej = jmag(q) e(3) components
% ek = kmag(q) e(4) components
% q3 = ldivide(q1,q2) quaternion left division, q3 = q1 \. q2 =
% inverse(q1) *. q2
% ql = log(q) quaternion logarithm, v = q.e(2:4), ql.e =
% [log(|q|);v.*acos(q.e(1)./|q|)./|v|]
% q3 = minus(q1,q2) quaternion subtraction, q3 = q1 - q2
% q3 = mldivide(q1,q2) left division only defined for scalar q1
% qp = mpower(q,p) quaternion matrix power, qp = q^p, p scalar
% integer >= 0, q square quaternion matrix
% q3 = mrdivide(q1,q2) right division only defined for scalar q2
% q3 = mtimes(q1,q2) 2-D matrix quaternion multiplication, q3 = q1 * q2
% l = ne(q1,q2) quaternion inequality, l = ~all( q1.e == q2.e )
% n = norm(q) quaternion norm, n = sqrt( sum( q.e.^2 ))
% [q,n] = normalize(q) make quaternion norm == 1, unless q == 0,
% n = matrix of previous norms
% q3 = plus(q1,q2) quaternion addition, q3 = q1 + q2
% qp = power(q,p) quaternion power, qp = q.^p
% qp = prod(q,dim) quaternion array product over dimension dim
% qp = product(q1,q2) quaternion product of scalar quaternions,
% qp = q1 .* q2, noncommutative
% q3 = rdivide(q1,q2) quaternion right division, q3 = q1 ./ q2 =
% q1 .* inverse(q2)
% er = real(q) real e(1) components
% qs = slerp(q0,q1,t) quaternion spherical linear interpolation
% qr = sqrt(q) qr = q.^0.5, square root
% qs = sum(q,dim) quaternion array sum over dimension dim
% q3 = times(q1,q2) matrix component quaternion multiplication,
% q3 = q1 .* q2, noncommutative
% qm = uminus(q) quaternion negation, qm = -q
% qp = uplus(q) quaternion unitary plus, qp = +q
% ev = vector(q) vector e(2:4) components
%
% Author:
% Mark Tincknell, MIT LL, 29 July 2011, revised 22 November 2013
properties (SetAccess = protected)
e = zeros(4,1);
end % properties
% Array constructors
methods
function q = quaternion( varargin ) % (constructor)
perm = [];
sqz = false;
switch nargin
case 0 % nargin == 0
q.e = zeros(4,1);
return;
case 1 % nargin == 1
siz = size( varargin{1} );
nel = prod( siz );
if nel == 0
q = quaternion.empty;
return;
elseif isa( varargin{1}, 'quaternion' )
q = varargin{1};
return;
elseif (nel == 1) || ~isreal( varargin{1}(:) )
for iel = nel : -1 : 1
q(iel).e = chop( [real(varargin{1}(iel)); ...
imag(varargin{1}(iel)); ...
0; ...
0] );
end
q = reshape( q, siz );
return;
end
[arg4, dim4, perm4] = finddim( varargin{1}, 4 );
if dim4 > 0
siz(dim4) = 1;
nel = prod( siz );
if dim4 > 1
perm = perm4;
else
sqz = true;
end
for iel = nel : -1 : 1
q(iel).e = chop( arg4(:,iel) );
end
else
[arg3, dim3, perm3] = finddim( varargin{1}, 3 );
if dim3 > 0
siz(dim3) = 1;
nel = prod( siz );
if dim3 > 1
perm = perm3;
else
sqz = true;
end
for iel = nel : -1 : 1
q(iel).e = chop( [0; arg3(:,iel)] );
end
else
error( 'Invalid input' );
end
end
case 2 % nargin == 2
% real-imaginary only (no j or k) inputs
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
0;
0] );
end
case 3 % nargin == 3
% vector inputs (no real, only i, j, k)
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [0; ...
varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
varargin{3}(min(iel,na(3)))] );
end
otherwise % nargin >= 4
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
varargin{3}(min(iel,na(3))); ...
varargin{4}(min(iel,na(4)))] );
end
end % switch nargin
if nel == 0
q = quaternion.empty;
end
q = reshape( q, siz );
if ~isempty( perm )
q = ipermute( q, perm );
end
if sqz
q = squeeze( q );
end
end % quaternion (constructor)
% Ordinary methods
function n = abs( q )
n = q.norm;
end % abs
function q3 = bsxfun( func, q1, q2 )
% function q3 = bsxfun( func, q1, q2 )
% Binary Singleton Expansion for quaternion arrays. Apply the element by
% element binary operation specified by the function handle func to arrays
% q1 and q2. All dimensions of q1 and q2 must either agree or be length 1.
% Inputs:
% func function handle (e.g. @plus) of quaternion function or operator
% q1(n1) quaternion array
% q2(n2) quaternion array
% Output:
% q3(n3) quaternion array of function or operator outputs
% size(q3) = max( size(q1), size(q2) )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
s1 = size( q1 );
s2 = size( q2 );
nd1 = length( s1 );
nd2 = length( s2 );
s1 = [s1, ones(1,nd2-nd1)];
s2 = [s2, ones(1,nd1-nd2)];
if ~all( (s1 == s2) | (s1 == 1) | (s2 == 1) )
error( 'Non-singleton dimensions of q1 and q2 must match each other' );
end
c1 = num2cell( s1 );
c2 = num2cell( s2 );
s3 = max( s1, s2 );
nd3 = length( s3 );
n3 = prod( s3 );
q3 = quaternion.nan( s3 );
for i3 = 1 : n3
[ix3{1:nd3}] = ind2sub( s3, i3 );
ix1 = cellfun( @min, ix3, c1, 'UniformOutput', false );
ix2 = cellfun( @min, ix3, c2, 'UniformOutput', false );
q3(i3) = func( q1(ix1{:}), q2(ix2{:}) );
end
end % bsxfun
function c = complex( q )
c = complex( real( q ), imag( q ));
end % complex
function qc = conj( q )
d = double( q );
qc = reshape( quaternion( d(1,:), -d(2,:), -d(3,:), -d(4,:) ), ...
size( q ));
end % conj
function qt = ctranspose( q )
qt = transpose( q.conj );
end % ctranspose
function qp = cumprod( q, dim )
% function qp = cumprod( q, dim )
% cumulative quaternion array product, dim defaults to first dimension of
% length > 1
if isempty( q )
qp = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
qp = q;
for is = 2 : size(q,1)
qp(is,:) = qp(is-1,:) .* q(is,:);
end
if dim > 1
qp = ipermute( qp, perm );
end
end % cumprod
function qs = cumsum( q, dim )
% function qs = cumsum( q, dim )
% cumulative quaternion array sum, dim defaults to first dimension of
% length > 1
if isempty( q )
qs = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
qs = q;
for is = 2 : size(q,1)
qs(is,:) = qs(is-1,:) + q(is,:);
end
if dim > 1
qs = ipermute( qs, perm );
end
end % cumsum
function qd = diff( q, ord, dim )
% function qd = diff( q, ord, dim )
% quaternion array difference, ord is the order of difference (default = 1)
% dim defaults to first dimension of length > 1
if isempty( q )
qd = q;
return;
end
if (nargin < 2) || isempty( ord )
ord = 1;
end
if ord <= 0
qd = q;
return;
end
if (nargin < 3) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
if siz(1) <= 1
qd = quaternion.empty;
return;
end
qd = quaternion.zeros( [(siz(1)-1), siz(2:end)] );
for is = 1 : siz(1)-1
qd(is,:) = q(is+1,:) - q(is,:);
end
ord = ord - 1;
if ord > 0
qd = diff( qd, ord, 1 );
end
if dim > 1
qd = ipermute( qd, perm );
end
end % diff
function display( q )
if ~isequal( get(0,'FormatSpacing'), 'compact' )
disp(' ');
end
if isempty( q )
fprintf( '%s \t= ([]) + i([]) + j([]) + k([])\n', inputname(1) )
return;
end
siz = size( q );
nel = [1 cumprod( siz )];
ndm = length( siz );
for iel = 1 : nel(end)
if nel(end) == 1
sub = '';
else
sub = ')';
jel = iel - 1;
for idm = ndm : -1 : 1
idx = floor( jel / nel(idm) ) + 1;
sub = [',' int2str(idx) sub]; %#ok<AGROW>
jel = rem( jel, nel(idm) );
end
sub(1) = '(';
end
fprintf( '%s%s \t= (%-12.5g) + i(%-12.5g) + j(%-12.5g) + k(%-12.5g)\n', ...
inputname(1), sub, q(iel).e )
end
end % display
function d = dot( q1, q2 )
% function d = dot( q1, q2 )
% quaternion element dot product: d = dot( q1.e, q2.e ), using binary
% singleton expansion of quaternion arrays
% dn = dot( q1, q2 )/( norm(q1) * norm(q2) ) is the cosine of the angle in
% 4D space between 4D vectors q1.e and q2.e
d = squeeze( sum( bsxfun( @times, double( q1 ), double( q2 )), 1 ));
end % dot
function d = double( q )
siz = size( q );
d = reshape( [q.e], [4 siz] );
d = chop( d );
end % double
function l = eq( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
l = logical([]);
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
l = bsxfun( @eq, [q1.e], [q2.e] );
l = reshape( all( l, 1 ), siz );
end % eq
function l = equiv( q1, q2, tol )
% function l = equiv( q1, q2, tol )
% quaternion rotational equivalence, within tolerance tol,
% l = (q1 == q2) | (q1 == -q2)
% optional argument tol (default = eps) sets tolerance for difference
% from exact equality
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
if (nargin < 3) || isempty( tol )
tol = eps;
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
l = logical([]);
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
dm = chop( bsxfun( @minus, [q1.e], [q2.e] ), tol );
dp = chop( bsxfun( @plus, [q1.e], [q2.e] ), tol );
l = all( (dm == 0) | (dp == 0), 1 );
l = reshape( l, siz );
end % equiv
function qe = exp( q )
% function qe = exp( q )
% quaternion exponential, v = q.e(2:4),
% qe.e = exp(q.e(1))*[cos(|v|);v.*sin(|v|)./|v|]
d = double( q );
siz = size( d );
od = ones( 1, ndims( q ));
vn = reshape( sqrt( sum( d(2:4,:).^2, 1 )), [1 siz(2:end)] );
cv = cos( vn );
sv = sin( vn );
n0 = vn ~= 0;
sv(n0) = sv(n0) ./ vn(n0);
sv = repmat( sv, [3, od] );
ex = repmat( reshape( exp( d(1,:) ), [1 siz(2:end)] ), [4, od] );
de = ex .* [ cv; sv .* reshape( d(2:4,:), [3 siz(2:end)] )];
qe = reshape( quaternion( de(1,:), de(2,:), de(3,:), de(4,:) ), ...
size( q ));
end % exp
function ei = imag( q )
siz = size( q );
d = double( q );
ei = reshape( d(2,:), siz );
end % imag
function qi = interp1( varargin )
% function qi = interp1( t, q, ti, method ) or
% qi = q.interp1( t, ti, method ) or
% qi = interp1( q, ti, method )
% Interpolate quaternion array. If q are rotation quaternions (i.e.
% normalized to 1), then -q is equivalent to q, and the sign of q to use as
% the second knot of the interpolation is chosen by which ever is closer to
% the first knot. Extrapolation (i.e. ti < min(t) or ti > max(t)) gives
% qi = quaternion.nan.
% Inputs:
% t(nt) array of ordinates (e.g. times); if t is not provided t=1:nt
% q(nt,nq) quaternion array
% ti(ni) array of query (interpolation) points, t(1) <= ti <= t(end)
% method [OPTIONAL] 'slerp' or 'linear'; default = 'slerp'
% Output:
% qi(ni,nq) interpolated quaternion array
nna = nnz( ~cellfun( @ischar, varargin ));
im = 4;
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
siq = size( q );
if nna == 2
if isrow( q )
t = (1 : siq(2)).';
else
t = (1 : siq(1)).';
end
ti = varargin{2}(:);
im = 3;
elseif isempty( varargin{2} )
if isrow( q )
t = (1 : siq(2)).';
else
t = (1 : siq(1)).';
end
ti = varargin{3}(:);
else
t = varargin{2}(:);
ti = varargin{3}(:);
end
elseif isa( varargin{2}, 'quaternion' )
t = varargin{1}(:);
q = varargin{2};
ti = varargin{3}(:);
siq = size( q );
else
error( 'Input q must be a quaterion' );
end
neq = prod( siq );
if neq == 0
qi = quaternion.empty;
return;
end
nt = numel( t );
if siq(1) == nt
dim = 1;
else
[q, dim, perm] = finddim( q, nt );
if dim == 0
error( 'q must have a dimension the same size as t' );
end
end
iNf = interp1( t, (1:nt).', ti );
iN = max( 1, min( nt-1, floor( iNf )));
jN = max( 2, min( nt, ceil( iNf )));
iNm = repmat( iNf - iN, [1, neq / nt] );
% If q are rotation quaternions (i.e. all normalized to 1), then -q
% represents the same rotation. Pick the sign of +/-q that has the closest
% dot product to use as the second knot of the interpolation.
qj = q(jN,:);
if all( abs( norm( q(:) ) - 1 ) <= eps(16) )
qd = dot( q(iN,:), qj );
lq = qd < -qd;
qj(lq) = -qj(lq);
end
if (length( varargin ) >= im) && ...
(strncmpi( 'linear', varargin{im}, length( varargin{im} )))
qi = (1 - iNm) .* q(iN,:) + iNm .* qj;
else
qi = slerp( q(iN,:), qj, iNm );
end
if length( siq ) > 2
sin = siq;
sin(dim) = numel( ti );
sin = circshift( sin, [0, 1-dim] );
qi = reshape( qi, sin );
end
if dim > 1
qi = ipermute( qi, perm );
end
end % interp1
function qi = inverse( q )
% function qi = inverse( q )
% quaternion inverse, qi = conj(q)/norm(q)^2, q*qi = qi*q = 1 for q ~= 0
if isempty( q )
qi = q;
return;
end
d = double( q );
d(2:4,:) = -d(2:4,:);
n2 = repmat( sum( d.^2, 1 ), 4, ones( 1, ndims( d ) - 1 ));
ne0 = n2 ~= 0;
di = Inf( size( d ));
di(ne0) = d(ne0) ./ n2(ne0);
qi = reshape( quaternion( di(1,:), di(2,:), di(3,:), di(4,:) ), ...
size( q ));
end % inverse
function l = isequal( q1, varargin )
% function l = isequal( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequal( [q1.e], [q2.e] )
return;
end
end
end
l = true;
end % isequal
function l = isequaln( q1, varargin )
% function l = isequaln( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequaln( [q1.e], [q2.e] )
return;
end
end
end
l = true;
end % isequaln
function l = isequalwithequalnans( q1, varargin )
% function l = isequalwithequalnans( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequalwithequalnans( [q1.e], [q2.e] ) %#ok<FPARK>
return;
end
end
end
l = true;
end % isequalwithequalnans
function l = isfinite( q )
% function l = isfinite( q ), l = all( isfinite( q.e ))
d = [q.e];
l = reshape( all( isfinite( d ), 1 ), size( q ));
end % isfinite
function l = isinf( q )
% function l = isinf( q ), l = any( isinf( q.e ))
d = [q.e];
l = reshape( any( isinf( d ), 1 ), size( q ));
end % isinf
function l = isnan( q )
% function l = isnan( q ), l = any( isnan( q.e ))
d = [q.e];
l = reshape( any( isnan( d ), 1 ), size( q ));
end % isnan
function ej = jmag( q )
siz = size( q );
d = double( q );
ej = reshape( d(3,:), siz );
end % jmag
function ek = kmag( q )
siz = size( q );
d = double( q );
ek = reshape( d(4,:), siz );
end % kmag
function q3 = ldivide( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)).inverse, ...
q2(min(iel,ne2)) );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % ldivide
function ql = log( q )
% function ql = log( q )
% quaternion logarithm, v = q.e(2:4), ql.e = [log(|q|);v.*acos(q.e(1)./|q|)./|v|]
% logarithm of negative real quaternions is ql.e = [log(|q|);pi;0;0]
d = double( q );
d2 = d.^2;
siz = size( d );
od = ones( 1, ndims( q ));
[vn,qn] = deal( zeros( [1 siz(2:end)] ));
vn(:) = sqrt( sum( d2(2:4,:), 1 ));
qn(:) = sqrt( sum( d2(1:4,:), 1 ));
lq = log( qn );
d1 = reshape( d(1,:), [1 siz(2:end)] );
nq = qn ~= 0;
d1(nq) = d1(nq) ./ qn(nq);
ac = acos( d1 );
nv = vn ~= 0;
ac(nv) = ac(nv) ./ vn(nv);
ac = reshape( repmat( ac, [3, od] ), 3, [] );
va = reshape( d(2:4,:) .* ac, [3 siz(2:end)] );
nn = (d1 < 0) & (vn == 0);
va(1,nn)= pi;
dl = [ lq; va ];
ql = reshape( quaternion( dl(1,:), dl(2,:), dl(3,:), dl(4,:) ), ...
size( q ));
end % log
function q3 = minus( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
d3 = bsxfun( @minus, [q1.e], [q2.e] );
q3 = quaternion( d3(1,:), d3(2,:), d3(3,:), d3(4,:) );
q3 = reshape( q3, siz );
end % minus
function q3 = mldivide( q1, q2 )
% function q3 = mldivide( q1, q2 ), left division only defined for scalar q1
if numel( q1 ) > 1
error( 'Left matix division undefined for quaternion arrays' );
end
q3 = ldivide( q1, q2 );
end % mldivide
function qp = mpower( q, p )
% function qp = mpower( q, p ), quaternion matrix power
siq = size( q );
neq = prod( siq );
nep = numel( p );
if neq == 1
qp = power( q, p );
return;
elseif isa( p, 'quaternion' )
error( 'Quaternion as matrix exponent is not defined' );
end
if (neq == 0) || (nep == 0)
qp = quaternion.empty;
return;
elseif (nep > 1) || (mod( p, 1 ) ~= 0) || (p < 0) || ...
(numel( siq ) > 2) || (siq(1) ~= siq(2))
error( 'Inputs must be a scalar non-negative integer power and a square quaternion matrix' );
elseif p == 0
qp = quaternion.eye( siq(1) );
return;
end
qp = q;
for ip = 2 : p
qp = qp * q;
end
end % mpower
function q3 = mrdivide( q1, q2 )
% function q3 = mrdivide( q1, q2 ), right division only defined for scalar q2
if numel( q2 ) > 1
error( 'Right matix division undefined for quaternion arrays' );
end
q3 = rdivide( q1, q2 );
end % mrdivide
function q3 = mtimes( q1, q2 )
% function q3 = mtimes( q1, q2 )
% q3 = matrix quaternion product of 2-D conformable quaternion matrices q1
% and q2
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 1) || (ne2 == 1)
q3 = times( q1, q2 );
return;
end
if (length( si1 ) ~= 2) || (length( si2 ) ~= 2)
error( 'Input arguments must be 2-D' );
end
if si1(2) ~= si2(1)
error( 'Inner matrix dimensions must agree' );
end
q3 = repmat( quaternion, [si1(1) si2(2)] );
for i1 = 1 : si1(1)
for i2 = 1 : si2(2)
for i3 = 1 : si1(2)
q3(i1,i2) = q3(i1,i2) + product( q1(i1,i3), q2(i3,i2) );
end
end
end
end % mtimes
function l = ne( q1, q2 )
l = ~eq( q1, q2 );
end % ne
function n = norm( q )
n = shiftdim( sqrt( sum( double( q ).^2, 1 )), 1 );
end % norm
function [q, n] = normalize( q )
% function [q, n] = normalize( q )
% q = quaternions with norm == 1 (unless q == 0), n = former norms
siz = size( q );
nel = prod( siz );
if nel == 0
if nargout > 1
n = zeros( siz );
end
return;
elseif nel > 1
nel = [];
end
d = double( q );
n = sqrt( sum( d.^2, 1 ));
if all( n(:) == 1 )
if nargout > 1
n = shiftdim( n, 1 );
end
return;
end
n4 = repmat( n, 4, nel );
ne0 = (n4 ~= 0) & (n4 ~= 1);
d(ne0) = d(ne0) ./ n4(ne0);
q = reshape( quaternion( d(1,:), d(2,:), d(3,:), d(4,:) ), siz );
if nargout > 1
n = shiftdim( n, 1 );
end
end % normalize
function q3 = plus( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
d3 = bsxfun( @plus, [q1.e], [q2.e] );
q3 = quaternion( d3(1,:), d3(2,:), d3(3,:), d3(4,:) );
q3 = reshape( q3, siz );
end % plus
function qp = power( q, p )
% function qp = power( q, p ), quaternion power
siq = size( q );
sip = size( p );
neq = prod( siq );
nep = prod( sip );
if (neq == 0) || (nep == 0)
qp = quaternion.empty;
return;
elseif ~isequal( siq, sip ) && (neq ~= 1) && (nep ~= 1)
error( 'Matrix dimensions must agree' );
end
qp = exp( p .* log( q ));
end % power
function qp = prod( q, dim )
% function qp = prod( q, dim )
% quaternion array product over dimension dim
% dim defaults to first dimension of length > 1
if isempty( q )
qp = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
qp = reshape( q(1,:), [1 siz(2:end)] );
for is = 2 : siz(1)
qp(1,:) = qp(1,:) .* q(is,:);
end
if dim > 1
qp = ipermute( qp, perm );
end
end % prod
function q3 = product( q1, q2 )
% function q3 = product( q1, q2 )
% q3 = quaternion product of scalar quaternions q1 and q2
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
if (numel( q1 ) ~= 1) || (numel( q2 ) ~= 1)
error( 'product not defined for arrays, use mtimes or times' );
end
ee = q1.e * q2.e.';
eo = [ee(1,1) - ee(2,2) - ee(3,3) - ee(4,4); ...
ee(1,2) + ee(2,1) + ee(3,4) - ee(4,3); ...
ee(1,3) - ee(2,4) + ee(3,1) + ee(4,2); ...
ee(1,4) + ee(2,3) - ee(3,2) + ee(4,1)];
eo = chop( eo );
q3 = quaternion( eo(1), eo(2), eo(3), eo(4) );
end % product
function q3 = rdivide( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)), ...
q2(min(iel,ne2)).inverse );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % rdivide
function er = real( q )
siz = size( q );
d = double( q );
er = reshape( d(1,:), siz );
end % real
function qs = slerp( q0, q1, t )
% function qs = slerp( q0, q1, t )
% quaternion spherical linear interpolation, qs = q0.*(q0.inverse.*q1).^t,
% default t = 0.5; see http://en.wikipedia.org/wiki/Slerp
if (nargin < 3) || isempty( t )
t = 0.5;
end
qs = q0 .* (q0.inverse .* q1).^t;
end % slerp
function qr = sqrt( q )
qr = q.^0.5;
end % sqrt
function qs = sum( q, dim )
% function qs = sum( q, dim )
% quaternion array sum over dimension dim
% dim defaults to first dimension of length > 1
if isempty( q )
qs = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
qs = reshape( q(1,:), [1 siz(2:end)] );
for is = 2 : siz(1)
qs(1,:) = qs(1,:) + q(is,:);
end
if dim > 1
qs = ipermute( qs, perm );
end
end % sum
function q3 = times( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)), q2(min(iel,ne2)) );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % times
function qm = uminus( q )
d = -double( q );
qm = reshape( quaternion( d(1,:), d(2,:), d(3,:), d(4,:) ), ...
size( q ));
end % uminus
function qp = uplus( q )
qp = q;
end % uplus
function ev = vector( q )
siz = size( q );
d = double( q );
ev = reshape( d(2:4,:), [3 siz] );
end % vector
function [angle, axis] = AngleAxis( q )
% function [angle, axis] = AngleAxis( q ) or [angle, axis] = q.AngleAxis
% Construct angle-axis pairs equivalent to quaternion rotations
% Input:
% q quaternion array
% Outputs:
% angle rotation angles in radians, 0 <= angle <= 2*pi
% axis 3xN or Nx3 rotation axis unit vectors
% Note: angle and axis are constructed so at least 2 out of 3 elements of
% axis are >= 0.
siz = size( q );
ndm = length( siz );
[angle, s] = deal( zeros( siz ));
axis = zeros( [3 siz] );
nel = prod( siz );
if nel == 0
return;
end
[q, n] = normalize( q );
d = double( q );
neg = repmat( reshape( d(1,:) < 0, [1 siz] ), ...
[4, ones(1,ndm)] );
d(neg) = -d(neg);
angle(1:end)= 2 * acos( d(1,:) );
s(1:end) = sin( 0.5 * angle );
angle(n==0) = 0;
s(s==0) = 1;
s3 = shiftdim( s, -1 );
axis(1:end) = bsxfun( @rdivide, reshape( d(2:4,:), [3 siz] ), s3 );
axis(1,(mod(angle,2*pi)==0)) = 1;
angle = chop( angle );
axis = chop( axis );
% Flip axis so at least 2 out of 3 elements are >= 0
flip = (sum( axis < 0, 1 ) > 1) | ...
((sum( axis == 0, 1 ) == 2) & (any( axis < 0, 1 ) == 1));
angle(flip) = 2 * pi - angle(flip);
flip = repmat( flip, [3, ones(1,ndm)] );
axis(flip) = -axis(flip);
axis = squeeze( axis );
end % AngleAxis
function qd = Derivative( varargin )
% function qd = Derivative( q, w ) or qd = q.Derivative( w )
% Inputs:
% q quaternion array
% w 3xN or Nx3 element angle rate vectors in radians/s
% Output:
% qd quaternion derivatives, qd = 0.5 * q * quaternion(w)
if isa( varargin{1}, 'quaternion' )
qd = 0.5 .* varargin{1} .* quaternion( varargin{2} );
else
qd = 0.5 .* varargin{2} .* quaternion( varargin{1} );
end
end % Derivative
function angles = EulerAngles( varargin )
% function angles = EulerAngles( q, axes ) or angles = q.EulerAngles( axes )
% Construct Euler angle triplets equivalent to quaternion rotations
% Inputs:
% q quaternion array
% axes axes designation strings (e.g. '123' = xyz) or cell strings
% (e.g. {'123'})
% Output:
% angles 3 element Euler Angle vectors in radians
ics = cellfun( @ischar, varargin );
if any( ics )
varargin{ics} = cellstr( varargin{ics} );
else
ics = cellfun( @iscellstr, varargin );
end
if ~any( ics )
error( 'Must provide axes as a string (e.g. ''123'') or cell string (e.g. {''123''})' );
end
siv = cellfun( @size, varargin, 'UniformOutput', false );
axes = varargin{ics};
six = siv{ics};
nex = prod( six );
q = varargin{~ics};
siq = siv{~ics};
neq = prod( siq );
if neq == 1
siz = six;
nel = nex;
elseif nex == 1
siz = siq;
nel = neq;
elseif nex == neq
siz = siq;
nel = neq;
else
error( 'Must have compatible dimensions for quaternion and axes' );
end
angles = zeros( [3 siz] );
q = normalize( q );
for jel = 1 : nel
iel = min( jel, neq );
switch axes{min(jel,nex)}
case {'121', 'xyx', 'XYX', 'iji'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(3)- ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
angles(2,iel) = acos(q(iel).e(1).^2+q(iel).e(2).^2- ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
case {'123', 'xyz', 'XYZ', 'ijk'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(4).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
case {'131', 'xzx', 'XZX', 'iki'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
angles(2,iel) = acos(q(iel).e(1).^2+q(iel).e(2).^2- ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(4)- ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
case {'132', 'xzy', 'XZY', 'ikj'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(4).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
angles(3,iel) = atan2(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
case {'212', 'yxy', 'YXY', 'jij'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2+ ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(3)- ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
case {'213', 'yxz', 'YXZ', 'jik'}
angles(1,iel) = atan2(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(4).*q(iel).e(2)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
case {'231', 'yzx', 'YZX', 'jki'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
case {'232', 'yzy', 'YZY', 'jkj'}
angles(1,iel) = atan2((q(iel).e(3).*q(iel).e(4)- ...
q(iel).e(2).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2+ ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
case {'312', 'zxy', 'ZXY', 'kij'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
case {'313', 'zxz', 'ZXZ', 'kik'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(4)- ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2- ...
q(iel).e(3).^2+q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
case {'321', 'zyx', 'ZYX', 'kji'}
angles(1,iel) = atan2(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
case {'323', 'zyz', 'ZYZ', 'kjk'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2- ...
q(iel).e(3).^2+q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(3).*q(iel).e(4)- ...
q(iel).e(2).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
otherwise
error( 'Invalid output Euler angle axes' );
end % switch axes
end % for iel
angles = chop( angles );
end % EulerAngles
function [omega, axis] = OmegaAxis( q, t, dim )
% function [omega, axis] = OmegaAxis( q, t, dim ) or
% [omega, axis] = q.OmegaAxis( t, dim )
% Estimate instantaneous angular velocities and rotation axes from a time
% series of quaternions. The angular velocity vector omegav is computed by:
% omegav(:,1) = vector( 2*log( q(1) * inverse(q(2)) )/(t(2) - t(1)) );
% omegav(:,i) = vector(...
% (log( q(i-1) * inverse(q(i)) ) + log( q(i) * inverse(q(i+1))) )/...
% (0.5*(t(i+1) - t(i-1))) );
% omegav(:,end) = vector( 2*log( q(end-1) * inverse(q(end)) )/...
% (t(end) - t(end-1)) );
% [axis, omega] = unitvector( omegav );
% Inputs:
% q array of normalized (rotation) quaternions
% t [OPT] array of monotonically increasing (or decreasing) times.
% if omitted or empty, unit time steps are assumed.
% t must either be a vector with the same length as dimension
% dim of q, or the same size as q.
% dim [OPT] dimension of q that is varying in time; if omitted or empty,
% the first non-singleton dimension is used.
% Outputs:
% omega array of instantaneous angular velocities, radians/(unit time)
% omega >= 0
% axis instantaneous 3D rotation axis unit vectors at each time
if isempty( q )
omega = [];
axis = [];
return;
end
if (nargin < 3) || isempty( dim )
if (nargin > 1) && ~isempty( t )
siq = size( q );
sit = size( t );
if isequal( siq, sit )
dim = find( siq > 1, 1 );
else
dim = find( siq == length( t ), 1 );
end
if isempty( dim )
error( 'size of t must agree with at least one dimension of q' );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
if isequal( siq, sit )
t = permute( t, perm );
end
end
else
[q, dim, perm] = finddim( q, -2 );
if dim == 0
omega = 0;
axis = unitvector( q.e(2:4), 1 );
return;
end
end
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
n = norm( q );
if ~all( abs( n(:) - 1 ) < eps(16) )
error( 'q must be normalized' );
end
siq = size( q );
if (nargin < 2) || isempty( t )
t = repmat( (0 : (siq(1)-1)).', [1 siq(2:end)] );
elseif length( t ) == siq(1)
t = repmat( t(:), [1 siq(2:end)] );
elseif ~isequal( siq, size( t ))
error( 'size of t must match size of q' );
end
dt = zeros( siq );
difft = diff( t, 1 );
dt(1,:) = difft(1,:);
dt(2:end-1,:) = 0.5 *( difft(1:end-1,:) + difft(2:end,:) );
dt(end,:) = difft(end,:);
dq = quaternion.zeros( siq );
q1iq2 = q(1:end-1,:) .* inverse( q(2:end,:) );
neg = real( q1iq2 ) < 0;
q1iq2(neg) = -q1iq2(neg); % keep real element >= 0
derivq = log( q1iq2 );
dq(1,:) = 2 .* derivq(1,:);
dq(2:end-1,:) = derivq(1:end-1,:) + derivq(2:end,:);
dq(end,:) = 2 .* derivq(end,:);
omegav = vector( dq ); % angular velocity vectors
[axis, omega] = unitvector( omegav, 1 );
omega = reshape( omega(1,:), siq )./ dt;
axis = -axis;
if dim > 1
axis = ipermute( axis, [1, 1+perm] );
omega = ipermute( omega, perm );
end
end % OmegaAxis
function PlotRotation( q, interval )
% function PlotRotation( q, interval ) or q.PlotRotation( interval )
% Inputs:
% q quaternion array
% interval pause between figure updates in seconds, default = 0.1
% Output:
% figure plotting the 3 Cartesian axes orientations for the series of
% quaternions in array q
if (nargin < 2) || isempty( interval )
interval = 0.1;
end
nel = numel( q );
or = zeros(1,3);
ax = eye(3);
alx = zeros( nel, 3, 3 );
figure;
for iel = 1 : nel
% plot3( [ or; ax(:,1).' ], [ or ; ax(:,2).' ], [ or; ax(:,3).' ], ':' );
plot3( [ or; ax(1,:) ], [ or ; ax(2,:) ], [ or; ax(3,:) ], ':' );
hold on
set( gca, 'Xlim', [-1 1], 'Ylim', [-1 1], 'Zlim', [-1 1] );
xlabel( 'x' );
ylabel( 'y' );
zlabel( 'z' );
grid on
nax = q(iel).RotationMatrix;
alx(iel,:,:) = nax;
% plot3( [ or; nax(:,1).' ], [ or ; nax(:,2).' ], [ or; nax(:,3).' ], '-', 'LineWidth', 2 );
plot3( [ or; nax(1,:) ], [ or ; nax(2,:) ], [ or; nax(3,:) ], '-', 'LineWidth', 2 );
% plot3( alx(1:iel,:,1), alx(1:iel,:,2), alx(1:iel,:,3), '*' );
plot3( squeeze(alx(1:iel,1,:)), squeeze(alx(1:iel,2,:)), squeeze(alx(1:iel,3,:)), '*' );
if interval
pause( interval );
end
hold off
end
end % PlotRotation
function [q1, w1, t1] = PropagateEulerEq( q0, w0, I, t, torque, varargin )
% function [q1, w1, t1] = PropagateEulerEq( q0, w0, I, t, torque, odeoptions )
% Inputs:
% q0 initial orientation quaternion (normalized, scalar)
% w0(3) initial body frame angular velocity vector
% I(3) principal body moments of inertia (if no torque, only
% ratios of elements of I are used)
% t(nt) initial and subsequent (or previous) times t = [t0,t1,...]
% (monotonic)
% @torque [OPTIONAL] function handle to calculate torque vector:
% tau(1:3) = torque( t, y ), where y = [q.e(1:4); w(1:3)]
% odeoptions [OPTIONAL] ode45 options
% Outputs:
% q1(1,nt) array of normalized quaternions at times t1
% w1(3,nt) array of body frame angular velocity vectors at times t1
% t1(1,nt) array of output times
% Calls:
% Derivative quaternion derivative method
% odeset matlab ode options setter
% ode45 matlab ode numerical differential equation integrator
% torque [OPTIONAL] user-supplied torque as function of time, orientation,
% and angular rates; default is no torque
% Author:
% Mark Tincknell, 20 December 2010
% modified 25 July 2012, enforce normalization of q0 and q1
options = odeset( varargin{:} );
q0 = q0.normalize;
y0 = [q0.e; w0(:)];
I0 = [ (I(2) - I(3)) / I(1);
(I(3) - I(1)) / I(2);
(I(1) - I(2)) / I(3) ];
[T, Y] = ode45( @Euler, t, y0, options );
function yd = Euler( ti, yi )
qi = quaternion( yi(1), yi(2), yi(3), yi(4) );
wi = yi(5:7);
qd = double( qi.Derivative( wi ));
wd = [ wi(2) * wi(3) * I0(1);
wi(3) * wi(1) * I0(2);
wi(1) * wi(2) * I0(3) ];
if exist( 'torque', 'var' ) && isa( torque, 'function_handle' )
tau = torque( ti, yi );
wd = tau(:) ./ I + wd;
end
yd = [ qd; wd ];
end
if numel(t) == 2
nT = 2;
T = [T(1); T(end)];
Y = [Y(1,:); Y(end,:)];
else
nT = length(T);
end
q1 = repmat( quaternion, [1 nT] );
w1 = zeros( [3 nT] );
t1 = T(:).';
for it = 1 : nT
q1(it) = quaternion( Y(it,1), Y(it,2), Y(it,3), Y(it,4) );
w1(:,it) = Y(it,5:7).';
end
q1 = q1.normalize;
neg = real( q1 ) < 0;
q1(neg) = -q1(neg); % keep real element >= 0
end % PropagateEulerEq
function vp = RotateVector( varargin )
% function vp = RotateVector( q, v, dim ) or
% vp = q.RotateVector( v, dim )
% 3x3 rotation matrices are created from q and matrix multiplication
% rotates v into vp. RotateVector is 7 times faster than RotateVectorQ.
% Inputs:
% q quaternion array
% v 3xN or Nx3 element Cartesian vectors
% dim [OPTIONAL] dimension of v with size 3 to rotate
% Output:
% vp 3xN or Nx3 element rotated vectors
if nargin < 2
error( 'RotateVector method requires 2 inputs: a vector and a quaternion' );
end
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
v = varargin{2};
else
v = varargin{1};
q = varargin{2};
end
if (nargin > 2) && ~isempty( varargin{3} )
dim = varargin{3};
if size( v, dim ) ~= 3
error( 'Dimension dim of vector v must be size 3' );
end
if dim > 1
ndm = ndims( v );
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
else
[v, dim, perm] = finddim( v, 3 );
if dim == 0
error( 'v must have a dimension of size 3' );
end
end
sip = size( v );
v = reshape( v, 3, [] );
nev = prod( sip )/ 3;
R = q.RotationMatrix;
siq = size( q );
neq = prod( siq );
if neq == nev
vp = zeros( sip );
for iel = 1 : neq
vp(:,iel) = R(:,:,iel) * v(:,iel);
end
if dim > 1
vp = ipermute( vp, perm );
end
elseif nev == 1
siz = [3 siq];
vp = zeros( siz );
for iel = 1 : neq
vp(:,iel) = R(:,:,iel) * v;
end
if siz(2) == 1
vp = squeeze( vp );
end
elseif neq == 1
vp = R * v;
vp = reshape( vp, sip );
if dim > 1
vp = ipermute( vp, perm );
end
else
error( 'q and v must have compatible dimensions' );
end
end % RotateVector
function vp = RotateVectorQ( varargin )
% function vp = RotateVectorQ( q, v, dim ) or
% vp = q.RotateVectorQ( v, dim )
% quaternions are created from v and quaternion multiplication rotates v
% into vp. RotateVector is 7 times faster than RotateVectorQ.
% Inputs:
% q quaternion array
% v 3xN or Nx3 element Cartesian vectors
% dim [OPTIONAL] dimension of v with size 3 to rotate
% Output:
% vp 3xN or Nx3 element rotated vectors
if nargin < 2
error( 'RotateVectorQ method requires 2 inputs: a vector and a quaternion' );
end
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
v = varargin{2};
else
v = varargin{1};
q = varargin{2};
end
siv = size( v );
if (nargin > 2) && ~isempty( varargin{3} )
dim = varargin{3};
if size( v, dim ) ~= 3
error( 'Dimension dim of vector v must be size 3' );
end
if dim > 1
ndm = ndims( v );
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
else
[v, dim, perm] = finddim( v, 3 );
if dim == 0
error( 'v must have a dimension of size 3' );
end
end
sip = size( v );
qv = quaternion( v(1,:), v(2,:), v(3,:) );
qv = reshape( qv, [1 sip(2:end)] );
if dim > 1
qv = ipermute( qv, perm );
end
q = q.normalize;
qp = q .* qv .* q.conj;
dp = qp.double;
nev = prod( siv )/ 3;
sqz = false;
if nev == 1
siz = [3 size(q)];
if siz(2) == 1
sqz = true;
end
else
siz = siv;
end
vp = reshape( dp(2:4,:), siz );
if sqz
vp = squeeze( vp );
end
end % RotateVectorQ
function R = RotationMatrix( q )
% function R = RotationMatrix( q ) or R = q.RotationMatrix
% Construct rotation (or direction cosine) matrices from quaternions
% Input:
% q quaternion array
% Output:
% R 3x3xN rotation (or direction cosine) matrices
siz = size( q );
R = zeros( [3 3 siz] );
nel = prod( siz );
q = normalize( q );
for iel = 1 : nel
e11 = q(iel).e(1)^2;
e12 = q(iel).e(1) * q(iel).e(2);
e13 = q(iel).e(1) * q(iel).e(3);
e14 = q(iel).e(1) * q(iel).e(4);
e22 = q(iel).e(2)^2;
e23 = q(iel).e(2) * q(iel).e(3);
e24 = q(iel).e(2) * q(iel).e(4);
e33 = q(iel).e(3)^2;
e34 = q(iel).e(3) * q(iel).e(4);
e44 = q(iel).e(4)^2;
R(:,:,iel) = ...
[ e11 + e22 - e33 - e44, 2*(e23 - e14), 2*(e24 + e13); ...
2*(e23 + e14), e11 - e22 + e33 - e44, 2*(e34 - e12); ...
2*(e24 - e13), 2*(e34 + e12), e11 - e22 - e33 + e44 ];
end
R = chop( R );
end % RotationMatrix
end % methods
% Static methods
methods(Static)
function q = angleaxis( angle, axis )
% function q = quaternion.angleaxis( angle, axis )
% Construct quaternions from rotation axes and rotation angles
% Inputs:
% angle array of rotation angles in radians
% axis 3xN or Nx3 array of axes (need not be unit vectors)
% Output:
% q quaternion array
sig = size( angle );
six = size( axis );
[axis, dim, perm] = finddim( axis, 3 );
if dim == 0
error( 'axis must have a dimension of size 3' );
end
neg = prod( sig );
nex = prod( six )/ 3;
if neg == 1
siz = six;
siz(dim)= 1;
nel = nex;
elseif nex == 1
siz = sig;
nel = neg;
elseif nex == neg
siz = sig;
nel = neg;
else
error( 'angle and axis must have compatible sizes' );
end
for iel = nel : -1 : 1
d(:,iel) = AngAxis2e( angle(min(iel,neg)), axis(:,min(iel,nex)) );
end
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = reshape( q, siz );
if neg == 1
q = ipermute( q, perm );
end
end % quaternion.angleaxis
function q = eulerangles( varargin )
% function q = quaternion.eulerangles( axes, angles ) OR
% function q = quaternion.eulerangles( axes, ang1, ang2, ang3 )
% Construct quaternions from triplets of axes and Euler angles
% Inputs:
% axes string array or cell string array
% '123' = 'xyz' = 'XYZ' = 'ijk', etc.
% angles 3xN or Nx3 array of angles in radians OR
% ang1, ang2, ang3 arrays of angles in radians
% Output:
% q quaternion array
ics = cellfun( @ischar, varargin );
if any( ics )
varargin{ics} = cellstr( varargin{ics} );
else
ics = cellfun( @iscellstr, varargin );
end
siv = cellfun( @size, varargin, 'UniformOutput', false );
axes = varargin{ics};
six = siv{ics};
nex = prod( six );
dim = 1;
if nargin == 2 % angles is 3xN or Nx3 array
angles = varargin{~ics};
sig = siv{~ics};
[angles, dim, perm] = finddim( angles, 3 );
if dim == 0
error( 'Must supply 3 Euler angles' );
end
sig(dim) = 1;
neg = prod( sig );
if nex == 1
siz = sig;
elseif neg == 1
siz = six;
elseif nex == neg
siz = sig;
end
nel = prod( siz );
for iel = nel : -1 : 1
q(iel) = EulerAng2q( axes{min(iel,nex)}, ...
angles(:,min(iel,neg)) );
end
elseif nargin == 4 % each of 3 angles is separate input argument
angles = varargin(~ics);
na = cellfun( 'prodofsize', angles );
[neg, jeg] = max( na );
if ~all( (na == 1) | (na == neg) )
error( 'All angles must be singletons or have the same number of elements' );
end
sig = size( angles{jeg} );
if nex == 1
siz = sig;
elseif neg == 1
siz = six;
elseif nex == neg
siz = sig;
end
nel = prod( siz );
for iel = nel : -1 : 1
q(iel) = EulerAng2q( axes{min(iel,nex)}, ...
[angles{1}(min(iel,na(1))), ...
angles{2}(min(iel,na(2))), ...
angles{3}(min(iel,na(3)))] );
end
else
error( 'Must supply either 2 or 4 input arguments' );
end % if nargin
q = reshape( q, siz );
if (dim > 1) && isequal( siz, sig )
q = ipermute( q, perm );
end
if ~ismatrix( q ) && (size( q, 1 ) == 1)
q = shiftdim( q, 1 );
end
end % quaternion.eulerangles
function q = eye( N )
% function q = eye( N )
if nargin < 1
N = 1;
end
if isempty(N) || (N <= 0)
q = quaternion.empty;
else
q = quaternion( eye(N), 0, 0, 0 );
end
end % quaternion.eye
function q = nan( varargin )
% function q = quaternion.nan( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( nan(siz), nan, nan, nan );
end
end % quaternion.nan
function q = NaN( varargin )
% function q = quaternion.NaN( siz )
q = quaternion.nan( varargin{:} );
end % quaternion.NaN
function q = ones( varargin )
% function q = quaternion.ones( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( ones(siz), 0, 0, 0 );
end
end % quaternion.ones
function q = rand( varargin )
% function q = quaternion.rand( siz )
% Input:
% siz size of output array q
% Output:
% q uniform random quaternions, NOT normalized to 1,
% 0 <= q.e(1) <= 1, -1 <= q.e(2:4) <= 1
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = quaternion.empty;
return;
end
d = [ rand( [1, siz] ); 2 * rand( [3, siz] ) - 1 ];
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = reshape( q, siz );
end % quaternion.rand
function q = randRot( varargin )
% function q = quaternion.randRot( siz )
% Random quaternions uniform in rotation space
% Input:
% siz size of output array q
% Output:
% q random quaternions, normalized to 1, 0 <= q.e(1) <= 1,
% uniform over the 3D surface of a 4 dimensional hypersphere
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = quaternion.empty;
return;
end
d = randn( [4, prod( siz )] );
n = sqrt( sum( d.^2, 1 ));
dn = bsxfun( @rdivide, d, n );
neg = dn(1,:) < 0;
dn(:,neg) = -dn(:,neg);
q = quaternion( dn(1,:), dn(2,:), dn(3,:), dn(4,:) );
q = reshape( q, siz );
end % quaternion.randRot
function q = rotateutov( u, v, dimu, dimv )
% function q = quaternion.rotateutov( u, v, dimu, dimv )
% Construct quaternions to rotate vectors u into directions of vectors v
% Inputs:
% u 3x1 or 3xN or 1x3 or Nx3 arrays of vectors
% v 3x1 or 3xN or 1x3 or Nx3 arrays of vectors
% dimu [OPTIONAL] dimension of u with size 3 to use
% dimv [OPTIONAL] dimension of v with size 3 to use
% Output:
% q quaternion array
if (nargin < 3) || isempty( dimu )
[u, dimu, permu] = finddim( u, 3 );
if dimu == 0
error( 'u must have a dimension of size 3' );
end
elseif dimu > 1
ndmu = ndims( u );
permu = [ dimu : ndmu, 1 : dimu-1 ];
u = permute( u, permu );
else
permu = 1 : ndims(u);
end
siu = size( u );
siu(1) = 1;
neu = prod( siu );
if (nargin < 4) || isempty( dimv )
[v, dimv, permv] = finddim( v, 3 );
if dimv == 0
error( 'v must have a dimension of size 3' );
end
elseif dimv > 1
ndmv = ndims( v );
permv = [ dimv : ndmv, 1 : dimv-1 ];
v = permute( v, permv );
else
permv = 1 : ndims(v);
end
siv = size( v );
siv(1) = 1;
nev = prod( siv );
if neu == nev
siz = siu;
nel = neu;
perm = permu;
dim = dimu;
elseif (neu > 1) && (nev == 1)
siz = siu;
nel = neu;
perm = permu;
dim = dimu;
elseif (neu == 1) && (nev > 1)
siz = siv;
nel = nev;
perm = permv;
dim = dimv;
else
error( 'Number of 3 element vectors in u and v must be 1 or equal' );
end
for iel = nel : -1 : 1
q(iel) = UV2q( u(:,min(iel,neu)), v(:,min(iel,nev)) );
end
if dim > 1
q = ipermute( reshape( q, siz ), perm );
end
end % quaternion.rotateutov
function q = rotationmatrix( R )
% function q = quaternion.rotationmatrix( R )
% Construct quaternions from rotation (or direction cosine) matrices
% Input:
% R 3x3xN rotation (or direction cosine) matrices
% Output:
% q quaternion array
siz = [size(R) 1 1];
if ~all( siz(1:2) == [3 3] ) || ...
(abs( det( R(:,:,1) ) - 1 ) > eps(16) )
error( 'Rotation matrices must be 3x3xN with det(R) == 1' );
end
nel = prod( siz(3:end) );
for iel = nel : -1 : 1
d(:,iel) = RotMat2e( chop( R(:,:,iel) ));
end
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = normalize( q );
q = reshape( q, siz(3:end) );
end % quaternion.rotationmatrix
function q = zeros( varargin )
% function q = quaternion.zeros( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( zeros(siz), 0, 0, 0 );
end
end % quaternion.zeros
end % methods(Static)
end % classdef quaternion
% Scalar rotation conversion functions
function eout = AngAxis2e( angle, axis )
% function eout = AngAxis2e( angle, axis )
% One Angle-Axis -> one quaternion
s = sin( 0.5 * angle );
v = axis(:);
vn = norm( v );
if vn == 0
if s == 0
c = 0;
else
c = 1;
end
u = zeros( 3, 1 );
else
c = cos( 0.5 * angle );
u = v(:) ./ vn;
end
eout = [ c; s * u ];
if (eout(1) < 0) && (mod( angle/(2*pi), 2 ) ~= 1)
eout = -eout; % rotationally equivalent quaternion with real element >= 0
end
end % AngAxis2e
function qout = EulerAng2q( axes, angles )
% function qout = EulerAng2q( axes, angles )
% One triplet Euler Angles -> one quaternion
na = length( axes );
axis = zeros( 3, na );
for i0 = 1 : na
switch axes(i0)
case {'1', 'i', 'x', 'X'}
axis(:,i0) = [ 1; 0; 0 ];
case {'2', 'j', 'y', 'Y'}
axis(:,i0) = [ 0; 1; 0 ];
case {'3', 'k', 'z', 'Z'}
axis(:,i0) = [ 0; 0; 1 ];
otherwise
error( 'Illegal axis designation' );
end
end
q0 = quaternion.angleaxis( angles(:).', axis );
qout = q0(1);
for i0 = 2 : numel(q0)
qout = product( q0(i0), qout );
end
if qout.e(1) < 0
qout = -qout; % rotationally equivalent quaternion with real element >= 0
end
end % EulerAng2q
function eout = RotMat2e( R )
% function eout = RotMat2e( R )
% One Rotation Matrix -> one quaternion
eout = zeros(4,1);
if ~all( all( R == 0 ))
eout(1) = 0.5 * sqrt( max( 0, R(1,1) + R(2,2) + R(3,3) + 1 ));
if eout(1) == 0
eout(2) = sqrt( max( 0, -0.5 *( R(2,2) + R(3,3) ))) * ...
sgn( -R(2,3) );
eout(3) = sqrt( max( 0, -0.5 *( R(1,1) + R(3,3) ))) * ...
sgn( -R(1,3) );
eout(4) = sqrt( max( 0, -0.5 *( R(1,1) + R(2,2) ))) * ...
sgn( -R(1,2) );
else
eout(2) = 0.25 *( R(3,2) - R(2,3) )/ eout(1);
eout(3) = 0.25 *( R(1,3) - R(3,1) )/ eout(1);
eout(4) = 0.25 *( R(2,1) - R(1,2) )/ eout(1);
end
end
end % RotMat2e
function qout = UV2q( u, v )
% function qout = UV2q( u, v )
% One pair vectors U, V -> one quaternion
w = cross( u, v ); % construct vector w perpendicular to u and v
magw = norm( w );
dotuv = dot( u, v );
if magw == 0
% Either norm(u) == 0 or norm(v) == 0 or dotuv/(norm(u)*norm(v)) == 1
if dotuv >= 0
qout = quaternion( 1, 0, 0, 0 );
return;
end
% dotuv/(norm(u)*norm(v)) == -1
% If v == [v(1); 0; 0], rotate by pi about the [0; 0; 1] axis
if (v(2) == 0) && (v(3) == 0)
qout = quaternion( 0, 0, 0, 1 );
return;
end
% Otherwise constuct "what" such that dot(v,what) == 0, and rotate about it
% by pi
what = [ 0; -v(3); v(2) ]./ sqrt( v(2)^2 + v(3)^2 );
costh = -1;
else
% Use w as rotation axis, angle between u and v as rotation angle
what = w(:) / magw;
costh = dotuv /( norm(u) * norm(v) );
end
c = sqrt( 0.5 *( 1 + costh )); % real element >= 0
s = sqrt( 0.5 *( 1 - costh ));
eout = [ c; s * what ];
qout = quaternion( eout(1), eout(2), eout(3), eout(4) );
end % UV2q
% Helper functions
function out = chop( in, tol )
% function out = chop( in, tol )
% Replace values that differ from an integer by <= tol by the integer
% Inputs:
% in input array
% tol tolerance, default = eps
% Output:
% out input array with integer replacements, if any
if (nargin < 2) || isempty( tol )
tol = eps;
end
out = in;
rin = round( in );
lx = abs( rin - in ) <= tol;
out(lx) = rin(lx);
end % chop
function [aout, dim, perm] = finddim( ain, len )
% function [aout, dim, perm] = finddim( ain, len )
% Find first dimension in ain of length len, permute ain to make it first
% Inputs:
% ain(s1,s2,...) data array, size = [s1, s2, ...]
% len length sought, e.g. s2 == len
% if len < 0, then find first dimension >= |len|
% Outputs:
% aout(s2,...,s1) data array, permuted so first dimension is length len
% dim dimension number of length len, 0 if ain has none
% perm permutation order (for permute and ipermute) of aout,
% e.g. [2, ..., 1]
% Notes: if no dimension has length len, aout = ain, dim = 0, perm = 1:ndm
% ain = ipermute( aout, perm )
siz = size( ain );
ndm = length( siz );
if len < 0
dim = find( siz >= -len, 1, 'first' );
else
dim = find( siz == len, 1, 'first' );
end
if isempty( dim )
dim = 0;
end
if dim < 2
aout = ain;
perm = 1 : ndm;
else
% Permute so that dim becomes the first dimension
perm = [ dim : ndm, 1 : dim-1 ];
aout = permute( ain, perm );
end
end % finddim
function s = sgn( x )
% function s = sgn( x ), if x >= 0, s = 1, else s = -1
s = ones( size( x ));
s(x < 0) = -1;
end % sgn
function [u, n] = unitvector( v, dim )
% function [u, n] = unitvector( v, dim )
% Inputs:
% v matrix of vectors
% dim [OPTIONAL] dimension to normalize, dim >= 1
% if no dim input, use first dimension of length >= 2
% Outputs:
% u matrix of unit vectors (except for vectors of norm 0)
% n matrix same size as v and u of norms
ndm = ndims( v );
if (nargin < 2) || isempty( dim )
[v, dim, perm] = finddim( v, -2 );
if dim == 0
n = sqrt( v.*conj(v) );
n0 = (n ~= 0) & (n ~= 1);
u = v;
u(n0) = v(n0) ./ n(n0);
return;
end
else
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
u = v;
sv = size( v );
n = repmat( sqrt( sum( v.*conj(v), 1 )), [sv(1) ones(1,ndm-1)] );
n0 = (n ~= 0) & (n ~= 1);
u(n0) = v(n0) ./ n(n0);
u = ipermute( u, perm );
if nargout > 1
n = ipermute( n, perm );
end
end % unitvector
|
github
|
jianxiongxiao/ProfXkit-master
|
rectify.m
|
.m
|
ProfXkit-master/rectifyroom/rectify.m
| 5,343 |
utf_8
|
58bf71d96dbaac2764184242fe621b7e
|
function [Rtilt,R] = rectify(XYZ)
%% XYZ is HxWx3 matrix
% X = XYZ(:,:,1);Y = XYZ(:,:,2);Z = XYZ(:,:,3);
% XYZnew = Rtilt*[X(:),Y(:),Z(:)]'
[Rtilt,R,world_center] = dominantAxes([eye(3) zeros(3,1)],XYZ);
function [Rtilt,R,world_center] = dominantAxes(cameraRt, pts)
XYZ = pts;
S = 1;
points = [reshape(XYZ(:,:,1),1,[]);reshape(XYZ(:,:,2),1,[]);reshape(XYZ(:,:,3),1,[])];
pointsOK = points(:,sum(isnan(points),1)==0);
pointsOK = pointsOK(:,1:S:end);
%tic;normals = points2normals_radius(pointsOK);toc;
normals = points2normals(pointsOK);
%{
figure,
s =1;
quiver3(pointsOK(1,1:S*s:end),pointsOK(2,1:S*s:end),pointsOK(3,1:S*s:end),normals(1,1:S*s:end),normals(2,1:S*s:end),normals(3,1:S*s:end));
quiver3(pointsOK(1,1:S*s:end),pointsOK(2,1:S*s:end),pointsOK(3,1:S*s:end),normals(1,1:s:end),normals(2,1:s:end),normals(3,1:s:end));
figure,
indxxx = B == b;
pointsOKxxx = pointsOK(:,1:S:end);
quiver3(pointsOKxxx(1,indxxx),pointsOKxxx(2,indxxx),pointsOKxxx(3,indxxx),normals(1,indxxx),normals(2,indxxx),normals(3,indxxx));
hold on
quiver3(pointsOK(1,1:S*s:end),pointsOK(2,1:S*s:end),pointsOK(3,1:S*s:end),nrm(1,1:s:end),nrm(2,1:s:end),nrm(3,1:s:end),'-.r');
figure,
plot3(sphere(1,:),sphere(2,:),sphere(3,:),'.')
%}
% approximately 1313 bins
sphere = icosahedron2sphere(12)';
bins = sphere(:, sphere(1, :) >= 0);
%NSAMPLE = 1e5;
%sampleind = randsample(1 : size(normals, 2), min(size(normals, 2), NSAMPLE));
%normals = normals(:,sampleind );
[D, B] = max(abs(bins' * normals), [], 1);
H = accumarray(cat(2, B', repmat(1, [length(B) 1])), repmat(1, [length(B) 1]));
A = eye(3);
[~, I] = sort(-H);
for j = 1 : 3
if ~isempty(I)
b = I(1);
% choose mean normal that falls into the biggest bin
in_bin = normals(:, B == b);
% flip mirrored normals
dots = sum(in_bin .* repmat(bins(:, b), [1 size(in_bin, 2)]), 1);
in_bin(:, (dots < 0)) = -in_bin(:, (dots < 0));
v = mean(in_bin, 2);
v = v / norm(v);
A(:, j) = v;
fprintf('Bin: %d, Normal: %f %f %f. Contains %d points. Mean vector: %f %f %f\n', b, bins(:, b), H(b), v);
% remove bins that are not ~90 degrees away
dots = sum(bins(:, I) .* repmat(v, [1 length(I)]), 1);
I = I((dots >= cos(deg2rad(110))) & (dots <= cos(deg2rad(70))));
end
end
axisI = A(:,1);
axisII = A(:,2);
axisII = axisII - (axisI'*axisII)*axisI;
axisII =axisII/norm(axisII);
axisIII = cross(axisI,axisII);
AA =[axisI,axisII,axisIII -1*[axisI,axisII,axisIII]];
[~, zi] = max(squeeze(cameraRt(1:3, 3, :))'*AA);
ZZ = AA(:, zi);
[~, xi] = max(squeeze(cameraRt(1:3, 1, :))'*AA);
XX = AA(:, xi);
[~, yi] = max(squeeze(cameraRt(1:3, 2, :))'*AA);
YY = AA(:, yi);
%{
for i =1:3,
hold on;
quiver3(1,1,1,AA(1,i),AA(2,i),AA(3,i));
quiver3(0,0,0,A(1,i),A(2,i),A(3,i));
pause;
end
axis tight;
%}
R = [XX YY ZZ]';
q = quaternion.rotateutov(ZZ, [0;0;1]);
Rtilt = RotationMatrix(q);
world_center = nanmean(reshape(pts,3,[]),2);
function rad = deg2rad(deg)
rad = deg*pi/180;
return;
function [coor,tri] = icosahedron2sphere(level)
% copyright by Jianxiong Xiao http://mit.edu/jxiao
% this function use a icosahedron to sample uniformly on a sphere
%{
Please cite this paper if you use this code in your publication:
J. Xiao, T. Fang, P. Zhao, M. Lhuillier, and L. Quan
Image-based Street-side City Modeling
ACM Transaction on Graphics (TOG), Volume 28, Number 5
Proceedings of ACM SIGGRAPH Asia 2009
%}
a= 2/(1+sqrt(5));
M=[
0 a -1 a 1 0 -a 1 0
0 a 1 -a 1 0 a 1 0
0 a 1 0 -a 1 -1 0 a
0 a 1 1 0 a 0 -a 1
0 a -1 0 -a -1 1 0 -a
0 a -1 -1 0 -a 0 -a -1
0 -a 1 a -1 0 -a -1 0
0 -a -1 -a -1 0 a -1 0
-a 1 0 -1 0 a -1 0 -a
-a -1 0 -1 0 -a -1 0 a
a 1 0 1 0 -a 1 0 a
a -1 0 1 0 a 1 0 -a
0 a 1 -1 0 a -a 1 0
0 a 1 a 1 0 1 0 a
0 a -1 -a 1 0 -1 0 -a
0 a -1 1 0 -a a 1 0
0 -a -1 -1 0 -a -a -1 0
0 -a -1 a -1 0 1 0 -a
0 -a 1 -a -1 0 -1 0 a
0 -a 1 1 0 a a -1 0
];
coor = reshape(M',3,60)';
%[M(:,[1 2 3]); M(:,[4 5 6]); M(:,[7 8 9])];
[coor, ~, idx] = unique(coor,'rows');
tri = reshape(idx,3,20)';
%{
for i=1:size(tri,1)
x(1)=coor(tri(i,1),1);
x(2)=coor(tri(i,2),1);
x(3)=coor(tri(i,3),1);
y(1)=coor(tri(i,1),2);
y(2)=coor(tri(i,2),2);
y(3)=coor(tri(i,3),2);
z(1)=coor(tri(i,1),3);
z(2)=coor(tri(i,2),3);
z(3)=coor(tri(i,3),3);
patch(x,y,z,'r');
end
axis equal
axis tight
%}
% extrude
coor = coor ./ repmat(sqrt(sum(coor .* coor,2)),1, 3);
for i=1:level
m = 0;
for t=1:size(tri,1)
n = size(coor,1);
coor(n+1,:) = ( coor(tri(t,1),:) + coor(tri(t,2),:) ) / 2;
coor(n+2,:) = ( coor(tri(t,2),:) + coor(tri(t,3),:) ) / 2;
coor(n+3,:) = ( coor(tri(t,3),:) + coor(tri(t,1),:) ) / 2;
triN(m+1,:) = [n+1 tri(t,1) n+3];
triN(m+2,:) = [n+1 tri(t,2) n+2];
triN(m+3,:) = [n+2 tri(t,3) n+3];
triN(m+4,:) = [n+1 n+2 n+3];
n = n+3;
m = m+4;
end
tri = triN;
% uniquefy
[coor, ~, idx] = unique(coor,'rows');
tri = idx(tri);
% extrude
coor = coor ./ repmat(sqrt(sum(coor .* coor,2)),1, 3);
end
% vertex number: 12 42 162 642
|
github
|
jianxiongxiao/ProfXkit-master
|
points2normals.m
|
.m
|
ProfXkit-master/rectifyroom/points2normals.m
| 2,551 |
utf_8
|
cffcb4a1ea7aa3af3e895f74f76491fa
|
function normals = points2normals(points)
% estimating a normal vector based on nearby 100 points
% points is 3 * n matrix for n points
if size(points,2)==3 && size(points,1)~=3
points = points';
end
normals = lsqnormest(points, 50);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% functions from http://www.mathworks.com/matlabcentral/fileexchange/27804-iterative-closest-point
% Least squares normal estimation from point clouds using PCA
%
% H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle.
% Surface reconstruction from unorganized points.
% In Proceedings of ACM Siggraph, pages 71:78, 1992.
%
% p should be a matrix containing the horizontally concatenated column
% vectors with points. k is a scalar indicating how many neighbors the
% normal estimation is based upon.
%
% Note that for large point sets, the function performs significantly
% faster if Statistics Toolbox >= v. 7.3 is installed.
%
% Jakob Wilm 2010
function n = lsqnormest(p, k)
m = size(p,2);
n = zeros(3,m);
v = ver('stats');
if str2double(v.Version) >= 7.5
neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1));
else
neighbors = k_nearest_neighbors(p, p, k+1);
end
for i = 1:m
x = p(:,neighbors(2:end, i));
p_bar = 1/k * sum(x,2);
P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P
%P = 2*cov(x);
[V,D] = eig(P);
[~, idx] = min(diag(D)); % choses the smallest eigenvalue
n(:,i) = V(:,idx); % returns the corresponding eigenvector
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Program to find the k - nearest neighbors (kNN) within a set of points.
% Distance metric used: Euclidean distance
%
% Note that this function makes repetitive use of min(), which seems to be
% more efficient than sort() for k < 30.
function [neighborIds,neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k)
numDataPoints = size(dataMatrix,2);
numQueryPoints = size(queryMatrix,2);
neighborIds = zeros(k,numQueryPoints);
neighborDistances = zeros(k,numQueryPoints);
D = size(dataMatrix, 1); %dimensionality of points
for i=1:numQueryPoints
d=zeros(1,numDataPoints);
for t=1:D % this is to avoid slow repmat()
d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2;
end
for j=1:k
[s,t] = min(d);
neighborIds(j,i)=t;
neighborDistances(j,i)=sqrt(s);
d(t) = NaN; % remove found number from d
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
quaternion.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/quaternion.m
| 85,196 |
utf_8
|
2aebad0378f433bf4d26b837b20047a3
|
classdef quaternion
% classdef quaternion, implements quaternion mathematics and 3D rotations
%
% Properties (SetAccess = protected):
% e(4,1) components, basis [1; i; j; k]: e(1) + i*e(2) + j*e(3) + k*e(4)
% i*j=k, j*i=-k, j*k=i, k*j=-i, k*i=j, i*k=-j, i*i = j*j = k*k = -1
%
% Constructors:
% q = quaternion scalar zero quaternion, q.e = [0;0;0;0]
% q = quaternion(x) x is a matrix size [4,s1,s2,...] or [s1,4,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% x(1:4,i1,i2,...) or x(i1,1:4,i2,...).'
% q = quaternion(v) v is a matrix size [3,s1,s2,...] or [s1,3,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% [0;v(1:3,i1,i2,...)] or [0;v(i1,1:3,i2,...).']
% q = quaternion(c) c is a complex matrix size [s1,s2,...],
% q is size [s1,s2,...], q(i1,i2,...).e = ...
% [real(c(i1,i2,...));imag(c(i1,i2,...));0;0]
% q = quaternion(x1,x2) x1,x2 are matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [x1(i1,i2,...);x2(i1,i2,...);0;0]
% q = quaternion(v1,v2,v3) v1,v2,v3 matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [0;v1(i1,i2,...);v2(i1,i2,...);...
% v3(i1,i2,...)]
% q = quaternion(x1,x2,x3,x4) x1,x2,x3,x4 matrices size [s1,s2,...] or scalars,
% q(i1,i2,...).e = [x1(i1,i2,...);x2(i1,i2,...);...
% x3(i1,i2,...);x4(i1,i2,...)]
%
% Quaternion array constructor methods:
% q = quaternion.eye(N) quaternion NxN identity matrix
% q = quaternion.nan(siz) q(:).e = [NaN;NaN;NaN;NaN]
% q = quaternion.ones(siz) q(:).e = [1;0;0;0]
% q = quaternion.rand(siz) uniform random quaternions, NOT normalized
% to 1, 0 <= q.e(1) <= 1, -1 <= q.e(2:4) <= 1
% q = quaternion.randRot(siz) random quaternions uniform in rotation space
% q = quaternion.zeros(siz) q(:).e = [0;0;0;0]
%
% Rotation constructor methods (all lower case):
% q = quaternion.angleaxis(angle,axis)
% angle is an array in radians, axis is an array
% of vectors size [3,s1,s2,...] or [s1,3,s2,...],
% q is size [s1,s2,...], quaternions normalized to 1
% equivalent to rotations about axis by angle
% q = quaternion.eulerangles(axes,angles) or
% q = quaternion.eulerangles(axes,ang1,ang2,ang3)
% axes is a string array or cell string array,
% '123' = 'xyz' = 'XYZ' = 'ijk', etc.,
% angles is an array of Euler angles in radians,
% size [3,s1,s2,...] or [s1,3,s2,...], or
% (ang1, ang2, ang3) are arrays or scalars of
% Euler angles in radians, q is size
% [s1,s2,...], quaternions normalized to 1
% equivalent to Euler Angle rotations
% q = quaternion.rotateutov(u,v,dimu,dimv)
% quaternions normalized to 1 that rotate 3
% element vectors u into the directions of 3
% element vectors v
% q = quaternion.rotationmatrix(R)
% R is an array of rotation or Direction Cosine
% Matrices size [3,3,s1,s2,...] with det(R) == 1,
% q(i1,i2,...) = quaternions normalized to 1,
% equivalent to R(1:3,1:3,i1,i2,...)
%
% Rotation methods (Mixed Case):
% [angle,axis] = AngleAxis(q) angles in radians, unit vector rotation axes
% equivalent to q
% qd = Derivative(q,w) quaternion derivatives, w are 3 component
% angular velocity vectors, qd = 0.5*q*quaternion(w)
% angles = EulerAngles(q,axes) angles are 3 Euler angles equivalent to q, axes
% are strings or cell strings, '123' = 'xyz', etc.
% [omega,axis] = OmegaAxis(q,t,dim)
% instantaneous angular velocities and rotation axes
% PlotRotation(q,interval) plot columns of rotation matrices of q,
% pause interval between figure updates in seconds
% [q1,w1,t1] = PropagateEulerEq(q0,w0,I,t,@torque,odeoptions)
% Euler equation numerical propagator, see
% help quaternion.PropagateEulerEq
% vp = RotateVector(q,v,dim) vp are 3 component vectors, rotations q acting
% on vectors v, uses rotation matrix multiplication
% vp = RotateVectorQ(q,v,dim) vp are 3 component vectors, rotations q acting
% on vectors v, uses quaternion multiplication,
% RotateVector is 7 times faster than RotateVectorQ
% R = RotationMatrix(q) 3x3 rotation matrices equivalent to q
%
% Note:
% In all rotation operations, the rotations operate from left to right on
% 3x1 column vectors and create rotated vectors, not representations of
% those vectors in rotated coordinate systems.
% For Euler angles, '123' means rotate the vector about x first, about y
% second, about z third, i.e.:
% vp = rotate(z,angle(3)) * rotate(y,angle(2)) * rotate(x,angle(1)) * v
%
% Ordinary methods:
% n = abs(q) quaternion norm, n = sqrt( sum( q.e.^2 ))
% q3 = bsxfun(func,q1,q2) binary singleton expansion of operation func
% c = complex(q) complex( real(q), imag(q) )
% qc = conj(q) quaternion conjugate, qc.e =
% [q.e(1);-q.e(2);-q.e(3);-q.e(4)]
% qt = ctranspose(q) qt = q'; quaternion conjugate transpose,
% 2-D (or scalar) q only
% qp = cumprod(q,dim) cumulative quaternion array product over
% dimension dim
% qs = cumsum(q,dim) cumulative quaternion array sum over dimension dim
% qd = diff(q,ord,dim) quaternion array difference, order ord, over
% dimension dim
% ans = display(q) 'q = ( e(1) ) + i( e(2) ) + j( e(3) ) + k( e(4) )'
% d = dot(q1,q2) quaternion element dot product, d = dot(q1.e,q2.e)
% d = double(q) d = q.e; if size(q) == [s1,s2,...], size(d) ==
% [4,s1,s2,...]
% l = eq(q1,q2) quaternion equality, l = all( q1.e == q2.e )
% l = equiv(q1,q2,tol) quaternion rotational equivalence, within
% tolerance tol, l = (q1 == q2) | (q1 == -q2)
% qe = exp(q) quaternion exponential, v = q.e(2:4), qe.e =
% exp(q.e(1))*[cos(|v|);v.*sin(|v|)./|v|]
% ei = imag(q) imaginary e(2) components
% qi = interp1(t,q,ti,method) interpolate quaternion array
% qi = inverse(q) quaternion inverse, qi = conj(q)./norm(q).^2,
% q .* qi = qi .*.q = 1 for q ~= 0
% l = isequal(q1,q2,...) true if equal sizes and values
% l = isequaln(q1,q2,...) true if equal including NaNs
% l = isequalwithequalnans(q1,q2,...) true if equal including NaNs
% l = isfinite(q) true if all( isfinite( q.e ))
% l = isinf(q) true if any( isinf( q.e ))
% l = isnan(q) true if any( isnan( q.e ))
% ej = jmag(q) e(3) components
% ek = kmag(q) e(4) components
% q3 = ldivide(q1,q2) quaternion left division, q3 = q1 \. q2 =
% inverse(q1) *. q2
% ql = log(q) quaternion logarithm, v = q.e(2:4), ql.e =
% [log(|q|);v.*acos(q.e(1)./|q|)./|v|]
% q3 = minus(q1,q2) quaternion subtraction, q3 = q1 - q2
% q3 = mldivide(q1,q2) left division only defined for scalar q1
% qp = mpower(q,p) quaternion matrix power, qp = q^p, p scalar
% integer >= 0, q square quaternion matrix
% q3 = mrdivide(q1,q2) right division only defined for scalar q2
% q3 = mtimes(q1,q2) 2-D matrix quaternion multiplication, q3 = q1 * q2
% l = ne(q1,q2) quaternion inequality, l = ~all( q1.e == q2.e )
% n = norm(q) quaternion norm, n = sqrt( sum( q.e.^2 ))
% [q,n] = normalize(q) make quaternion norm == 1, unless q == 0,
% n = matrix of previous norms
% q3 = plus(q1,q2) quaternion addition, q3 = q1 + q2
% qp = power(q,p) quaternion power, qp = q.^p
% qp = prod(q,dim) quaternion array product over dimension dim
% qp = product(q1,q2) quaternion product of scalar quaternions,
% qp = q1 .* q2, noncommutative
% q3 = rdivide(q1,q2) quaternion right division, q3 = q1 ./ q2 =
% q1 .* inverse(q2)
% er = real(q) real e(1) components
% qs = slerp(q0,q1,t) quaternion spherical linear interpolation
% qr = sqrt(q) qr = q.^0.5, square root
% qs = sum(q,dim) quaternion array sum over dimension dim
% q3 = times(q1,q2) matrix component quaternion multiplication,
% q3 = q1 .* q2, noncommutative
% qm = uminus(q) quaternion negation, qm = -q
% qp = uplus(q) quaternion unitary plus, qp = +q
% ev = vector(q) vector e(2:4) components
%
% Author:
% Mark Tincknell, MIT LL, 29 July 2011, revised 22 November 2013
properties (SetAccess = protected)
e = zeros(4,1);
end % properties
% Array constructors
methods
function q = quaternion( varargin ) % (constructor)
perm = [];
sqz = false;
switch nargin
case 0 % nargin == 0
q.e = zeros(4,1);
return;
case 1 % nargin == 1
siz = size( varargin{1} );
nel = prod( siz );
if nel == 0
q = quaternion.empty;
return;
elseif isa( varargin{1}, 'quaternion' )
q = varargin{1};
return;
elseif (nel == 1) || ~isreal( varargin{1}(:) )
for iel = nel : -1 : 1
q(iel).e = chop( [real(varargin{1}(iel)); ...
imag(varargin{1}(iel)); ...
0; ...
0] );
end
q = reshape( q, siz );
return;
end
[arg4, dim4, perm4] = finddim( varargin{1}, 4 );
if dim4 > 0
siz(dim4) = 1;
nel = prod( siz );
if dim4 > 1
perm = perm4;
else
sqz = true;
end
for iel = nel : -1 : 1
q(iel).e = chop( arg4(:,iel) );
end
else
[arg3, dim3, perm3] = finddim( varargin{1}, 3 );
if dim3 > 0
siz(dim3) = 1;
nel = prod( siz );
if dim3 > 1
perm = perm3;
else
sqz = true;
end
for iel = nel : -1 : 1
q(iel).e = chop( [0; arg3(:,iel)] );
end
else
error( 'Invalid input' );
end
end
case 2 % nargin == 2
% real-imaginary only (no j or k) inputs
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
0;
0] );
end
case 3 % nargin == 3
% vector inputs (no real, only i, j, k)
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [0; ...
varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
varargin{3}(min(iel,na(3)))] );
end
otherwise % nargin >= 4
na = cellfun( 'prodofsize', varargin );
[nel, jel] = max( na );
if ~all( (na == 1) | (na == nel) )
error( 'All inputs must be singletons or have the same number of elements' );
end
siz = size( varargin{jel} );
for iel = nel : -1 : 1
q(iel).e = chop( [varargin{1}(min(iel,na(1))); ...
varargin{2}(min(iel,na(2))); ...
varargin{3}(min(iel,na(3))); ...
varargin{4}(min(iel,na(4)))] );
end
end % switch nargin
if nel == 0
q = quaternion.empty;
end
q = reshape( q, siz );
if ~isempty( perm )
q = ipermute( q, perm );
end
if sqz
q = squeeze( q );
end
end % quaternion (constructor)
% Ordinary methods
function n = abs( q )
n = q.norm;
end % abs
function q3 = bsxfun( func, q1, q2 )
% function q3 = bsxfun( func, q1, q2 )
% Binary Singleton Expansion for quaternion arrays. Apply the element by
% element binary operation specified by the function handle func to arrays
% q1 and q2. All dimensions of q1 and q2 must either agree or be length 1.
% Inputs:
% func function handle (e.g. @plus) of quaternion function or operator
% q1(n1) quaternion array
% q2(n2) quaternion array
% Output:
% q3(n3) quaternion array of function or operator outputs
% size(q3) = max( size(q1), size(q2) )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
s1 = size( q1 );
s2 = size( q2 );
nd1 = length( s1 );
nd2 = length( s2 );
s1 = [s1, ones(1,nd2-nd1)];
s2 = [s2, ones(1,nd1-nd2)];
if ~all( (s1 == s2) | (s1 == 1) | (s2 == 1) )
error( 'Non-singleton dimensions of q1 and q2 must match each other' );
end
c1 = num2cell( s1 );
c2 = num2cell( s2 );
s3 = max( s1, s2 );
nd3 = length( s3 );
n3 = prod( s3 );
q3 = quaternion.nan( s3 );
for i3 = 1 : n3
[ix3{1:nd3}] = ind2sub( s3, i3 );
ix1 = cellfun( @min, ix3, c1, 'UniformOutput', false );
ix2 = cellfun( @min, ix3, c2, 'UniformOutput', false );
q3(i3) = func( q1(ix1{:}), q2(ix2{:}) );
end
end % bsxfun
function c = complex( q )
c = complex( real( q ), imag( q ));
end % complex
function qc = conj( q )
d = double( q );
qc = reshape( quaternion( d(1,:), -d(2,:), -d(3,:), -d(4,:) ), ...
size( q ));
end % conj
function qt = ctranspose( q )
qt = transpose( q.conj );
end % ctranspose
function qp = cumprod( q, dim )
% function qp = cumprod( q, dim )
% cumulative quaternion array product, dim defaults to first dimension of
% length > 1
if isempty( q )
qp = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
qp = q;
for is = 2 : size(q,1)
qp(is,:) = qp(is-1,:) .* q(is,:);
end
if dim > 1
qp = ipermute( qp, perm );
end
end % cumprod
function qs = cumsum( q, dim )
% function qs = cumsum( q, dim )
% cumulative quaternion array sum, dim defaults to first dimension of
% length > 1
if isempty( q )
qs = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
qs = q;
for is = 2 : size(q,1)
qs(is,:) = qs(is-1,:) + q(is,:);
end
if dim > 1
qs = ipermute( qs, perm );
end
end % cumsum
function qd = diff( q, ord, dim )
% function qd = diff( q, ord, dim )
% quaternion array difference, ord is the order of difference (default = 1)
% dim defaults to first dimension of length > 1
if isempty( q )
qd = q;
return;
end
if (nargin < 2) || isempty( ord )
ord = 1;
end
if ord <= 0
qd = q;
return;
end
if (nargin < 3) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
if siz(1) <= 1
qd = quaternion.empty;
return;
end
qd = quaternion.zeros( [(siz(1)-1), siz(2:end)] );
for is = 1 : siz(1)-1
qd(is,:) = q(is+1,:) - q(is,:);
end
ord = ord - 1;
if ord > 0
qd = diff( qd, ord, 1 );
end
if dim > 1
qd = ipermute( qd, perm );
end
end % diff
function display( q )
if ~isequal( get(0,'FormatSpacing'), 'compact' )
disp(' ');
end
if isempty( q )
fprintf( '%s \t= ([]) + i([]) + j([]) + k([])\n', inputname(1) )
return;
end
siz = size( q );
nel = [1 cumprod( siz )];
ndm = length( siz );
for iel = 1 : nel(end)
if nel(end) == 1
sub = '';
else
sub = ')';
jel = iel - 1;
for idm = ndm : -1 : 1
idx = floor( jel / nel(idm) ) + 1;
sub = [',' int2str(idx) sub]; %#ok<AGROW>
jel = rem( jel, nel(idm) );
end
sub(1) = '(';
end
fprintf( '%s%s \t= (%-12.5g) + i(%-12.5g) + j(%-12.5g) + k(%-12.5g)\n', ...
inputname(1), sub, q(iel).e )
end
end % display
function d = dot( q1, q2 )
% function d = dot( q1, q2 )
% quaternion element dot product: d = dot( q1.e, q2.e ), using binary
% singleton expansion of quaternion arrays
% dn = dot( q1, q2 )/( norm(q1) * norm(q2) ) is the cosine of the angle in
% 4D space between 4D vectors q1.e and q2.e
d = squeeze( sum( bsxfun( @times, double( q1 ), double( q2 )), 1 ));
end % dot
function d = double( q )
siz = size( q );
d = reshape( [q.e], [4 siz] );
d = chop( d );
end % double
function l = eq( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
l = logical([]);
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
l = bsxfun( @eq, [q1.e], [q2.e] );
l = reshape( all( l, 1 ), siz );
end % eq
function l = equiv( q1, q2, tol )
% function l = equiv( q1, q2, tol )
% quaternion rotational equivalence, within tolerance tol,
% l = (q1 == q2) | (q1 == -q2)
% optional argument tol (default = eps) sets tolerance for difference
% from exact equality
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
if (nargin < 3) || isempty( tol )
tol = eps;
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
l = logical([]);
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
dm = chop( bsxfun( @minus, [q1.e], [q2.e] ), tol );
dp = chop( bsxfun( @plus, [q1.e], [q2.e] ), tol );
l = all( (dm == 0) | (dp == 0), 1 );
l = reshape( l, siz );
end % equiv
function qe = exp( q )
% function qe = exp( q )
% quaternion exponential, v = q.e(2:4),
% qe.e = exp(q.e(1))*[cos(|v|);v.*sin(|v|)./|v|]
d = double( q );
siz = size( d );
od = ones( 1, ndims( q ));
vn = reshape( sqrt( sum( d(2:4,:).^2, 1 )), [1 siz(2:end)] );
cv = cos( vn );
sv = sin( vn );
n0 = vn ~= 0;
sv(n0) = sv(n0) ./ vn(n0);
sv = repmat( sv, [3, od] );
ex = repmat( reshape( exp( d(1,:) ), [1 siz(2:end)] ), [4, od] );
de = ex .* [ cv; sv .* reshape( d(2:4,:), [3 siz(2:end)] )];
qe = reshape( quaternion( de(1,:), de(2,:), de(3,:), de(4,:) ), ...
size( q ));
end % exp
function ei = imag( q )
siz = size( q );
d = double( q );
ei = reshape( d(2,:), siz );
end % imag
function qi = interp1( varargin )
% function qi = interp1( t, q, ti, method ) or
% qi = q.interp1( t, ti, method ) or
% qi = interp1( q, ti, method )
% Interpolate quaternion array. If q are rotation quaternions (i.e.
% normalized to 1), then -q is equivalent to q, and the sign of q to use as
% the second knot of the interpolation is chosen by which ever is closer to
% the first knot. Extrapolation (i.e. ti < min(t) or ti > max(t)) gives
% qi = quaternion.nan.
% Inputs:
% t(nt) array of ordinates (e.g. times); if t is not provided t=1:nt
% q(nt,nq) quaternion array
% ti(ni) array of query (interpolation) points, t(1) <= ti <= t(end)
% method [OPTIONAL] 'slerp' or 'linear'; default = 'slerp'
% Output:
% qi(ni,nq) interpolated quaternion array
nna = nnz( ~cellfun( @ischar, varargin ));
im = 4;
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
siq = size( q );
if nna == 2
if isrow( q )
t = (1 : siq(2)).';
else
t = (1 : siq(1)).';
end
ti = varargin{2}(:);
im = 3;
elseif isempty( varargin{2} )
if isrow( q )
t = (1 : siq(2)).';
else
t = (1 : siq(1)).';
end
ti = varargin{3}(:);
else
t = varargin{2}(:);
ti = varargin{3}(:);
end
elseif isa( varargin{2}, 'quaternion' )
t = varargin{1}(:);
q = varargin{2};
ti = varargin{3}(:);
siq = size( q );
else
error( 'Input q must be a quaterion' );
end
neq = prod( siq );
if neq == 0
qi = quaternion.empty;
return;
end
nt = numel( t );
if siq(1) == nt
dim = 1;
else
[q, dim, perm] = finddim( q, nt );
if dim == 0
error( 'q must have a dimension the same size as t' );
end
end
iNf = interp1( t, (1:nt).', ti );
iN = max( 1, min( nt-1, floor( iNf )));
jN = max( 2, min( nt, ceil( iNf )));
iNm = repmat( iNf - iN, [1, neq / nt] );
% If q are rotation quaternions (i.e. all normalized to 1), then -q
% represents the same rotation. Pick the sign of +/-q that has the closest
% dot product to use as the second knot of the interpolation.
qj = q(jN,:);
if all( abs( norm( q(:) ) - 1 ) <= eps(16) )
qd = dot( q(iN,:), qj );
lq = qd < -qd;
qj(lq) = -qj(lq);
end
if (length( varargin ) >= im) && ...
(strncmpi( 'linear', varargin{im}, length( varargin{im} )))
qi = (1 - iNm) .* q(iN,:) + iNm .* qj;
else
qi = slerp( q(iN,:), qj, iNm );
end
if length( siq ) > 2
sin = siq;
sin(dim) = numel( ti );
sin = circshift( sin, [0, 1-dim] );
qi = reshape( qi, sin );
end
if dim > 1
qi = ipermute( qi, perm );
end
end % interp1
function qi = inverse( q )
% function qi = inverse( q )
% quaternion inverse, qi = conj(q)/norm(q)^2, q*qi = qi*q = 1 for q ~= 0
if isempty( q )
qi = q;
return;
end
d = double( q );
d(2:4,:) = -d(2:4,:);
n2 = repmat( sum( d.^2, 1 ), 4, ones( 1, ndims( d ) - 1 ));
ne0 = n2 ~= 0;
di = Inf( size( d ));
di(ne0) = d(ne0) ./ n2(ne0);
qi = reshape( quaternion( di(1,:), di(2,:), di(3,:), di(4,:) ), ...
size( q ));
end % inverse
function l = isequal( q1, varargin )
% function l = isequal( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequal( [q1.e], [q2.e] )
return;
end
end
end
l = true;
end % isequal
function l = isequaln( q1, varargin )
% function l = isequaln( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequaln( [q1.e], [q2.e] )
return;
end
end
end
l = true;
end % isequaln
function l = isequalwithequalnans( q1, varargin )
% function l = isequalwithequalnans( q1, q2, ... )
nar = numel( varargin );
if nar == 0
error( 'Not enough input arguments' );
end
l = false;
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
si1 = size( q1 );
for iar = 1 : nar
si2 = size( varargin{iar} );
if (length( si1 ) ~= length( si2 )) || ...
~all( si1 == si2 )
return;
else
if ~isa( varargin{iar}, 'quaternion' )
q2 = quaternion( ...
real(varargin{iar}), imag(varargin{iar}), 0, 0 );
else
q2 = varargin{iar};
end
if ~isequalwithequalnans( [q1.e], [q2.e] ) %#ok<FPARK>
return;
end
end
end
l = true;
end % isequalwithequalnans
function l = isfinite( q )
% function l = isfinite( q ), l = all( isfinite( q.e ))
d = [q.e];
l = reshape( all( isfinite( d ), 1 ), size( q ));
end % isfinite
function l = isinf( q )
% function l = isinf( q ), l = any( isinf( q.e ))
d = [q.e];
l = reshape( any( isinf( d ), 1 ), size( q ));
end % isinf
function l = isnan( q )
% function l = isnan( q ), l = any( isnan( q.e ))
d = [q.e];
l = reshape( any( isnan( d ), 1 ), size( q ));
end % isnan
function ej = jmag( q )
siz = size( q );
d = double( q );
ej = reshape( d(3,:), siz );
end % jmag
function ek = kmag( q )
siz = size( q );
d = double( q );
ek = reshape( d(4,:), siz );
end % kmag
function q3 = ldivide( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)).inverse, ...
q2(min(iel,ne2)) );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % ldivide
function ql = log( q )
% function ql = log( q )
% quaternion logarithm, v = q.e(2:4), ql.e = [log(|q|);v.*acos(q.e(1)./|q|)./|v|]
% logarithm of negative real quaternions is ql.e = [log(|q|);pi;0;0]
d = double( q );
d2 = d.^2;
siz = size( d );
od = ones( 1, ndims( q ));
[vn,qn] = deal( zeros( [1 siz(2:end)] ));
vn(:) = sqrt( sum( d2(2:4,:), 1 ));
qn(:) = sqrt( sum( d2(1:4,:), 1 ));
lq = log( qn );
d1 = reshape( d(1,:), [1 siz(2:end)] );
nq = qn ~= 0;
d1(nq) = d1(nq) ./ qn(nq);
ac = acos( d1 );
nv = vn ~= 0;
ac(nv) = ac(nv) ./ vn(nv);
ac = reshape( repmat( ac, [3, od] ), 3, [] );
va = reshape( d(2:4,:) .* ac, [3 siz(2:end)] );
nn = (d1 < 0) & (vn == 0);
va(1,nn)= pi;
dl = [ lq; va ];
ql = reshape( quaternion( dl(1,:), dl(2,:), dl(3,:), dl(4,:) ), ...
size( q ));
end % log
function q3 = minus( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
d3 = bsxfun( @minus, [q1.e], [q2.e] );
q3 = quaternion( d3(1,:), d3(2,:), d3(3,:), d3(4,:) );
q3 = reshape( q3, siz );
end % minus
function q3 = mldivide( q1, q2 )
% function q3 = mldivide( q1, q2 ), left division only defined for scalar q1
if numel( q1 ) > 1
error( 'Left matix division undefined for quaternion arrays' );
end
q3 = ldivide( q1, q2 );
end % mldivide
function qp = mpower( q, p )
% function qp = mpower( q, p ), quaternion matrix power
siq = size( q );
neq = prod( siq );
nep = numel( p );
if neq == 1
qp = power( q, p );
return;
elseif isa( p, 'quaternion' )
error( 'Quaternion as matrix exponent is not defined' );
end
if (neq == 0) || (nep == 0)
qp = quaternion.empty;
return;
elseif (nep > 1) || (mod( p, 1 ) ~= 0) || (p < 0) || ...
(numel( siq ) > 2) || (siq(1) ~= siq(2))
error( 'Inputs must be a scalar non-negative integer power and a square quaternion matrix' );
elseif p == 0
qp = quaternion.eye( siq(1) );
return;
end
qp = q;
for ip = 2 : p
qp = qp * q;
end
end % mpower
function q3 = mrdivide( q1, q2 )
% function q3 = mrdivide( q1, q2 ), right division only defined for scalar q2
if numel( q2 ) > 1
error( 'Right matix division undefined for quaternion arrays' );
end
q3 = rdivide( q1, q2 );
end % mrdivide
function q3 = mtimes( q1, q2 )
% function q3 = mtimes( q1, q2 )
% q3 = matrix quaternion product of 2-D conformable quaternion matrices q1
% and q2
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 1) || (ne2 == 1)
q3 = times( q1, q2 );
return;
end
if (length( si1 ) ~= 2) || (length( si2 ) ~= 2)
error( 'Input arguments must be 2-D' );
end
if si1(2) ~= si2(1)
error( 'Inner matrix dimensions must agree' );
end
q3 = repmat( quaternion, [si1(1) si2(2)] );
for i1 = 1 : si1(1)
for i2 = 1 : si2(2)
for i3 = 1 : si1(2)
q3(i1,i2) = q3(i1,i2) + product( q1(i1,i3), q2(i3,i2) );
end
end
end
end % mtimes
function l = ne( q1, q2 )
l = ~eq( q1, q2 );
end % ne
function n = norm( q )
n = shiftdim( sqrt( sum( double( q ).^2, 1 )), 1 );
end % norm
function [q, n] = normalize( q )
% function [q, n] = normalize( q )
% q = quaternions with norm == 1 (unless q == 0), n = former norms
siz = size( q );
nel = prod( siz );
if nel == 0
if nargout > 1
n = zeros( siz );
end
return;
elseif nel > 1
nel = [];
end
d = double( q );
n = sqrt( sum( d.^2, 1 ));
if all( n(:) == 1 )
if nargout > 1
n = shiftdim( n, 1 );
end
return;
end
n4 = repmat( n, 4, nel );
ne0 = (n4 ~= 0) & (n4 ~= 1);
d(ne0) = d(ne0) ./ n4(ne0);
q = reshape( quaternion( d(1,:), d(2,:), d(3,:), d(4,:) ), siz );
if nargout > 1
n = shiftdim( n, 1 );
end
end % normalize
function q3 = plus( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ne1 == 1
siz = si2;
elseif ne2 == 1
siz = si1;
elseif isequal( si1, si2 )
siz = si1;
else
error( 'Matrix dimensions must agree' );
end
d3 = bsxfun( @plus, [q1.e], [q2.e] );
q3 = quaternion( d3(1,:), d3(2,:), d3(3,:), d3(4,:) );
q3 = reshape( q3, siz );
end % plus
function qp = power( q, p )
% function qp = power( q, p ), quaternion power
siq = size( q );
sip = size( p );
neq = prod( siq );
nep = prod( sip );
if (neq == 0) || (nep == 0)
qp = quaternion.empty;
return;
elseif ~isequal( siq, sip ) && (neq ~= 1) && (nep ~= 1)
error( 'Matrix dimensions must agree' );
end
qp = exp( p .* log( q ));
end % power
function qp = prod( q, dim )
% function qp = prod( q, dim )
% quaternion array product over dimension dim
% dim defaults to first dimension of length > 1
if isempty( q )
qp = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
qp = reshape( q(1,:), [1 siz(2:end)] );
for is = 2 : siz(1)
qp(1,:) = qp(1,:) .* q(is,:);
end
if dim > 1
qp = ipermute( qp, perm );
end
end % prod
function q3 = product( q1, q2 )
% function q3 = product( q1, q2 )
% q3 = quaternion product of scalar quaternions q1 and q2
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
if (numel( q1 ) ~= 1) || (numel( q2 ) ~= 1)
error( 'product not defined for arrays, use mtimes or times' );
end
ee = q1.e * q2.e.';
eo = [ee(1,1) - ee(2,2) - ee(3,3) - ee(4,4); ...
ee(1,2) + ee(2,1) + ee(3,4) - ee(4,3); ...
ee(1,3) - ee(2,4) + ee(3,1) + ee(4,2); ...
ee(1,4) + ee(2,3) - ee(3,2) + ee(4,1)];
eo = chop( eo );
q3 = quaternion( eo(1), eo(2), eo(3), eo(4) );
end % product
function q3 = rdivide( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)), ...
q2(min(iel,ne2)).inverse );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % rdivide
function er = real( q )
siz = size( q );
d = double( q );
er = reshape( d(1,:), siz );
end % real
function qs = slerp( q0, q1, t )
% function qs = slerp( q0, q1, t )
% quaternion spherical linear interpolation, qs = q0.*(q0.inverse.*q1).^t,
% default t = 0.5; see http://en.wikipedia.org/wiki/Slerp
if (nargin < 3) || isempty( t )
t = 0.5;
end
qs = q0 .* (q0.inverse .* q1).^t;
end % slerp
function qr = sqrt( q )
qr = q.^0.5;
end % sqrt
function qs = sum( q, dim )
% function qs = sum( q, dim )
% quaternion array sum over dimension dim
% dim defaults to first dimension of length > 1
if isempty( q )
qs = q;
return;
end
if (nargin < 2) || isempty( dim )
[q, dim, perm] = finddim( q, -2 );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
siz = size( q );
qs = reshape( q(1,:), [1 siz(2:end)] );
for is = 2 : siz(1)
qs(1,:) = qs(1,:) + q(is,:);
end
if dim > 1
qs = ipermute( qs, perm );
end
end % sum
function q3 = times( q1, q2 )
if ~isa( q1, 'quaternion' )
q1 = quaternion( real(q1), imag(q1), 0, 0 );
end
if ~isa( q2, 'quaternion' )
q2 = quaternion( real(q2), imag(q2), 0, 0 );
end
si1 = size( q1 );
si2 = size( q2 );
ne1 = prod( si1 );
ne2 = prod( si2 );
if (ne1 == 0) || (ne2 == 0)
q3 = quaternion.empty;
return;
elseif ~isequal( si1, si2 ) && (ne1 ~= 1) && (ne2 ~= 1)
error( 'Matrix dimensions must agree' );
end
for iel = max( ne1, ne2 ) : -1 : 1
q3(iel) = product( q1(min(iel,ne1)), q2(min(iel,ne2)) );
end
if ne2 > ne1
q3 = reshape( q3, si2 );
else
q3 = reshape( q3, si1 );
end
end % times
function qm = uminus( q )
d = -double( q );
qm = reshape( quaternion( d(1,:), d(2,:), d(3,:), d(4,:) ), ...
size( q ));
end % uminus
function qp = uplus( q )
qp = q;
end % uplus
function ev = vector( q )
siz = size( q );
d = double( q );
ev = reshape( d(2:4,:), [3 siz] );
end % vector
function [angle, axis] = AngleAxis( q )
% function [angle, axis] = AngleAxis( q ) or [angle, axis] = q.AngleAxis
% Construct angle-axis pairs equivalent to quaternion rotations
% Input:
% q quaternion array
% Outputs:
% angle rotation angles in radians, 0 <= angle <= 2*pi
% axis 3xN or Nx3 rotation axis unit vectors
% Note: angle and axis are constructed so at least 2 out of 3 elements of
% axis are >= 0.
siz = size( q );
ndm = length( siz );
[angle, s] = deal( zeros( siz ));
axis = zeros( [3 siz] );
nel = prod( siz );
if nel == 0
return;
end
[q, n] = normalize( q );
d = double( q );
neg = repmat( reshape( d(1,:) < 0, [1 siz] ), ...
[4, ones(1,ndm)] );
d(neg) = -d(neg);
angle(1:end)= 2 * acos( d(1,:) );
s(1:end) = sin( 0.5 * angle );
angle(n==0) = 0;
s(s==0) = 1;
s3 = shiftdim( s, -1 );
axis(1:end) = bsxfun( @rdivide, reshape( d(2:4,:), [3 siz] ), s3 );
axis(1,(mod(angle,2*pi)==0)) = 1;
angle = chop( angle );
axis = chop( axis );
% Flip axis so at least 2 out of 3 elements are >= 0
flip = (sum( axis < 0, 1 ) > 1) | ...
((sum( axis == 0, 1 ) == 2) & (any( axis < 0, 1 ) == 1));
angle(flip) = 2 * pi - angle(flip);
flip = repmat( flip, [3, ones(1,ndm)] );
axis(flip) = -axis(flip);
axis = squeeze( axis );
end % AngleAxis
function qd = Derivative( varargin )
% function qd = Derivative( q, w ) or qd = q.Derivative( w )
% Inputs:
% q quaternion array
% w 3xN or Nx3 element angle rate vectors in radians/s
% Output:
% qd quaternion derivatives, qd = 0.5 * q * quaternion(w)
if isa( varargin{1}, 'quaternion' )
qd = 0.5 .* varargin{1} .* quaternion( varargin{2} );
else
qd = 0.5 .* varargin{2} .* quaternion( varargin{1} );
end
end % Derivative
function angles = EulerAngles( varargin )
% function angles = EulerAngles( q, axes ) or angles = q.EulerAngles( axes )
% Construct Euler angle triplets equivalent to quaternion rotations
% Inputs:
% q quaternion array
% axes axes designation strings (e.g. '123' = xyz) or cell strings
% (e.g. {'123'})
% Output:
% angles 3 element Euler Angle vectors in radians
ics = cellfun( @ischar, varargin );
if any( ics )
varargin{ics} = cellstr( varargin{ics} );
else
ics = cellfun( @iscellstr, varargin );
end
if ~any( ics )
error( 'Must provide axes as a string (e.g. ''123'') or cell string (e.g. {''123''})' );
end
siv = cellfun( @size, varargin, 'UniformOutput', false );
axes = varargin{ics};
six = siv{ics};
nex = prod( six );
q = varargin{~ics};
siq = siv{~ics};
neq = prod( siq );
if neq == 1
siz = six;
nel = nex;
elseif nex == 1
siz = siq;
nel = neq;
elseif nex == neq
siz = siq;
nel = neq;
else
error( 'Must have compatible dimensions for quaternion and axes' );
end
angles = zeros( [3 siz] );
q = normalize( q );
for jel = 1 : nel
iel = min( jel, neq );
switch axes{min(jel,nex)}
case {'121', 'xyx', 'XYX', 'iji'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(3)- ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
angles(2,iel) = acos(q(iel).e(1).^2+q(iel).e(2).^2- ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
case {'123', 'xyz', 'XYZ', 'ijk'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(4).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
case {'131', 'xzx', 'XZX', 'iki'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
angles(2,iel) = acos(q(iel).e(1).^2+q(iel).e(2).^2- ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(4)- ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
case {'132', 'xzy', 'XZY', 'ikj'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(4).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
angles(3,iel) = atan2(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
case {'212', 'yxy', 'YXY', 'jij'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2+ ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(3)- ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
case {'213', 'yxz', 'YXZ', 'jik'}
angles(1,iel) = atan2(2.*(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(4).*q(iel).e(2)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
case {'231', 'yzx', 'YZX', 'jki'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
case {'232', 'yzy', 'YZY', 'jkj'}
angles(1,iel) = atan2((q(iel).e(3).*q(iel).e(4)- ...
q(iel).e(2).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2+ ...
q(iel).e(3).^2-q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)));
case {'312', 'zxy', 'ZXY', 'kij'}
angles(1,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(3)+ ...
q(iel).e(4).*q(iel).e(1)),(q(iel).e(1).^2- ...
q(iel).e(2).^2+q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
case {'313', 'zxz', 'ZXZ', 'kik'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(4)- ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2- ...
q(iel).e(3).^2+q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)));
case {'321', 'zyx', 'ZYX', 'kji'}
angles(1,iel) = atan2(2.*(q(iel).e(4).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(3)),(q(iel).e(1).^2+ ...
q(iel).e(2).^2-q(iel).e(3).^2-q(iel).e(4).^2));
angles(2,iel) = asin(2.*(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
angles(3,iel) = atan2(2.*(q(iel).e(2).*q(iel).e(1)- ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(1).^2- ...
q(iel).e(2).^2-q(iel).e(3).^2+q(iel).e(4).^2));
case {'323', 'zyz', 'ZYZ', 'kjk'}
angles(1,iel) = atan2((q(iel).e(2).*q(iel).e(1)+ ...
q(iel).e(3).*q(iel).e(4)),(q(iel).e(3).*q(iel).e(1)- ...
q(iel).e(2).*q(iel).e(4)));
angles(2,iel) = acos(q(iel).e(1).^2-q(iel).e(2).^2- ...
q(iel).e(3).^2+q(iel).e(4).^2);
angles(3,iel) = atan2((q(iel).e(3).*q(iel).e(4)- ...
q(iel).e(2).*q(iel).e(1)),(q(iel).e(2).*q(iel).e(4)+ ...
q(iel).e(3).*q(iel).e(1)));
otherwise
error( 'Invalid output Euler angle axes' );
end % switch axes
end % for iel
angles = chop( angles );
end % EulerAngles
function [omega, axis] = OmegaAxis( q, t, dim )
% function [omega, axis] = OmegaAxis( q, t, dim ) or
% [omega, axis] = q.OmegaAxis( t, dim )
% Estimate instantaneous angular velocities and rotation axes from a time
% series of quaternions. The angular velocity vector omegav is computed by:
% omegav(:,1) = vector( 2*log( q(1) * inverse(q(2)) )/(t(2) - t(1)) );
% omegav(:,i) = vector(...
% (log( q(i-1) * inverse(q(i)) ) + log( q(i) * inverse(q(i+1))) )/...
% (0.5*(t(i+1) - t(i-1))) );
% omegav(:,end) = vector( 2*log( q(end-1) * inverse(q(end)) )/...
% (t(end) - t(end-1)) );
% [axis, omega] = unitvector( omegav );
% Inputs:
% q array of normalized (rotation) quaternions
% t [OPT] array of monotonically increasing (or decreasing) times.
% if omitted or empty, unit time steps are assumed.
% t must either be a vector with the same length as dimension
% dim of q, or the same size as q.
% dim [OPT] dimension of q that is varying in time; if omitted or empty,
% the first non-singleton dimension is used.
% Outputs:
% omega array of instantaneous angular velocities, radians/(unit time)
% omega >= 0
% axis instantaneous 3D rotation axis unit vectors at each time
if isempty( q )
omega = [];
axis = [];
return;
end
if (nargin < 3) || isempty( dim )
if (nargin > 1) && ~isempty( t )
siq = size( q );
sit = size( t );
if isequal( siq, sit )
dim = find( siq > 1, 1 );
else
dim = find( siq == length( t ), 1 );
end
if isempty( dim )
error( 'size of t must agree with at least one dimension of q' );
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
if isequal( siq, sit )
t = permute( t, perm );
end
end
else
[q, dim, perm] = finddim( q, -2 );
if dim == 0
omega = 0;
axis = unitvector( q.e(2:4), 1 );
return;
end
end
elseif dim > 1
ndm = ndims( q );
perm = [ dim : ndm, 1 : dim-1 ];
q = permute( q, perm );
end
n = norm( q );
if ~all( abs( n(:) - 1 ) < eps(16) )
error( 'q must be normalized' );
end
siq = size( q );
if (nargin < 2) || isempty( t )
t = repmat( (0 : (siq(1)-1)).', [1 siq(2:end)] );
elseif length( t ) == siq(1)
t = repmat( t(:), [1 siq(2:end)] );
elseif ~isequal( siq, size( t ))
error( 'size of t must match size of q' );
end
dt = zeros( siq );
difft = diff( t, 1 );
dt(1,:) = difft(1,:);
dt(2:end-1,:) = 0.5 *( difft(1:end-1,:) + difft(2:end,:) );
dt(end,:) = difft(end,:);
dq = quaternion.zeros( siq );
q1iq2 = q(1:end-1,:) .* inverse( q(2:end,:) );
neg = real( q1iq2 ) < 0;
q1iq2(neg) = -q1iq2(neg); % keep real element >= 0
derivq = log( q1iq2 );
dq(1,:) = 2 .* derivq(1,:);
dq(2:end-1,:) = derivq(1:end-1,:) + derivq(2:end,:);
dq(end,:) = 2 .* derivq(end,:);
omegav = vector( dq ); % angular velocity vectors
[axis, omega] = unitvector( omegav, 1 );
omega = reshape( omega(1,:), siq )./ dt;
axis = -axis;
if dim > 1
axis = ipermute( axis, [1, 1+perm] );
omega = ipermute( omega, perm );
end
end % OmegaAxis
function PlotRotation( q, interval )
% function PlotRotation( q, interval ) or q.PlotRotation( interval )
% Inputs:
% q quaternion array
% interval pause between figure updates in seconds, default = 0.1
% Output:
% figure plotting the 3 Cartesian axes orientations for the series of
% quaternions in array q
if (nargin < 2) || isempty( interval )
interval = 0.1;
end
nel = numel( q );
or = zeros(1,3);
ax = eye(3);
alx = zeros( nel, 3, 3 );
figure;
for iel = 1 : nel
% plot3( [ or; ax(:,1).' ], [ or ; ax(:,2).' ], [ or; ax(:,3).' ], ':' );
plot3( [ or; ax(1,:) ], [ or ; ax(2,:) ], [ or; ax(3,:) ], ':' );
hold on
set( gca, 'Xlim', [-1 1], 'Ylim', [-1 1], 'Zlim', [-1 1] );
xlabel( 'x' );
ylabel( 'y' );
zlabel( 'z' );
grid on
nax = q(iel).RotationMatrix;
alx(iel,:,:) = nax;
% plot3( [ or; nax(:,1).' ], [ or ; nax(:,2).' ], [ or; nax(:,3).' ], '-', 'LineWidth', 2 );
plot3( [ or; nax(1,:) ], [ or ; nax(2,:) ], [ or; nax(3,:) ], '-', 'LineWidth', 2 );
% plot3( alx(1:iel,:,1), alx(1:iel,:,2), alx(1:iel,:,3), '*' );
plot3( squeeze(alx(1:iel,1,:)), squeeze(alx(1:iel,2,:)), squeeze(alx(1:iel,3,:)), '*' );
if interval
pause( interval );
end
hold off
end
end % PlotRotation
function [q1, w1, t1] = PropagateEulerEq( q0, w0, I, t, torque, varargin )
% function [q1, w1, t1] = PropagateEulerEq( q0, w0, I, t, torque, odeoptions )
% Inputs:
% q0 initial orientation quaternion (normalized, scalar)
% w0(3) initial body frame angular velocity vector
% I(3) principal body moments of inertia (if no torque, only
% ratios of elements of I are used)
% t(nt) initial and subsequent (or previous) times t = [t0,t1,...]
% (monotonic)
% @torque [OPTIONAL] function handle to calculate torque vector:
% tau(1:3) = torque( t, y ), where y = [q.e(1:4); w(1:3)]
% odeoptions [OPTIONAL] ode45 options
% Outputs:
% q1(1,nt) array of normalized quaternions at times t1
% w1(3,nt) array of body frame angular velocity vectors at times t1
% t1(1,nt) array of output times
% Calls:
% Derivative quaternion derivative method
% odeset matlab ode options setter
% ode45 matlab ode numerical differential equation integrator
% torque [OPTIONAL] user-supplied torque as function of time, orientation,
% and angular rates; default is no torque
% Author:
% Mark Tincknell, 20 December 2010
% modified 25 July 2012, enforce normalization of q0 and q1
options = odeset( varargin{:} );
q0 = q0.normalize;
y0 = [q0.e; w0(:)];
I0 = [ (I(2) - I(3)) / I(1);
(I(3) - I(1)) / I(2);
(I(1) - I(2)) / I(3) ];
[T, Y] = ode45( @Euler, t, y0, options );
function yd = Euler( ti, yi )
qi = quaternion( yi(1), yi(2), yi(3), yi(4) );
wi = yi(5:7);
qd = double( qi.Derivative( wi ));
wd = [ wi(2) * wi(3) * I0(1);
wi(3) * wi(1) * I0(2);
wi(1) * wi(2) * I0(3) ];
if exist( 'torque', 'var' ) && isa( torque, 'function_handle' )
tau = torque( ti, yi );
wd = tau(:) ./ I + wd;
end
yd = [ qd; wd ];
end
if numel(t) == 2
nT = 2;
T = [T(1); T(end)];
Y = [Y(1,:); Y(end,:)];
else
nT = length(T);
end
q1 = repmat( quaternion, [1 nT] );
w1 = zeros( [3 nT] );
t1 = T(:).';
for it = 1 : nT
q1(it) = quaternion( Y(it,1), Y(it,2), Y(it,3), Y(it,4) );
w1(:,it) = Y(it,5:7).';
end
q1 = q1.normalize;
neg = real( q1 ) < 0;
q1(neg) = -q1(neg); % keep real element >= 0
end % PropagateEulerEq
function vp = RotateVector( varargin )
% function vp = RotateVector( q, v, dim ) or
% vp = q.RotateVector( v, dim )
% 3x3 rotation matrices are created from q and matrix multiplication
% rotates v into vp. RotateVector is 7 times faster than RotateVectorQ.
% Inputs:
% q quaternion array
% v 3xN or Nx3 element Cartesian vectors
% dim [OPTIONAL] dimension of v with size 3 to rotate
% Output:
% vp 3xN or Nx3 element rotated vectors
if nargin < 2
error( 'RotateVector method requires 2 inputs: a vector and a quaternion' );
end
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
v = varargin{2};
else
v = varargin{1};
q = varargin{2};
end
if (nargin > 2) && ~isempty( varargin{3} )
dim = varargin{3};
if size( v, dim ) ~= 3
error( 'Dimension dim of vector v must be size 3' );
end
if dim > 1
ndm = ndims( v );
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
else
[v, dim, perm] = finddim( v, 3 );
if dim == 0
error( 'v must have a dimension of size 3' );
end
end
sip = size( v );
v = reshape( v, 3, [] );
nev = prod( sip )/ 3;
R = q.RotationMatrix;
siq = size( q );
neq = prod( siq );
if neq == nev
vp = zeros( sip );
for iel = 1 : neq
vp(:,iel) = R(:,:,iel) * v(:,iel);
end
if dim > 1
vp = ipermute( vp, perm );
end
elseif nev == 1
siz = [3 siq];
vp = zeros( siz );
for iel = 1 : neq
vp(:,iel) = R(:,:,iel) * v;
end
if siz(2) == 1
vp = squeeze( vp );
end
elseif neq == 1
vp = R * v;
vp = reshape( vp, sip );
if dim > 1
vp = ipermute( vp, perm );
end
else
error( 'q and v must have compatible dimensions' );
end
end % RotateVector
function vp = RotateVectorQ( varargin )
% function vp = RotateVectorQ( q, v, dim ) or
% vp = q.RotateVectorQ( v, dim )
% quaternions are created from v and quaternion multiplication rotates v
% into vp. RotateVector is 7 times faster than RotateVectorQ.
% Inputs:
% q quaternion array
% v 3xN or Nx3 element Cartesian vectors
% dim [OPTIONAL] dimension of v with size 3 to rotate
% Output:
% vp 3xN or Nx3 element rotated vectors
if nargin < 2
error( 'RotateVectorQ method requires 2 inputs: a vector and a quaternion' );
end
if isa( varargin{1}, 'quaternion' )
q = varargin{1};
v = varargin{2};
else
v = varargin{1};
q = varargin{2};
end
siv = size( v );
if (nargin > 2) && ~isempty( varargin{3} )
dim = varargin{3};
if size( v, dim ) ~= 3
error( 'Dimension dim of vector v must be size 3' );
end
if dim > 1
ndm = ndims( v );
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
else
[v, dim, perm] = finddim( v, 3 );
if dim == 0
error( 'v must have a dimension of size 3' );
end
end
sip = size( v );
qv = quaternion( v(1,:), v(2,:), v(3,:) );
qv = reshape( qv, [1 sip(2:end)] );
if dim > 1
qv = ipermute( qv, perm );
end
q = q.normalize;
qp = q .* qv .* q.conj;
dp = qp.double;
nev = prod( siv )/ 3;
sqz = false;
if nev == 1
siz = [3 size(q)];
if siz(2) == 1
sqz = true;
end
else
siz = siv;
end
vp = reshape( dp(2:4,:), siz );
if sqz
vp = squeeze( vp );
end
end % RotateVectorQ
function R = RotationMatrix( q )
% function R = RotationMatrix( q ) or R = q.RotationMatrix
% Construct rotation (or direction cosine) matrices from quaternions
% Input:
% q quaternion array
% Output:
% R 3x3xN rotation (or direction cosine) matrices
siz = size( q );
R = zeros( [3 3 siz] );
nel = prod( siz );
q = normalize( q );
for iel = 1 : nel
e11 = q(iel).e(1)^2;
e12 = q(iel).e(1) * q(iel).e(2);
e13 = q(iel).e(1) * q(iel).e(3);
e14 = q(iel).e(1) * q(iel).e(4);
e22 = q(iel).e(2)^2;
e23 = q(iel).e(2) * q(iel).e(3);
e24 = q(iel).e(2) * q(iel).e(4);
e33 = q(iel).e(3)^2;
e34 = q(iel).e(3) * q(iel).e(4);
e44 = q(iel).e(4)^2;
R(:,:,iel) = ...
[ e11 + e22 - e33 - e44, 2*(e23 - e14), 2*(e24 + e13); ...
2*(e23 + e14), e11 - e22 + e33 - e44, 2*(e34 - e12); ...
2*(e24 - e13), 2*(e34 + e12), e11 - e22 - e33 + e44 ];
end
R = chop( R );
end % RotationMatrix
end % methods
% Static methods
methods(Static)
function q = angleaxis( angle, axis )
% function q = quaternion.angleaxis( angle, axis )
% Construct quaternions from rotation axes and rotation angles
% Inputs:
% angle array of rotation angles in radians
% axis 3xN or Nx3 array of axes (need not be unit vectors)
% Output:
% q quaternion array
sig = size( angle );
six = size( axis );
[axis, dim, perm] = finddim( axis, 3 );
if dim == 0
error( 'axis must have a dimension of size 3' );
end
neg = prod( sig );
nex = prod( six )/ 3;
if neg == 1
siz = six;
siz(dim)= 1;
nel = nex;
elseif nex == 1
siz = sig;
nel = neg;
elseif nex == neg
siz = sig;
nel = neg;
else
error( 'angle and axis must have compatible sizes' );
end
for iel = nel : -1 : 1
d(:,iel) = AngAxis2e( angle(min(iel,neg)), axis(:,min(iel,nex)) );
end
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = reshape( q, siz );
if neg == 1
q = ipermute( q, perm );
end
end % quaternion.angleaxis
function q = eulerangles( varargin )
% function q = quaternion.eulerangles( axes, angles ) OR
% function q = quaternion.eulerangles( axes, ang1, ang2, ang3 )
% Construct quaternions from triplets of axes and Euler angles
% Inputs:
% axes string array or cell string array
% '123' = 'xyz' = 'XYZ' = 'ijk', etc.
% angles 3xN or Nx3 array of angles in radians OR
% ang1, ang2, ang3 arrays of angles in radians
% Output:
% q quaternion array
ics = cellfun( @ischar, varargin );
if any( ics )
varargin{ics} = cellstr( varargin{ics} );
else
ics = cellfun( @iscellstr, varargin );
end
siv = cellfun( @size, varargin, 'UniformOutput', false );
axes = varargin{ics};
six = siv{ics};
nex = prod( six );
dim = 1;
if nargin == 2 % angles is 3xN or Nx3 array
angles = varargin{~ics};
sig = siv{~ics};
[angles, dim, perm] = finddim( angles, 3 );
if dim == 0
error( 'Must supply 3 Euler angles' );
end
sig(dim) = 1;
neg = prod( sig );
if nex == 1
siz = sig;
elseif neg == 1
siz = six;
elseif nex == neg
siz = sig;
end
nel = prod( siz );
for iel = nel : -1 : 1
q(iel) = EulerAng2q( axes{min(iel,nex)}, ...
angles(:,min(iel,neg)) );
end
elseif nargin == 4 % each of 3 angles is separate input argument
angles = varargin(~ics);
na = cellfun( 'prodofsize', angles );
[neg, jeg] = max( na );
if ~all( (na == 1) | (na == neg) )
error( 'All angles must be singletons or have the same number of elements' );
end
sig = size( angles{jeg} );
if nex == 1
siz = sig;
elseif neg == 1
siz = six;
elseif nex == neg
siz = sig;
end
nel = prod( siz );
for iel = nel : -1 : 1
q(iel) = EulerAng2q( axes{min(iel,nex)}, ...
[angles{1}(min(iel,na(1))), ...
angles{2}(min(iel,na(2))), ...
angles{3}(min(iel,na(3)))] );
end
else
error( 'Must supply either 2 or 4 input arguments' );
end % if nargin
q = reshape( q, siz );
if (dim > 1) && isequal( siz, sig )
q = ipermute( q, perm );
end
if ~ismatrix( q ) && (size( q, 1 ) == 1)
q = shiftdim( q, 1 );
end
end % quaternion.eulerangles
function q = eye( N )
% function q = eye( N )
if nargin < 1
N = 1;
end
if isempty(N) || (N <= 0)
q = quaternion.empty;
else
q = quaternion( eye(N), 0, 0, 0 );
end
end % quaternion.eye
function q = nan( varargin )
% function q = quaternion.nan( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( nan(siz), nan, nan, nan );
end
end % quaternion.nan
function q = NaN( varargin )
% function q = quaternion.NaN( siz )
q = quaternion.nan( varargin{:} );
end % quaternion.NaN
function q = ones( varargin )
% function q = quaternion.ones( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( ones(siz), 0, 0, 0 );
end
end % quaternion.ones
function q = rand( varargin )
% function q = quaternion.rand( siz )
% Input:
% siz size of output array q
% Output:
% q uniform random quaternions, NOT normalized to 1,
% 0 <= q.e(1) <= 1, -1 <= q.e(2:4) <= 1
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = quaternion.empty;
return;
end
d = [ rand( [1, siz] ); 2 * rand( [3, siz] ) - 1 ];
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = reshape( q, siz );
end % quaternion.rand
function q = randRot( varargin )
% function q = quaternion.randRot( siz )
% Random quaternions uniform in rotation space
% Input:
% siz size of output array q
% Output:
% q random quaternions, normalized to 1, 0 <= q.e(1) <= 1,
% uniform over the 3D surface of a 4 dimensional hypersphere
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = quaternion.empty;
return;
end
d = randn( [4, prod( siz )] );
n = sqrt( sum( d.^2, 1 ));
dn = bsxfun( @rdivide, d, n );
neg = dn(1,:) < 0;
dn(:,neg) = -dn(:,neg);
q = quaternion( dn(1,:), dn(2,:), dn(3,:), dn(4,:) );
q = reshape( q, siz );
end % quaternion.randRot
function q = rotateutov( u, v, dimu, dimv )
% function q = quaternion.rotateutov( u, v, dimu, dimv )
% Construct quaternions to rotate vectors u into directions of vectors v
% Inputs:
% u 3x1 or 3xN or 1x3 or Nx3 arrays of vectors
% v 3x1 or 3xN or 1x3 or Nx3 arrays of vectors
% dimu [OPTIONAL] dimension of u with size 3 to use
% dimv [OPTIONAL] dimension of v with size 3 to use
% Output:
% q quaternion array
if (nargin < 3) || isempty( dimu )
[u, dimu, permu] = finddim( u, 3 );
if dimu == 0
error( 'u must have a dimension of size 3' );
end
elseif dimu > 1
ndmu = ndims( u );
permu = [ dimu : ndmu, 1 : dimu-1 ];
u = permute( u, permu );
else
permu = 1 : ndims(u);
end
siu = size( u );
siu(1) = 1;
neu = prod( siu );
if (nargin < 4) || isempty( dimv )
[v, dimv, permv] = finddim( v, 3 );
if dimv == 0
error( 'v must have a dimension of size 3' );
end
elseif dimv > 1
ndmv = ndims( v );
permv = [ dimv : ndmv, 1 : dimv-1 ];
v = permute( v, permv );
else
permv = 1 : ndims(v);
end
siv = size( v );
siv(1) = 1;
nev = prod( siv );
if neu == nev
siz = siu;
nel = neu;
perm = permu;
dim = dimu;
elseif (neu > 1) && (nev == 1)
siz = siu;
nel = neu;
perm = permu;
dim = dimu;
elseif (neu == 1) && (nev > 1)
siz = siv;
nel = nev;
perm = permv;
dim = dimv;
else
error( 'Number of 3 element vectors in u and v must be 1 or equal' );
end
for iel = nel : -1 : 1
q(iel) = UV2q( u(:,min(iel,neu)), v(:,min(iel,nev)) );
end
if dim > 1
q = ipermute( reshape( q, siz ), perm );
end
end % quaternion.rotateutov
function q = rotationmatrix( R )
% function q = quaternion.rotationmatrix( R )
% Construct quaternions from rotation (or direction cosine) matrices
% Input:
% R 3x3xN rotation (or direction cosine) matrices
% Output:
% q quaternion array
siz = [size(R) 1 1];
if ~all( siz(1:2) == [3 3] ) || ...
(abs( det( R(:,:,1) ) - 1 ) > eps(16) )
error( 'Rotation matrices must be 3x3xN with det(R) == 1' );
end
nel = prod( siz(3:end) );
for iel = nel : -1 : 1
d(:,iel) = RotMat2e( chop( R(:,:,iel) ));
end
q = quaternion( d(1,:), d(2,:), d(3,:), d(4,:) );
q = normalize( q );
q = reshape( q, siz(3:end) );
end % quaternion.rotationmatrix
function q = zeros( varargin )
% function q = quaternion.zeros( siz )
if isempty( varargin )
siz = [1 1];
elseif numel( varargin ) > 1
siz = [varargin{:}];
elseif isempty( varargin{1} )
siz = [0 0];
elseif numel( varargin{1} ) > 1
siz = varargin{1};
else
siz = [varargin{1} varargin{1}];
end
if prod( siz ) == 0
q = reshape( quaternion.empty, siz );
else
q = quaternion( zeros(siz), 0, 0, 0 );
end
end % quaternion.zeros
end % methods(Static)
end % classdef quaternion
% Scalar rotation conversion functions
function eout = AngAxis2e( angle, axis )
% function eout = AngAxis2e( angle, axis )
% One Angle-Axis -> one quaternion
s = sin( 0.5 * angle );
v = axis(:);
vn = norm( v );
if vn == 0
if s == 0
c = 0;
else
c = 1;
end
u = zeros( 3, 1 );
else
c = cos( 0.5 * angle );
u = v(:) ./ vn;
end
eout = [ c; s * u ];
if (eout(1) < 0) && (mod( angle/(2*pi), 2 ) ~= 1)
eout = -eout; % rotationally equivalent quaternion with real element >= 0
end
end % AngAxis2e
function qout = EulerAng2q( axes, angles )
% function qout = EulerAng2q( axes, angles )
% One triplet Euler Angles -> one quaternion
na = length( axes );
axis = zeros( 3, na );
for i0 = 1 : na
switch axes(i0)
case {'1', 'i', 'x', 'X'}
axis(:,i0) = [ 1; 0; 0 ];
case {'2', 'j', 'y', 'Y'}
axis(:,i0) = [ 0; 1; 0 ];
case {'3', 'k', 'z', 'Z'}
axis(:,i0) = [ 0; 0; 1 ];
otherwise
error( 'Illegal axis designation' );
end
end
q0 = quaternion.angleaxis( angles(:).', axis );
qout = q0(1);
for i0 = 2 : numel(q0)
qout = product( q0(i0), qout );
end
if qout.e(1) < 0
qout = -qout; % rotationally equivalent quaternion with real element >= 0
end
end % EulerAng2q
function eout = RotMat2e( R )
% function eout = RotMat2e( R )
% One Rotation Matrix -> one quaternion
eout = zeros(4,1);
if ~all( all( R == 0 ))
eout(1) = 0.5 * sqrt( max( 0, R(1,1) + R(2,2) + R(3,3) + 1 ));
if eout(1) == 0
eout(2) = sqrt( max( 0, -0.5 *( R(2,2) + R(3,3) ))) * ...
sgn( -R(2,3) );
eout(3) = sqrt( max( 0, -0.5 *( R(1,1) + R(3,3) ))) * ...
sgn( -R(1,3) );
eout(4) = sqrt( max( 0, -0.5 *( R(1,1) + R(2,2) ))) * ...
sgn( -R(1,2) );
else
eout(2) = 0.25 *( R(3,2) - R(2,3) )/ eout(1);
eout(3) = 0.25 *( R(1,3) - R(3,1) )/ eout(1);
eout(4) = 0.25 *( R(2,1) - R(1,2) )/ eout(1);
end
end
end % RotMat2e
function qout = UV2q( u, v )
% function qout = UV2q( u, v )
% One pair vectors U, V -> one quaternion
w = cross( u, v ); % construct vector w perpendicular to u and v
magw = norm( w );
dotuv = dot( u, v );
if magw == 0
% Either norm(u) == 0 or norm(v) == 0 or dotuv/(norm(u)*norm(v)) == 1
if dotuv >= 0
qout = quaternion( 1, 0, 0, 0 );
return;
end
% dotuv/(norm(u)*norm(v)) == -1
% If v == [v(1); 0; 0], rotate by pi about the [0; 0; 1] axis
if (v(2) == 0) && (v(3) == 0)
qout = quaternion( 0, 0, 0, 1 );
return;
end
% Otherwise constuct "what" such that dot(v,what) == 0, and rotate about it
% by pi
what = [ 0; -v(3); v(2) ]./ sqrt( v(2)^2 + v(3)^2 );
costh = -1;
else
% Use w as rotation axis, angle between u and v as rotation angle
what = w(:) / magw;
costh = dotuv /( norm(u) * norm(v) );
end
c = sqrt( 0.5 *( 1 + costh )); % real element >= 0
s = sqrt( 0.5 *( 1 - costh ));
eout = [ c; s * what ];
qout = quaternion( eout(1), eout(2), eout(3), eout(4) );
end % UV2q
% Helper functions
function out = chop( in, tol )
% function out = chop( in, tol )
% Replace values that differ from an integer by <= tol by the integer
% Inputs:
% in input array
% tol tolerance, default = eps
% Output:
% out input array with integer replacements, if any
if (nargin < 2) || isempty( tol )
tol = eps;
end
out = in;
rin = round( in );
lx = abs( rin - in ) <= tol;
out(lx) = rin(lx);
end % chop
function [aout, dim, perm] = finddim( ain, len )
% function [aout, dim, perm] = finddim( ain, len )
% Find first dimension in ain of length len, permute ain to make it first
% Inputs:
% ain(s1,s2,...) data array, size = [s1, s2, ...]
% len length sought, e.g. s2 == len
% if len < 0, then find first dimension >= |len|
% Outputs:
% aout(s2,...,s1) data array, permuted so first dimension is length len
% dim dimension number of length len, 0 if ain has none
% perm permutation order (for permute and ipermute) of aout,
% e.g. [2, ..., 1]
% Notes: if no dimension has length len, aout = ain, dim = 0, perm = 1:ndm
% ain = ipermute( aout, perm )
siz = size( ain );
ndm = length( siz );
if len < 0
dim = find( siz >= -len, 1, 'first' );
else
dim = find( siz == len, 1, 'first' );
end
if isempty( dim )
dim = 0;
end
if dim < 2
aout = ain;
perm = 1 : ndm;
else
% Permute so that dim becomes the first dimension
perm = [ dim : ndm, 1 : dim-1 ];
aout = permute( ain, perm );
end
end % finddim
function s = sgn( x )
% function s = sgn( x ), if x >= 0, s = 1, else s = -1
s = ones( size( x ));
s(x < 0) = -1;
end % sgn
function [u, n] = unitvector( v, dim )
% function [u, n] = unitvector( v, dim )
% Inputs:
% v matrix of vectors
% dim [OPTIONAL] dimension to normalize, dim >= 1
% if no dim input, use first dimension of length >= 2
% Outputs:
% u matrix of unit vectors (except for vectors of norm 0)
% n matrix same size as v and u of norms
ndm = ndims( v );
if (nargin < 2) || isempty( dim )
[v, dim, perm] = finddim( v, -2 );
if dim == 0
n = sqrt( v.*conj(v) );
n0 = (n ~= 0) & (n ~= 1);
u = v;
u(n0) = v(n0) ./ n(n0);
return;
end
else
perm = [ dim : ndm, 1 : dim-1 ];
v = permute( v, perm );
end
u = v;
sv = size( v );
n = repmat( sqrt( sum( v.*conj(v), 1 )), [sv(1) ones(1,ndm-1)] );
n0 = (n ~= 0) & (n ~= 1);
u(n0) = v(n0) ./ n(n0);
u = ipermute( u, perm );
if nargout > 1
n = ipermute( n, perm );
end
end % unitvector
|
github
|
jianxiongxiao/ProfXkit-master
|
rectify.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/rectify.m
| 5,343 |
utf_8
|
bd641fe58842594e88f1d3d86a1f5271
|
function [Rtilt,R] = rectify(XYZ)
%% XYZ is HxWx3 matrix
% X = XYZ(:,:,1);Y = XYZ(:,:,2);Z = XYZ(:,:,3);
% XYZnew = Rtilt*[X(:),Y(:),Z(:)]'
[Rtilt,R,world_center] = dominantAxes([eye(3) zeros(3,1)],XYZ);
function [Rtilt,R,world_center] = dominantAxes(cameraRt, pts)
XYZ = pts;
S = 10;
points = [reshape(XYZ(:,:,1),1,[]);reshape(XYZ(:,:,2),1,[]);reshape(XYZ(:,:,3),1,[])];
pointsOK = points(:,sum(isnan(points),1)==0);
pointsOK = pointsOK(:,1:S:end);
%tic;normals = points2normals_radius(pointsOK);toc;
normals = points2normals(pointsOK);
%{
figure,
s =1;
quiver3(pointsOK(1,1:S*s:end),pointsOK(2,1:S*s:end),pointsOK(3,1:S*s:end),normals(1,1:S*s:end),normals(2,1:S*s:end),normals(3,1:S*s:end));
quiver3(pointsOK(1,1:S*s:end),pointsOK(2,1:S*s:end),pointsOK(3,1:S*s:end),normals(1,1:s:end),normals(2,1:s:end),normals(3,1:s:end));
figure,
indxxx = B == b;
pointsOKxxx = pointsOK(:,1:S:end);
quiver3(pointsOKxxx(1,indxxx),pointsOKxxx(2,indxxx),pointsOKxxx(3,indxxx),normals(1,indxxx),normals(2,indxxx),normals(3,indxxx));
hold on
quiver3(pointsOK(1,1:S*s:end),pointsOK(2,1:S*s:end),pointsOK(3,1:S*s:end),nrm(1,1:s:end),nrm(2,1:s:end),nrm(3,1:s:end),'-.r');
figure,
plot3(sphere(1,:),sphere(2,:),sphere(3,:),'.')
%}
% approximately 1313 bins
sphere = icosahedron2sphere(4)';
bins = sphere(:, sphere(1, :) >= 0);
%NSAMPLE = 1e5;
%sampleind = randsample(1 : size(normals, 2), min(size(normals, 2), NSAMPLE));
%normals = normals(:,sampleind );
[D, B] = max(abs(bins' * normals), [], 1);
H = accumarray(cat(2, B', repmat(1, [length(B) 1])), repmat(1, [length(B) 1]));
A = eye(3);
[~, I] = sort(-H);
for j = 1 : 3
if ~isempty(I)
b = I(1);
% choose mean normal that falls into the biggest bin
in_bin = normals(:, B == b);
% flip mirrored normals
dots = sum(in_bin .* repmat(bins(:, b), [1 size(in_bin, 2)]), 1);
in_bin(:, (dots < 0)) = -in_bin(:, (dots < 0));
v = mean(in_bin, 2);
v = v / norm(v);
A(:, j) = v;
fprintf('Bin: %d, Normal: %f %f %f. Contains %d points. Mean vector: %f %f %f\n', b, bins(:, b), H(b), v);
% remove bins that are not ~90 degrees away
dots = sum(bins(:, I) .* repmat(v, [1 length(I)]), 1);
I = I((dots >= cos(deg2rad(110))) & (dots <= cos(deg2rad(70))));
end
end
axisI = A(:,1);
axisII = A(:,2);
axisII = axisII - (axisI'*axisII)*axisI;
axisII =axisII/norm(axisII);
axisIII = cross(axisI,axisII);
AA =[axisI,axisII,axisIII -1*[axisI,axisII,axisIII]];
[~, zi] = max(squeeze(cameraRt(1:3, 3, :))'*AA);
ZZ = AA(:, zi);
[~, xi] = max(squeeze(cameraRt(1:3, 1, :))'*AA);
XX = AA(:, xi);
[~, yi] = max(squeeze(cameraRt(1:3, 2, :))'*AA);
YY = AA(:, yi);
%{
for i =1:3,
hold on;
quiver3(1,1,1,AA(1,i),AA(2,i),AA(3,i));
quiver3(0,0,0,A(1,i),A(2,i),A(3,i));
pause;
end
axis tight;
%}
R = [XX YY ZZ]';
q = quaternion.rotateutov(ZZ, [0;0;1]);
Rtilt = RotationMatrix(q);
world_center = nanmean(reshape(pts,3,[]),2);
function rad = deg2rad(deg)
rad = deg*pi/180;
return;
function [coor,tri] = icosahedron2sphere(level)
% copyright by Jianxiong Xiao http://mit.edu/jxiao
% this function use a icosahedron to sample uniformly on a sphere
%{
Please cite this paper if you use this code in your publication:
J. Xiao, T. Fang, P. Zhao, M. Lhuillier, and L. Quan
Image-based Street-side City Modeling
ACM Transaction on Graphics (TOG), Volume 28, Number 5
Proceedings of ACM SIGGRAPH Asia 2009
%}
a= 2/(1+sqrt(5));
M=[
0 a -1 a 1 0 -a 1 0
0 a 1 -a 1 0 a 1 0
0 a 1 0 -a 1 -1 0 a
0 a 1 1 0 a 0 -a 1
0 a -1 0 -a -1 1 0 -a
0 a -1 -1 0 -a 0 -a -1
0 -a 1 a -1 0 -a -1 0
0 -a -1 -a -1 0 a -1 0
-a 1 0 -1 0 a -1 0 -a
-a -1 0 -1 0 -a -1 0 a
a 1 0 1 0 -a 1 0 a
a -1 0 1 0 a 1 0 -a
0 a 1 -1 0 a -a 1 0
0 a 1 a 1 0 1 0 a
0 a -1 -a 1 0 -1 0 -a
0 a -1 1 0 -a a 1 0
0 -a -1 -1 0 -a -a -1 0
0 -a -1 a -1 0 1 0 -a
0 -a 1 -a -1 0 -1 0 a
0 -a 1 1 0 a a -1 0
];
coor = reshape(M',3,60)';
%[M(:,[1 2 3]); M(:,[4 5 6]); M(:,[7 8 9])];
[coor, ~, idx] = unique(coor,'rows');
tri = reshape(idx,3,20)';
%{
for i=1:size(tri,1)
x(1)=coor(tri(i,1),1);
x(2)=coor(tri(i,2),1);
x(3)=coor(tri(i,3),1);
y(1)=coor(tri(i,1),2);
y(2)=coor(tri(i,2),2);
y(3)=coor(tri(i,3),2);
z(1)=coor(tri(i,1),3);
z(2)=coor(tri(i,2),3);
z(3)=coor(tri(i,3),3);
patch(x,y,z,'r');
end
axis equal
axis tight
%}
% extrude
coor = coor ./ repmat(sqrt(sum(coor .* coor,2)),1, 3);
for i=1:level
m = 0;
for t=1:size(tri,1)
n = size(coor,1);
coor(n+1,:) = ( coor(tri(t,1),:) + coor(tri(t,2),:) ) / 2;
coor(n+2,:) = ( coor(tri(t,2),:) + coor(tri(t,3),:) ) / 2;
coor(n+3,:) = ( coor(tri(t,3),:) + coor(tri(t,1),:) ) / 2;
triN(m+1,:) = [n+1 tri(t,1) n+3];
triN(m+2,:) = [n+1 tri(t,2) n+2];
triN(m+3,:) = [n+2 tri(t,3) n+3];
triN(m+4,:) = [n+1 n+2 n+3];
n = n+3;
m = m+4;
end
tri = triN;
% uniquefy
[coor, ~, idx] = unique(coor,'rows');
tri = idx(tri);
% extrude
coor = coor ./ repmat(sqrt(sum(coor .* coor,2)),1, 3);
end
% vertex number: 12 42 162 642
|
github
|
jianxiongxiao/ProfXkit-master
|
loadStructureIOdata.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/loadStructureIOdata.m
| 1,696 |
utf_8
|
cfffdd283dc7a2322c9963dab946a95a
|
% Load data taken from Structure IO
function data = loadStructureIOdata(directory, frameIDs)
% Get image file list
imageFiles = dir(fullfile(directory, 'color', '*.jpg'));
depthFiles = dir(fullfile(directory, 'depth', '*.png'));
% Set default frames to go through
if length(frameIDs) == 0
frameIDs = 1:length(imageFiles);
end
% Loop through all image files to get corresponding image and depth names
count = 0;
data.depthTimestamp = zeros(1,length(depthFiles));
data.imageTimestamp = zeros(1,length(imageFiles));
for frameID = frameIDs
count = count + 1;
timestr = regexp(imageFiles(frameID).name,'\d+T\d+\.\d+\.\d+\.\d+-','match');
timeArr = sscanf(timestr{1}, '%dT%d.%d.%d.%d-');
data.imageTimestamp(frameID) = timeArr(1)*24*3600000 + timeArr(2)*3600000+timeArr(3)*60000+timeArr(4)*1000+timeArr(5);
timestr = regexp(depthFiles(frameID).name,'\d+T\d+\.\d+\.\d+\.\d+-','match');
timeArr = sscanf(timestr{1}, '%dT%d.%d.%d.%d-');
data.depthTimestamp(frameID) = timeArr(1)*24*3600000 + timeArr(2)*3600000+timeArr(3)*60000+timeArr(4)*1000+timeArr(5);
data.imageAll{count} = fullfile(fullfile(directory, 'color', imageFiles(frameID).name));
data.depthAll{count} = fullfile(fullfile(directory, 'depth', depthFiles(frameID).name));
end
% Grab camera data
data.K = reshape(readValuesFromTxt(fullfile(directory, 'intrinsics.txt')), 3, 3)';
if exist(fullfile(directory, 'intrinsics_d2c.txt'),'file')
depthCam = readValuesFromTxt(fullfile(directory, 'intrinsics_d2c.txt'));
data.Kdepth = reshape(depthCam(1:9), 3, 3)';
data.RT_d2c = reshape(depthCam(10:21), 4, 3)';
else
data.image = data.imageAll;
data.depth = data.depthAll;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
loadSUN3Dv2.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/loadSUN3Dv2.m
| 4,264 |
utf_8
|
200caa9bc4374066976ff436d05416b9
|
function data = loadSUN3Dv2(sequenceName, frameIDs)
if ~exist('sequenceName','var')
sequenceName = '2014-04-29_14-39-49_094959634447';
end
SUN3Dpath = '/n/fs/sun3d/sun3dv2/';
%{
fileID = fopen(fullfile(SUN3Dpath,sequenceName,'image/time.dat'));
imageTimestamp = fread(fileID,'int64');
fclose(fileID);
data.image = VideoReader(fullfile(SUN3Dpath,sequenceName,'image/image.mp4'));
%}
imageFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'image/'),'jpg');
imageFrameID = zeros(1,length(imageFiles));
imageTimestamp = zeros(1,length(imageFiles));
for i=1:length(imageFiles)
id_time = sscanf(imageFiles(i).name, '%d-%ld.jpg');
imageFrameID(i) = id_time(1);
imageTimestamp(i) = id_time(2);
data.imageAll{i}= fullfile(fullfile(SUN3Dpath,sequenceName,'image',imageFiles(i).name));
end
depthFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'depth/'),'tif');
irFiles = dirSmart(fullfile(SUN3Dpath,sequenceName,'ir/'),'tif');
depthFrameID = zeros(1,length(depthFiles));
depthTimestamp = zeros(1,length(depthFiles));
for i=1:length(depthFiles)
id_time = sscanf(depthFiles(i).name, '%d-%ld.tif');
depthFrameID(i) = id_time(1);
depthTimestamp(i) = id_time(2);
data.depthAll{i}= fullfile(fullfile(SUN3Dpath,sequenceName,'depth',depthFiles(i).name));
end
irFrameID = zeros(1,length(irFiles));
irTimestamp = zeros(1,length(irFiles));
for i=1:length(irFiles)
id_time = sscanf(irFiles(i).name, '%d-%ld.tif');
irFrameID(i) = id_time(1);
irTimestamp(i) = id_time(2);
data.irAll{i}= fullfile(fullfile(SUN3Dpath,sequenceName,'ir',irFiles(i).name));
end
data.imageTimestamp = imageTimestamp;
data.depthTimestamp = depthTimestamp;
data.imageTotalFrames = length(data.imageTimestamp);
data.depthTotalFrames = length(data.depthTimestamp);
% synchronize: find a depth for each image
frameCount = length(imageTimestamp);
IDimage2depth = zeros(1,frameCount);
for i=1:frameCount
[~, IDimage2depth(i)]=min(abs(double(depthTimestamp)-double(imageTimestamp(i))));
end
if ~exist('frameIDs','var') || isempty(frameIDs)
frameIDs = 1:frameCount;
end
data.sequenceName = sequenceName;
cnt = 0;
for frameID=frameIDs
cnt = cnt + 1;
data.depth{cnt} = fullfile(fullfile(SUN3Dpath,sequenceName,'depth',depthFiles(IDimage2depth(frameID)).name));
data.ir{cnt} = fullfile(fullfile(SUN3Dpath,sequenceName,'ir',irFiles(IDimage2depth(frameID)).name));
end
kinectID = strsplit(sequenceName,'_');
kinectID = kinectID{end};
data.camera = load(fullfile(SUN3Dpath,'intrinsics',[kinectID '.mat']));
end
function files = dirSmart(page, tag)
[files, status] = urldir(page, tag);
if status == 0
files = dir(fullfile(page, ['*.' tag]));
end
end
function [files, status] = urldir(page, tag)
if nargin == 1
tag = '/';
else
tag = lower(tag);
if strcmp(tag, 'dir')
tag = '/';
end
if strcmp(tag, 'img')
tag = 'jpg';
end
end
nl = length(tag);
nfiles = 0;
files = [];
% Read page
page = strrep(page, '\', '/');
[webpage, status] = urlread(page);
if status
% Parse page
j1 = findstr(lower(webpage), '<a href="');
j2 = findstr(lower(webpage), '</a>');
Nelements = length(j1);
if Nelements>0
for f = 1:Nelements
% get HREF element
chain = webpage(j1(f):j2(f));
jc = findstr(lower(chain), '">');
chain = deblank(chain(10:jc(1)-1));
% check if it is the right type
if length(chain)>length(tag)-1
if strcmp(chain(end-nl+1:end), tag)
nfiles = nfiles+1;
chain = strrep(chain, '%20', ' '); % replace space character
files(nfiles).name = chain;
files(nfiles).bytes = 1;
end
end
end
end
end
end
function XYZcamera = depth2XYZcamera(K, depth)
sz = size(depth);
[x,y] = meshgrid(1:sz(2), 1:sz(1));
XYZcamera(:,:,1) = (x-K(1,3)).*depth/K(1,1);
XYZcamera(:,:,2) = (y-K(2,3)).*depth/K(2,2);
XYZcamera(:,:,3) = depth;
XYZcamera(:,:,4) = depth~=0;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
estimateRt.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/estimateRt.m
| 501 |
utf_8
|
d7ad6f4ea024b18ceb9915fec69b9a71
|
% Usage: Rt = estimateRt(x1, x2)
% Rt = estimateRt(x)
%
% Arguments:
% x1, x2 - Two sets of corresponding 3xN set of homogeneous
% points.
%
% x - If a single argument is supplied it is assumed that it
% is in the form x = [x1; x2]
% Returns:
% Rt - The rotation matrix such that x1 = R * x2 + t
function Rt = estimateRt(x, npts)
[T, Eps] = estimateRigidTransform(x(1:3,:), x(4:6,:));
Rt = T(1:3,:);
end
|
github
|
jianxiongxiao/ProfXkit-master
|
get_depth.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/get_depth.m
| 131 |
utf_8
|
8ee8bdf3980d7e82262719804012ca95
|
function depth = get_depth(depth)
depth = bitor(bitshift(depth,-3), bitshift(depth,16-3));
depth = double(depth)/1000;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
points2ply.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/points2ply.m
| 1,440 |
utf_8
|
aac4b7c6b547a9c026121d967f85a036
|
function points2ply(PLYfilename, coordinate, rgb)
% coordinate is 3 * n single matrix for n points
% rgb is 3 * n uint8 matrix for n points range [0, 255]
if size(coordinate,2)==3 && size(coordinate,1)~=3
coordinate = coordinate';
end
isValid = (~isnan(coordinate(1,:))) & (~isnan(coordinate(2,:))) & (~isnan(coordinate(3,:)));
coordinate = coordinate(:,isValid);
data = reshape(typecast(reshape(single(coordinate),1,[]),'uint8'),3*4,[]);
if nargin>2
if size(rgb,2)==3 && size(rgb,1)~=3
rgb = rgb';
end
if ~isa(rgb,'uint8')
if max(rgb(:))<=1
rgb = rgb * 255;
end
end
if isa(rgb,'double')
rgb = uint8(rgb);
end
rgb = rgb(:,isValid);
data = [data; rgb];
end
file = fopen(PLYfilename,'w');
fprintf (file, 'ply\n');
fprintf (file, 'format binary_little_endian 1.0\n');
fprintf (file, 'element vertex %d\n', size(data,2));
fprintf (file, 'property float x\n');
fprintf (file, 'property float y\n');
fprintf (file, 'property float z\n');
if nargin>2
fprintf (file, 'property uchar red\n');
fprintf (file, 'property uchar green\n');
fprintf (file, 'property uchar blue\n');
end
fprintf (file, 'end_header\n');
fwrite(file, data,'uint8');
fclose(file);
end
|
github
|
jianxiongxiao/ProfXkit-master
|
undistort.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/undistort.m
| 4,632 |
utf_8
|
e1febb403e3759f567009ee0a0442cce
|
function x = undistort( xd, k, seed )
%[x] = undistort(xd, k)
%INPUT: xd: distorted (normalized) point coordinates in the image plane (2xN matrix)
% k: Distortion coefficients (radial and tangential) (5x1 vector)
% seed: (OPTIONAL) seed point corrdinates for undistortion
% optimization
% Written by Fisher Yu
k1 = k(1);
k2 = k(2);
k3 = k(5);
p1 = k(3);
p2 = k(4);
if nargin < 3
seed = xd; % initial guess
end
% First undistort with oulu algorithm
x = undistort_oulu(xd, k);
% Find the bad undistorted pixels and refine with better optimization
new_xd = distort(x, k);
errors = sum((xd - new_xd) .^ 2);
badones = errors > 1e-10;
num_badones = sum(badones);
%fprintf('Found %d bad ones\n', num_badones);
if num_badones>0
options = optimoptions(@fsolve,'Display','off','Jacobian','on',...
'Algorithm','trust-region-reflective','PrecondBandWidth',1);
f = @(x) undistort_Jv(x, xd(:, badones), k);
x(:, badones) = reshape(fsolve(f, seed(:, badones), options), [2, num_badones]);
end
errors = sum((xd - distort(x, k)) .^ 2);
if numel(errors)==424*512
figure;
imagesc(reshape(errors,[424 512]));
axis equal; axis tight; axis off;
colorbar
end
if numel(errors)==1080*1920
figure;
imagesc(reshape(errors,[1080 1920]));
axis equal; axis tight; axis off;
colorbar
end
end
function [x] = undistort_oulu(xd, k)
%
%[x] = comp_distortion_oulu(xd,k)
%
%Compensates for radial and tangential distortion. Model From Oulu university.
%For more informatino about the distortion model, check the forward projection mapping function:
%project_points.m
%
%INPUT: xd: distorted (normalized) point coordinates in the image plane (2xN matrix)
% k: Distortion coefficients (radial and tangential) (5x1 vector)
%
%OUTPUT: x: undistorted (normalized) point coordinates in the image plane (2xN matrix)
%
%Method: Iterative method for compensation.
%
%NOTE: This compensation has to be done after the subtraction
% of the principal point, and division by the focal length.
if length(k) == 1,
[x] = comp_distortion(xd,k);
else
k1 = k(1);
k2 = k(2);
k3 = k(5);
p1 = k(3);
p2 = k(4);
x = xd; % initial guess
for kk=1:20,
r_2 = sum(x.^2);
k_radial = 1 + k1 * r_2 + k2 * r_2.^2 + k3 * r_2.^3;
delta_x = [2*p1*x(1,:).*x(2,:) + p2*(r_2 + 2*x(1,:).^2);
p1 * (r_2 + 2*x(2,:).^2)+2*p2*x(1,:).*x(2,:)];
x = (xd - delta_x)./(ones(2,1)*k_radial);
end;
end;
end
function [F, J] = undistort_J(p, xd, k)
F = distort(p, k) - xd;
if nargout > 1
J = zeros(2, 2);
x = p(1);
y = p(2);
k1 = k(1);
k2 = k(2);
k3 = k(5);
p1 = k(3);
p2 = k(4);
J(1, 1) = 1+2.*p1.*y+k1.*(x.^2+y.^2)+k2.*(x.^2+y.^2).^2+k3.*(x.^2+y.^2).^3+ ...
p2.*(4.*x+4.*x.*(x.^2+y.^2))+x.*(2.*k1.*x+4.*k2.*x.*(x.^2+y.^2)+ ...
6.*k3.*x.*(x.^2+y.^2).^2);
J(1, 2) = 2.*p1.*x+4.*p2.*y.*(x.^2+y.^2)+x.*(2.*k1.*y+4.*k2.*y.*(x.^2+y.^2)+ ...
6.*k3.*y.*(x.^2+y.^2).^2);
J(2, 1) = 2.*p1.*x+2.*p2.*y+y.*(2.*k1.*x+4.*k2.*x.*(x.^2+y.^2)+6.*k3.*x.*( ...
x.^2+y.^2).^2);
J(2, 2) = 1+2.*p2.*x+6.*p1.*y+k1.*(x.^2+y.^2)+k2.*(x.^2+y.^2).^2+k3.*(x.^2+ ...
y.^2).^3+y.*(2.*k1.*y+4.*k2.*y.*(x.^2+y.^2)+6.*k3.*y.*(x.^2+y.^2) ...
.^2);
end
end
function [F, J] = undistort_Jv(p, xd, k)
%tic
num_points = size(xd, 2);
F = distort(p, k) - xd;
if ~isvector(F)
F = reshape(F, [numel(F), 1]);
end
if nargout > 1
Jv = zeros(1, num_points * 4);
k1 = k(1);
k2 = k(2);
k3 = k(5);
p1 = k(3);
p2 = k(4);
x = p(1:2:end);
y = p(2:2:end);
r2 = x .* x + y .* y;
Jv(1:4:end) = 1+2.*p1.*y+k1.*r2+k2.*r2.^2+k3.*r2.^3+ ...
p2.*(4.*x+4.*x.*r2)+x.*(2.*k1.*x+4.*k2.*x.*r2+ ...
6.*k3.*x.*r2.^2);
Jv(2:4:end) = 2.*p1.*x+4.*p2.*y.*r2+x.*(2.*k1.*y+4.*k2.*y.*r2+ ...
6.*k3.*y.*r2.^2);
Jv(3:4:end) = 2.*p1.*x+2.*p2.*y+y.*(2.*k1.*x+4.*k2.*x.*r2+6.*k3.*x.*( ...
r2).^2);
Jv(4:4:end) = 1+2.*p2.*x+6.*p1.*y+k1.*r2+k2.*r2.^2+k3.*(x.^2+ ...
y.^2).^3+y.*(2.*k1.*y+4.*k2.*y.*r2+6.*k3.*y.*r2 ...
.^2);
indexes = 1:(num_points * 2);
is = zeros(1, num_points * 4);
is(1:2:end) = indexes;
is(2:2:end) = indexes;
js = reshape(indexes, [2, num_points]);
js = [js; js];
js = reshape(js, [1, numel(js)]);
J = sparse(is, js, Jv, num_points * 2, num_points * 2, num_points * 4);
end
%fprintf('Undistort_Jv took %f seconds\n', toc);
end
|
github
|
jianxiongxiao/ProfXkit-master
|
points2normals.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/points2normals.m
| 2,551 |
utf_8
|
cffcb4a1ea7aa3af3e895f74f76491fa
|
function normals = points2normals(points)
% estimating a normal vector based on nearby 100 points
% points is 3 * n matrix for n points
if size(points,2)==3 && size(points,1)~=3
points = points';
end
normals = lsqnormest(points, 50);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% functions from http://www.mathworks.com/matlabcentral/fileexchange/27804-iterative-closest-point
% Least squares normal estimation from point clouds using PCA
%
% H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle.
% Surface reconstruction from unorganized points.
% In Proceedings of ACM Siggraph, pages 71:78, 1992.
%
% p should be a matrix containing the horizontally concatenated column
% vectors with points. k is a scalar indicating how many neighbors the
% normal estimation is based upon.
%
% Note that for large point sets, the function performs significantly
% faster if Statistics Toolbox >= v. 7.3 is installed.
%
% Jakob Wilm 2010
function n = lsqnormest(p, k)
m = size(p,2);
n = zeros(3,m);
v = ver('stats');
if str2double(v.Version) >= 7.5
neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1));
else
neighbors = k_nearest_neighbors(p, p, k+1);
end
for i = 1:m
x = p(:,neighbors(2:end, i));
p_bar = 1/k * sum(x,2);
P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P
%P = 2*cov(x);
[V,D] = eig(P);
[~, idx] = min(diag(D)); % choses the smallest eigenvalue
n(:,i) = V(:,idx); % returns the corresponding eigenvector
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Program to find the k - nearest neighbors (kNN) within a set of points.
% Distance metric used: Euclidean distance
%
% Note that this function makes repetitive use of min(), which seems to be
% more efficient than sort() for k < 30.
function [neighborIds,neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k)
numDataPoints = size(dataMatrix,2);
numQueryPoints = size(queryMatrix,2);
neighborIds = zeros(k,numQueryPoints);
neighborDistances = zeros(k,numQueryPoints);
D = size(dataMatrix, 1); %dimensionality of points
for i=1:numQueryPoints
d=zeros(1,numDataPoints);
for t=1:D % this is to avoid slow repmat()
d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2;
end
for j=1:k
[s,t] = min(d);
neighborIds(j,i)=t;
neighborDistances(j,i)=sqrt(s);
d(t) = NaN; % remove found number from d
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
transformPointCloud.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/transformPointCloud.m
| 130 |
utf_8
|
ebf18e96a2a3d9ca20da267e9d345dcd
|
function XYZtransform = transformPointCloud(XYZ,Rt)
XYZtransform = Rt(1:3,1:3) * XYZ + repmat(Rt(1:3,4),1,size(XYZ,2));
end
|
github
|
jianxiongxiao/ProfXkit-master
|
icp.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/icp.m
| 19,013 |
utf_8
|
08b226a4c6ddc02c96cb999b6f8dc8fe
|
function [TR, TT, ER, maxD, t] = icp(q,p,varargin)
% this is modified version of the original version
%
% Perform the Iterative Closest Point algorithm on three dimensional point
% clouds.
%
% [TR, TT] = icp(q,p) returns the rotation matrix TR and translation
% vector TT that minimizes the distances from (TR * p + TT) to q.
% p is a 3xm matrix and q is a 3xn matrix.
%
% [TR, TT] = icp(q,p,k) forces the algorithm to make k iterations
% exactly. The default is 10 iterations.
%
% [TR, TT, ER] = icp(q,p,k) also returns the RMS of errors for k
% iterations in a (k+1)x1 vector. ER(0) is the initial error.
%
% [TR, TT, ER, t] = icp(q,p,k) also returns the calculation times per
% iteration in a (k+1)x1 vector. t(0) is the time consumed for preprocessing.
%
% Additional settings may be provided in a parameter list:
%
% Boundary
% {[]} | 1x? vector
% If EdgeRejection is set, a vector can be provided that indexes into
% q and specifies which points of q are on the boundary.
%
% EdgeRejection
% {false} | true
% If EdgeRejection is true, point matches to edge vertices of q are
% ignored. Requires that boundary points of q are specified using
% Boundary or that a triangulation matrix for q is provided.
%
% Extrapolation
% {false} | true
% If Extrapolation is true, the iteration direction will be evaluated
% and extrapolated if possible using the method outlined by
% Besl and McKay 1992.
%
% Matching
% bruteForce | Delaunay | {kDtree}
% Specifies how point matching should be done.
% bruteForce is usually the slowest and kDtree is the fastest.
% Note that the kDtree option is depends on the Statistics Toolbox
% v. 7.3 or higher.
%
% Minimize
% {point} | plane | lmaPoint
% Defines whether point to point or point to plane minimization
% should be performed. point is based on the SVD approach and is
% usually the fastest. plane will often yield higher accuracy. It
% uses linearized angles and requires surface normals for all points
% in q. Calculation of surface normals requires substantial pre
% proccessing.
% The option lmaPoint does point to point minimization using the non
% linear least squares Levenberg Marquardt algorithm. Results are
% generally the same as in points, but computation time may differ.
%
% Normals
% {[]} | n x 3 matrix
% A matrix of normals for the n points in q might be provided.
% Normals of q are used for point to plane minimization.
% Else normals will be found through a PCA of the 4 nearest
% neighbors.
%
% ReturnAll
% {false} | true
% Determines whether R and T should be returned for all iterations
% or only for the last one. If this option is set to true, R will be
% a 3x3x(k+1) matrix and T will be a 3x1x(k+1) matrix.
%
% Triangulation
% {[]} | ? x 3 matrix
% A triangulation matrix for the points in q can be provided,
% enabling EdgeRejection. The elements should index into q, defining
% point triples that act together as triangles.
%
% Verbose
% {false} | true
% Enables extrapolation output in the Command Window.
%
% Weight
% {@(match)ones(1,m)} | Function handle
% For point or plane minimization, a function handle to a weighting
% function can be provided. The weighting function will be called
% with one argument, a 1xm vector that specifies point pairs by
% indexing into q. The weighting function should return a 1xm vector
% of weights for every point pair.
%
% WorstRejection
% {0} | scalar in ]0; 1[
% Reject a given percentage of the worst point pairs, based on their
% Euclidean distance.
%
% Martin Kjer and Jakob Wilm, Technical University of Denmark, 2012
% Use the inputParser class to validate input arguments.
inp = inputParser;
inp.addRequired('q', @(x)isreal(x) && size(x,1) == 3);
inp.addRequired('p', @(x)isreal(x) && size(x,1) == 3);
inp.addOptional('iter', 10, @(x)x > 0 && x < 10^5);
inp.addParamValue('Boundary', [], @(x)size(x,1) == 1);
inp.addParamValue('EdgeRejection', false, @(x)islogical(x));
inp.addParamValue('Extrapolation', false, @(x)islogical(x));
validMatching = {'bruteForce','Delaunay','kDtree'};
inp.addParamValue('Matching', 'kDtree', @(x)any(strcmpi(x,validMatching)));
validMinimize = {'point','plane','lmapoint'};
inp.addParamValue('Minimize', 'point', @(x)any(strcmpi(x,validMinimize)));
inp.addParamValue('Normals', [], @(x)isreal(x) && size(x,1) == 3);
inp.addParamValue('NormalsData', [], @(x)isreal(x) && size(x,1) == 3);
inp.addParamValue('ReturnAll', false, @(x)islogical(x));
inp.addParamValue('Triangulation', [], @(x)isreal(x) && size(x,2) == 3);
inp.addParamValue('Verbose', false, @(x)islogical(x));
inp.addParamValue('Weight', @(x)ones(1,length(x)), @(x)isa(x,'function_handle'));
inp.addParamValue('WorstRejection', 0, @(x)isscalar(x) && x > 0 && x < 1);
inp.addParamValue('SmartRejection', 0, @(x)isscalar(x) && x > 0);
inp.parse(q,p,varargin{:});
arg = inp.Results;
clear('inp');
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Actual implementation
% Allocate vector for RMS of errors in every iteration.
t = zeros(arg.iter+1,1);
% Start timer
tic;
Np = size(p,2);
% Transformed data point cloud
pt = p;
% Allocate vector for RMS of errors in every iteration.
ER = zeros(arg.iter+1,1);
maxD = zeros(arg.iter,1);
% Initialize temporary transform vector and matrix.
T = zeros(3,1);
R = eye(3,3);
% Initialize total transform vector(s) and rotation matric(es).
TT = zeros(3,1, arg.iter+1);
TR = repmat(eye(3,3), [1,1, arg.iter+1]);
% If Minimize == 'plane', normals are needed
if (strcmp(arg.Minimize, 'plane') && isempty(arg.Normals))
arg.Normals = lsqnormest(q,4);
end
% If Matching == 'Delaunay', a triangulation is needed
if strcmp(arg.Matching, 'Delaunay')
DT = DelaunayTri(transpose(q));
end
% If Matching == 'kDtree', a kD tree should be built (req. Stat. TB >= 7.3)
if strcmp(arg.Matching, 'kDtree')
kdOBJ = KDTreeSearcher(transpose(q));
end
% If edge vertices should be rejected, find edge vertices
if arg.EdgeRejection
if isempty(arg.Boundary)
bdr = find_bound(q, arg.Triangulation);
else
bdr = arg.Boundary;
end
end
if arg.Extrapolation
% Initialize total transform vector (quaternion ; translation vec.)
qq = [ones(1,arg.iter+1);zeros(6,arg.iter+1)];
% Allocate vector for direction change and change angle.
dq = zeros(7,arg.iter+1);
theta = zeros(1,arg.iter+1);
end
t(1) = toc;
% Go into main iteration loop
for k=1:arg.iter
% Do matching
switch arg.Matching
case 'bruteForce'
[match mindist] = match_bruteForce(q,pt);
case 'Delaunay'
[match mindist] = match_Delaunay(q,pt,DT);
case 'kDtree'
[match mindist] = match_kDtree(q,pt,kdOBJ);
end
% If matches to edge vertices should be rejected
if arg.EdgeRejection
p_idx = not(ismember(match, bdr));
q_idx = match(p_idx);
mindist = mindist(p_idx);
else
p_idx = true(1, Np);
q_idx = match;
end
if k==1 && arg.SmartRejection
arg.WorstRejection = sum(mindist > (median(mindist)* arg.SmartRejection))/ length(mindist);
fprintf('ICP: Median=%f Threshold=%f WorstRejection=%f\n', median(mindist),median(mindist)* arg.SmartRejection,arg.WorstRejection);
% vis
%{
figure
hist(mindist,0:0.01/10:max(mindist)); hold on;
plot(median(mindist),0,'g*');
plot(median(mindist)* arg.SmartRejection,0,'r*');
%}
end
% If worst matches should be rejected
if arg.WorstRejection
edge = round((1-arg.WorstRejection)*sum(p_idx));
pairs = find(p_idx);
[~, idx] = sort(mindist);
p_idx(pairs(idx(edge:end))) = false;
q_idx = match(p_idx);
mindist = mindist(p_idx);
end
maxD(k) = max(mindist);
if k == 1
ER(k) = sqrt(sum(mindist.^2)/length(mindist));
end
switch arg.Minimize
case 'point'
% Determine weight vector
weights = arg.Weight(match);
[R,T] = eq_point(q(:,q_idx),pt(:,p_idx), weights(p_idx));
case 'plane'
weights = arg.Weight(match);
[R,T] = eq_plane(q(:,q_idx),pt(:,p_idx),arg.Normals(:,q_idx),weights(p_idx));
case 'lmaPoint'
[R,T] = eq_lmaPoint(q(:,q_idx),pt(:,p_idx));
end
% Add to the total transformation
TR(:,:,k+1) = R*TR(:,:,k);
TT(:,:,k+1) = R*TT(:,:,k)+T;
% Apply last transformation
pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np);
% Root mean of objective function
ER(k+1) = rms_error(q(:,q_idx), pt(:,p_idx));
% If Extrapolation, we might be able to move quicker
if arg.Extrapolation
qq(:,k+1) = [rmat2quat(TR(:,:,k+1));TT(:,:,k+1)];
dq(:,k+1) = qq(:,k+1) - qq(:,k);
theta(k+1) = (180/pi)*acos(dot(dq(:,k),dq(:,k+1))/(norm(dq(:,k))*norm(dq(:,k+1))));
if arg.Verbose
disp(['Direction change ' num2str(theta(k+1)) ' degree in iteration ' num2str(k)]);
end
if k>2 && theta(k+1) < 10 && theta(k) < 10
d = [ER(k+1), ER(k), ER(k-1)];
v = [0, -norm(dq(:,k+1)), -norm(dq(:,k))-norm(dq(:,k+1))];
vmax = 25 * norm(dq(:,k+1));
dv = extrapolate(v,d,vmax);
if dv ~= 0
q_mark = qq(:,k+1) + dv * dq(:,k+1)/norm(dq(:,k+1));
q_mark(1:4) = q_mark(1:4)/norm(q_mark(1:4));
qq(:,k+1) = q_mark;
TR(:,:,k+1) = quat2rmat(qq(1:4,k+1));
TT(:,:,k+1) = qq(5:7,k+1);
% Reapply total transformation
pt = TR(:,:,k+1) * p + repmat(TT(:,:,k+1), 1, Np);
% Recalculate root mean of objective function
% Note this is costly and only for fun!
switch arg.Matching
case 'bruteForce'
[~, mindist] = match_bruteForce(q,pt);
case 'Delaunay'
[~, mindist] = match_Delaunay(q,pt,DT);
case 'kDtree'
[~, mindist] = match_kDtree(q,pt,kdOBJ);
end
ER(k+1) = sqrt(sum(mindist.^2)/length(mindist));
end
end
end
t(k+1) = toc;
end
if not(arg.ReturnAll)
TR = TR(:,:,end);
TT = TT(:,:,end);
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [match mindist] = match_bruteForce(q, p)
m = size(p,2);
n = size(q,2);
match = zeros(1,m);
mindist = zeros(1,m);
for ki=1:m
d=zeros(1,n);
for ti=1:3
d=d+(q(ti,:)-p(ti,ki)).^2;
end
[mindist(ki),match(ki)]=min(d);
end
mindist = sqrt(mindist);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [match mindist] = match_Delaunay(q, p, DT)
match = transpose(nearestNeighbor(DT, transpose(p)));
mindist = sqrt(sum((p-q(:,match)).^2,1));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [match mindist] = match_kDtree(~, p, kdOBJ)
[match mindist] = knnsearch(kdOBJ,transpose(p));
match = transpose(match);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = eq_point(q,p,weights)
m = size(p,2);
n = size(q,2);
% normalize weights
weights = weights ./ sum(weights);
% find data centroid and deviations from centroid
q_bar = q * transpose(weights);
q_mark = q - repmat(q_bar, 1, n);
% Apply weights
q_mark = q_mark .* repmat(weights, 3, 1);
% find data centroid and deviations from centroid
p_bar = p * transpose(weights);
p_mark = p - repmat(p_bar, 1, m);
% Apply weights
%p_mark = p_mark .* repmat(weights, 3, 1);
N = p_mark*transpose(q_mark); % taking points of q in matched order
[U,~,V] = svd(N); % singular value decomposition
R = V*diag([1 1 det(U*V')])*transpose(U);
T = q_bar - R*p_bar;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = eq_plane(q,p,n,weights)
n = n .* repmat(weights,3,1);
c = cross(p,n);
cn = vertcat(c,n);
C = cn*transpose(cn);
b = - [sum(sum((p-q).*repmat(cn(1,:),3,1).*n));
sum(sum((p-q).*repmat(cn(2,:),3,1).*n));
sum(sum((p-q).*repmat(cn(3,:),3,1).*n));
sum(sum((p-q).*repmat(cn(4,:),3,1).*n));
sum(sum((p-q).*repmat(cn(5,:),3,1).*n));
sum(sum((p-q).*repmat(cn(6,:),3,1).*n))];
X = C\b;
cx = cos(X(1)); cy = cos(X(2)); cz = cos(X(3));
sx = sin(X(1)); sy = sin(X(2)); sz = sin(X(3));
R = [cy*cz cz*sx*sy-cx*sz cx*cz*sy+sx*sz;
cy*sz cx*cz+sx*sy*sz cx*sy*sz-cz*sx;
-sy cy*sx cx*cy];
T = X(4:6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [R,T] = eq_lmaPoint(q,p)
Rx = @(a)[1 0 0;
0 cos(a) -sin(a);
0 sin(a) cos(a)];
Ry = @(b)[cos(b) 0 sin(b);
0 1 0;
-sin(b) 0 cos(b)];
Rz = @(g)[cos(g) -sin(g) 0;
sin(g) cos(g) 0;
0 0 1];
Rot = @(x)Rx(x(1))*Ry(x(2))*Rz(x(3));
myfun = @(x,xdata)Rot(x(1:3))*xdata+repmat(x(4:6),1,length(xdata));
options = optimset('Algorithm', 'levenberg-marquardt');
x = lsqcurvefit(myfun, zeros(6,1), p, q, [], [], options);
R = Rot(x(1:3));
T = x(4:6);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Extrapolation in quaternion space. Details are found in:
%
% Besl, P., & McKay, N. (1992). A method for registration of 3-D shapes.
% IEEE Transactions on pattern analysis and machine intelligence, 239?256.
function [dv] = extrapolate(v,d,vmax)
p1 = polyfit(v,d,1); % linear fit
p2 = polyfit(v,d,2); % parabolic fit
v1 = -p1(2)/p1(1); % linear zero crossing
v2 = -p2(2)/(2*p2(1)); % polynomial top point
if issorted([0 v2 v1 vmax]) || issorted([0 v2 vmax v1])
disp('Parabolic update!');
dv = v2;
elseif issorted([0 v1 v2 vmax]) || issorted([0 v1 vmax v2])...
|| (v2 < 0 && issorted([0 v1 vmax]))
disp('Line based update!');
dv = v1;
elseif v1 > vmax && v2 > vmax
disp('Maximum update!');
dv = vmax;
else
disp('No extrapolation!');
dv = 0;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Determine the RMS error between two point equally sized point clouds with
% point correspondance.
% ER = rms_error(p1,p2) where p1 and p2 are 3xn matrices.
function ER = rms_error(p1,p2)
dsq = sum(power(p1 - p2, 2),1);
ER = sqrt(mean(dsq));
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Converts (orthogonal) rotation matrices R to (unit) quaternion
% representations
%
% Input: A 3x3xn matrix of rotation matrices
% Output: A 4xn matrix of n corresponding quaternions
%
% http://en.wikipedia.org/wiki/Rotation_matrix#Quaternion
function quaternion = rmat2quat(R)
Qxx = R(1,1,:);
Qxy = R(1,2,:);
Qxz = R(1,3,:);
Qyx = R(2,1,:);
Qyy = R(2,2,:);
Qyz = R(2,3,:);
Qzx = R(3,1,:);
Qzy = R(3,2,:);
Qzz = R(3,3,:);
w = 0.5 * sqrt(1+Qxx+Qyy+Qzz);
x = 0.5 * sign(Qzy-Qyz) .* sqrt(1+Qxx-Qyy-Qzz);
y = 0.5 * sign(Qxz-Qzx) .* sqrt(1-Qxx+Qyy-Qzz);
z = 0.5 * sign(Qyx-Qxy) .* sqrt(1-Qxx-Qyy+Qzz);
quaternion = reshape([w;x;y;z],4,[]);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Converts (unit) quaternion representations to (orthogonal) rotation matrices R
%
% Input: A 4xn matrix of n quaternions
% Output: A 3x3xn matrix of corresponding rotation matrices
%
% http://en.wikipedia.org/wiki/Quaternions_and_spatial_rotation#From_a_quaternion_to_an_orthogonal_matrix
function R = quat2rmat(quaternion)
q0(1,1,:) = quaternion(1,:);
qx(1,1,:) = quaternion(2,:);
qy(1,1,:) = quaternion(3,:);
qz(1,1,:) = quaternion(4,:);
R = [q0.^2+qx.^2-qy.^2-qz.^2 2*qx.*qy-2*q0.*qz 2*qx.*qz+2*q0.*qy;
2*qx.*qy+2*q0.*qz q0.^2-qx.^2+qy.^2-qz.^2 2*qy.*qz-2*q0.*qx;
2*qx.*qz-2*q0.*qy 2*qy.*qz+2*q0.*qx q0.^2-qx.^2-qy.^2+qz.^2];
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Least squares normal estimation from point clouds using PCA
%
% H. Hoppe, T. DeRose, T. Duchamp, J. McDonald, and W. Stuetzle.
% Surface reconstruction from unorganized points.
% In Proceedings of ACM Siggraph, pages 71:78, 1992.
%
% p should be a matrix containing the horizontally concatenated column
% vectors with points. k is a scalar indicating how many neighbors the
% normal estimation is based upon.
%
% Note that for large point sets, the function performs significantly
% faster if Statistics Toolbox >= v. 7.3 is installed.
%
% Jakob Wilm 2010
function n = lsqnormest(p, k)
m = size(p,2);
n = zeros(3,m);
v = ver('stats');
if str2double(v.Version) >= 7.5
neighbors = transpose(knnsearch(transpose(p), transpose(p), 'k', k+1));
else
neighbors = k_nearest_neighbors(p, p, k+1);
end
for i = 1:m
x = p(:,neighbors(2:end, i));
p_bar = 1/k * sum(x,2);
P = (x - repmat(p_bar,1,k)) * transpose(x - repmat(p_bar,1,k)); %spd matrix P
%P = 2*cov(x);
[V,D] = eig(P);
[~, idx] = min(diag(D)); % choses the smallest eigenvalue
n(:,i) = V(:,idx); % returns the corresponding eigenvector
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Program to find the k - nearest neighbors (kNN) within a set of points.
% Distance metric used: Euclidean distance
%
% Note that this function makes repetitive use of min(), which seems to be
% more efficient than sort() for k < 30.
function [neighborIds neighborDistances] = k_nearest_neighbors(dataMatrix, queryMatrix, k)
numDataPoints = size(dataMatrix,2);
numQueryPoints = size(queryMatrix,2);
neighborIds = zeros(k,numQueryPoints);
neighborDistances = zeros(k,numQueryPoints);
D = size(dataMatrix, 1); %dimensionality of points
for i=1:numQueryPoints
d=zeros(1,numDataPoints);
for t=1:D % this is to avoid slow repmat()
d=d+(dataMatrix(t,:)-queryMatrix(t,i)).^2;
end
for j=1:k
[s,t] = min(d);
neighborIds(j,i)=t;
neighborDistances(j,i)=sqrt(s);
d(t) = NaN; % remove found number from d
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Boundary point determination. Given a set of 3D points and a
% corresponding triangle representation, returns those point indices that
% define the border/edge of the surface.
function bound = find_bound(pts, poly)
%Correcting polygon indices and converting datatype
poly = double(poly);
pts = double(pts);
%Calculating freeboundary points:
TR = TriRep(poly, pts(1,:)', pts(2,:)', pts(3,:)');
FF = freeBoundary(TR);
%Output
bound = FF(:,1);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
|
github
|
jianxiongxiao/ProfXkit-master
|
ransacfitRt.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/ransacfitRt.m
| 2,888 |
utf_8
|
738399412f806f9855724ff192fe4494
|
% Usage: [Rt, inliers] = ransacfitRt(x1, x2, t)
%
% Arguments:
% x1 - 3xN set of 3D points.
% x2 - 3xN set of 3D points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% Rt - The 3x4 transformation matrix such that x1 = R*x2 + t.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC
% Author: Jianxiong Xiao
function [Rt, inliers] = ransacfitRt(x, t, feedback)
s = 3; % Number of points needed to fit a Rt matrix.
if size(x,2)==s
inliers = 1:s;
Rt = estimateRt(x);
return;
end
fittingfn = @estimateRt;
distfn = @euc3Ddist;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[Rt, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback);
if length(inliers)<s
Rt = [eye(3) zeros(3,1)];
inliers = [];
return;
end
% Now do a final least squares fit on the data points considered to
% be inliers.
Rt = estimateRt(x(:,inliers));
end
%--------------------------------------------------------------------------
% Note that this code allows for Rt being a cell array of matrices of
% which we have to pick the best one.
function [bestInliers, bestRt] = euc3Ddist(Rt, x, t)
if iscell(Rt) % We have several solutions each of which must be tested
nRt = length(Rt); % Number of solutions to test
bestRt = Rt{1}; % Initial allocation of best solution
ninliers = 0; % Number of inliers
for k = 1:nRt
d = sum((x(1:3,:) - (Rt{k}(:,1:3)*x(4:6,:)+repmat(Rt{k}(:,4),1,size(x,2)))).^2,1).^0.5;
inliers = find(abs(d) < t); % Indices of inlying points
if length(inliers) > ninliers % Record best solution
ninliers = length(inliers);
bestRt = Rt{k};
bestInliers = inliers;
end
end
else % We just have one solution
d = sum((x(1:3,:) - (Rt(:,1:3)*x(4:6,:)+repmat(Rt(:,4),1,size(x,2)))).^2,1).^0.5;
bestInliers = find(abs(d) < t); % Indices of inlying points
bestRt = Rt; % Copy Rt directly to bestRt
end
end
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a fundamental matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
show.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/show.m
| 4,944 |
utf_8
|
e2225be3d05b416c72fc6f1acbde02d0
|
% SHOW - Displays an image with the right size and colors and with a title.
%
% Usage:
% h = show(im)
% h = show(im, figNo)
% h = show(im, title)
% h = show(im, figNo, title)
%
% Arguments: im - Either a 2 or 3D array of pixel values or the name
% of an image file;
% figNo - Optional figure number to display image in. If
% figNo is 0 the current figure or subplot is
% assumed.
% title - Optional string specifying figure title
%
% Returns: h - Handle to the figure. This allows you to set
% additional figure attributes if desired.
%
% The function displays the image, automatically setting the colour map to
% grey if it is a 2D image, or leaving it as colour otherwise, and setting
% the axes to be 'equal'. The image is also displayed as 'TrueSize', that
% is, pixels on the screen match pixels in the image (if it is possible
% to fit it on the screen, otherwise MATLAB rescales it to fit).
%
% Unless you are doing a subplot (figNo==0) the window is sized to match
% the image, leaving no border, and hence saving desktop real estate.
%
% If figNo is omitted a new figure window is created for the image. If
% figNo is supplied, and the figure exists, the existing window is reused to
% display the image, otherwise a new window is created. If figNo is 0 the
% current figure or subplot is assumed.
%
% See also: SHOWSURF
% Copyright (c) 2000-2009 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% October 2000 Original version
% March 2003 Mods to alow figure name in window bar and allow for subplots.
% April 2007 Proper recording and restoring of MATLAB warning state.
% September 2008 Octave compatible
% May 2009 Reworked argument handling logic for extra flexibility
function h = show(im, param2, param3)
Octave = exist('OCTAVE_VERSION') ~= 0; % Are we running under Octave?
if ~Octave
s = warning('query','all'); % Record existing warning state.
warning('off'); % Turn off warnings that might arise if image
% has to be rescaled to fit on screen
end
% Check case where im is an image filename rather than image data
if ~isnumeric(im) & ~islogical(im)
Title = im; % Default title is file name
im = imread(im);
else
Title = inputname(1); % Default title is variable name of image data
end
figNo = -1; % Default value indicating create new figure
% If two arguments check type of 2nd argument to see if it is the title or
% figure number that has been supplied
if nargin == 2
if strcmp(class(param2),'char')
Title = param2;
elseif isnumeric(param2) && length(param2) == 1
figNo = param2;
else
error('2nd argument must be a figure number or title');
end
elseif nargin == 3
figNo = param2;
Title = param3;
if ~strcmp(class(Title),'char')
error('Title must be a string');
end
if ~isnumeric(param2) || length(param2) ~= 1
error('Figure number must be an integer');
end
end
if figNo > 0 % We have a valid figure number
figure(figNo); % Reuse or create a figure window with this number
if ~Octave
subplot('position',[0 0 1 1]); % Use the whole window
end
elseif figNo == -1
figNo = figure; % Create new figure window
if ~Octave
subplot('position',[0 0 1 1]); % Use the whole window
end
end
if ndims(im) == 2 % Display as greyscale
imagesc(im);
colormap('gray');
else
imshow(im); % Display as RGB
end
if figNo == 0 % Assume we are trying to do a subplot
figNo = gcf; % Get the current figure number
axis('image'); axis('off');
title(Title); % Use a title rather than rename the figure
else
axis('image'); axis('off');
set(figNo,'name', [' ' Title])
if ~Octave
truesize(figNo);
end
end
if nargout == 1
h = figNo;
end
if ~Octave
warning(s); % Restore warnings
end
|
github
|
jianxiongxiao/ProfXkit-master
|
nonmaxsuppts.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/nonmaxsuppts.m
| 5,086 |
utf_8
|
6d711b2f28fd3ea2543d59f3e89139b7
|
% NONMAXSUPPTS - Non-maximal suppression for features/corners
%
% Non maxima suppression and thresholding for points generated by a feature
% or corner detector.
%
% Usage: [r,c] = nonmaxsuppts(cim, radius, thresh, im)
% /
% optional
%
% [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)
%
% Arguments:
% cim - corner strength image.
% radius - radius of region considered in non-maximal
% suppression. Typical values to use might
% be 1-3 pixels.
% thresh - threshold.
% im - optional image data. If this is supplied the
% thresholded corners are overlayed on this
% image. This can be useful for parameter tuning.
% Returns:
% r - row coordinates of corner points (integer valued).
% c - column coordinates of corner points.
% rsubp - If four return values are requested sub-pixel
% csubp - localization of feature points is attempted and
% returned as an additional set of floating point
% coords. Note that you may still want to use the integer
% valued coords to specify centres of correlation windows
% for feature matching.
%
% Copyright (c) 2003-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% September 2003 Original version
% August 2005 Subpixel localization and Octave compatibility
% January 2010 Fix for completely horizontal and vertical lines (by Thomas Stehle,
% RWTH Aachen University)
% January 2011 Warning given if no maxima found
function [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)
subPixel = nargout == 4; % We want sub-pixel locations
[rows,cols] = size(cim);
% Extract local maxima by performing a grey scale morphological
% dilation and then finding points in the corner strength image that
% match the dilated image and are also greater than the threshold.
sze = 2*radius+1; % Size of dilation mask.
mx = ordfilt2(cim,sze^2,ones(sze)); % Grey-scale dilate.
% Make mask to exclude points within radius of the image boundary.
bordermask = zeros(size(cim));
bordermask(radius+1:end-radius, radius+1:end-radius) = 1;
% Find maxima, threshold, and apply bordermask
cimmx = (cim==mx) & (cim>thresh) & bordermask;
[r,c] = find(cimmx); % Find row,col coords.
if subPixel % Compute local maxima to sub pixel accuracy
if ~isempty(r) % ...if we have some ponts to work with
ind = sub2ind(size(cim),r,c); % 1D indices of feature points
w = 1; % Width that we look out on each side of the feature
% point to fit a local parabola
% Indices of points above, below, left and right of feature point
indrminus1 = max(ind-w,1);
indrplus1 = min(ind+w,rows*cols);
indcminus1 = max(ind-w*rows,1);
indcplus1 = min(ind+w*rows,rows*cols);
% Solve for quadratic down rows
rowshift = zeros(size(ind));
cy = cim(ind);
ay = (cim(indrminus1) + cim(indrplus1))/2 - cy;
by = ay + cy - cim(indrminus1);
rowshift(ay ~= 0) = -w*by(ay ~= 0)./(2*ay(ay ~= 0)); % Maxima of quadradic
rowshift(ay == 0) = 0;
% Solve for quadratic across columns
colshift = zeros(size(ind));
cx = cim(ind);
ax = (cim(indcminus1) + cim(indcplus1))/2 - cx;
bx = ax + cx - cim(indcminus1);
colshift(ax ~= 0) = -w*bx(ax ~= 0)./(2*ax(ax ~= 0)); % Maxima of quadradic
colshift(ax == 0) = 0;
rsubp = r+rowshift; % Add subpixel corrections to original row
csubp = c+colshift; % and column coords.
else
rsubp = []; csubp = [];
end
end
if nargin==4 & ~isempty(r) % Overlay corners on supplied image.
figure(1), imshow(im,[]), hold on
if subPixel
plot(csubp,rsubp,'r+'), title('corners detected');
else
plot(c,r,'r+'), title('corners detected');
end
hold off
end
if isempty(r)
% fprintf('No maxima above threshold found\n');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
ransacfitfundmatrix.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/ransacfitfundmatrix.m
| 5,544 |
utf_8
|
b87d72c56902f27c573b6c545f6754ab
|
% RANSACFITFUNDMATRIX - fits fundamental matrix using RANSAC
%
% Usage: [F, inliers] = ransacfitfundmatrix(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% F - The 3x3 fundamental matrix such that x2'Fx1 = 0.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: RANSAC, FUNDMATRIX
% Copyright (c) 2004-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2004 Original version
% August 2005 Distance error function changed to match changes in RANSAC
function [F, inliers] = ransacfitfundmatrix(x1, x2, t, feedback)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
if nargin == 3
feedback = 0;
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'fundmatrix' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 8; % Number of points needed to fit a fundamental matrix. Note that
% only 7 are needed but the function 'fundmatrix' only
% implements the 8-point solution.
fittingfn = @fundmatrix;
distfn = @funddist;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[F, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t, feedback);
% Now do a final least squares fit on the data points considered to
% be inliers.
F = fundmatrix(x1(:,inliers), x2(:,inliers));
% Denormalise
F = T2'*F*T1;
%--------------------------------------------------------------------------
% Function to evaluate the first order approximation of the geometric error
% (Sampson distance) of the fit of a fundamental matrix with respect to a
% set of matched points as needed by RANSAC. See: Hartley and Zisserman,
% 'Multiple View Geometry in Computer Vision', page 270.
%
% Note that this code allows for F being a cell array of fundamental matrices of
% which we have to pick the best one. (A 7 point solution can return up to 3
% solutions)
function [bestInliers, bestF] = funddist(F, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
if iscell(F) % We have several solutions each of which must be tested
nF = length(F); % Number of solutions to test
bestF = F{1}; % Initial allocation of best solution
ninliers = 0; % Number of inliers
for k = 1:nF
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F{k}*x1(:,n);
end
Fx1 = F{k}*x1;
Ftx2 = F{k}'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
inliers = find(abs(d) < t); % Indices of inlying points
if length(inliers) > ninliers % Record best solution
ninliers = length(inliers);
bestF = F{k};
bestInliers = inliers;
end
end
else % We just have one solution
x2tFx1 = zeros(1,length(x1));
for n = 1:length(x1)
x2tFx1(n) = x2(:,n)'*F*x1(:,n);
end
Fx1 = F*x1;
Ftx2 = F'*x2;
% Evaluate distances
d = x2tFx1.^2 ./ ...
(Fx1(1,:).^2 + Fx1(2,:).^2 + Ftx2(1,:).^2 + Ftx2(2,:).^2);
bestInliers = find(abs(d) < t); % Indices of inlying points
bestF = F; % Copy F directly to bestF
end
%----------------------------------------------------------------------
% (Degenerate!) function to determine if a set of matched points will result
% in a degeneracy in the calculation of a fundamental matrix as needed by
% RANSAC. This function assumes this cannot happen...
function r = isdegenerate(x)
r = 0;
|
github
|
jianxiongxiao/ProfXkit-master
|
matrix2quaternion.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/matrix2quaternion.m
| 2,010 |
utf_8
|
ad7a1983aceaa9953be167eddabb22ae
|
% MATRIX2QUATERNION - Homogeneous matrix to quaternion
%
% Converts 4x4 homogeneous rotation matrix to quaternion
%
% Usage: Q = matrix2quaternion(T)
%
% Argument: T - 4x4 Homogeneous transformation matrix
% Returns: Q - a quaternion in the form [w, xi, yj, zk]
%
% See Also QUATERNION2MATRIX
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
function Q = matrix2quaternion(T)
% This code follows the implementation suggested by Hartley and Zisserman
R = T(1:3, 1:3); % Extract rotation part of T
% Find rotation axis as the eigenvector having unit eigenvalue
% Solve (R-I)v = 0;
[v,d] = eig(R-eye(3));
% The following code assumes the eigenvalues returned are not necessarily
% sorted by size. This may be overcautious on my part.
d = diag(abs(d)); % Extract eigenvalues
[s, ind] = sort(d); % Find index of smallest one
if d(ind(1)) > 0.001 % Hopefully it is close to 0
warning('Rotation matrix is dubious');
end
axis = v(:,ind(1)); % Extract appropriate eigenvector
if abs(norm(axis) - 1) > .0001 % Debug
warning('non unit rotation axis');
end
% Now determine the rotation angle
twocostheta = trace(R)-1;
twosinthetav = [R(3,2)-R(2,3), R(1,3)-R(3,1), R(2,1)-R(1,2)]';
twosintheta = axis'*twosinthetav;
theta = atan2(twosintheta, twocostheta);
Q = [cos(theta/2); axis*sin(theta/2)];
|
github
|
jianxiongxiao/ProfXkit-master
|
harris.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/harris.m
| 4,707 |
utf_8
|
9123c3c21835dfa4d233abe149d6620d
|
% HARRIS - Harris corner detector
%
% Usage: cim = harris(im, sigma)
% [cim, r, c] = harris(im, sigma, thresh, radius, disp)
% [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)
%
% Arguments:
% im - image to be processed.
% sigma - standard deviation of smoothing Gaussian. Typical
% values to use might be 1-3.
% thresh - threshold (optional). Try a value ~1000.
% radius - radius of region considered in non-maximal
% suppression (optional). Typical values to use might
% be 1-3.
% disp - optional flag (0 or 1) indicating whether you want
% to display corners overlayed on the original
% image. This can be useful for parameter tuning. This
% defaults to 0
%
% Returns:
% cim - binary image marking corners.
% r - row coordinates of corner points.
% c - column coordinates of corner points.
% rsubp - If five return values are requested sub-pixel
% csubp - localization of feature points is attempted and
% returned as an additional set of floating point
% coords. Note that you may still want to use the integer
% valued coords to specify centres of correlation windows
% for feature matching.
%
% If thresh and radius are omitted from the argument list only 'cim' is returned
% as a raw corner strength image. You may then want to look at the values
% within 'cim' to determine the appropriate threshold value to use. Note that
% the Harris corner strength varies with the intensity gradient raised to the
% 4th power. Small changes in input image contrast result in huge changes in
% the appropriate threshold.
%
% Note that this code computes Noble's version of the detector which does not
% require the parameter 'k'. See comments in code if you wish to use Harris'
% original measure.
%
% See also: NONMAXSUPPTS, DERIVATIVE5
% References:
% C.G. Harris and M.J. Stephens. "A combined corner and edge detector",
% Proceedings Fourth Alvey Vision Conference, Manchester.
% pp 147-151, 1988.
%
% Alison Noble, "Descriptions of Image Surfaces", PhD thesis, Department
% of Engineering Science, Oxford University 1989, p45.
% Copyright (c) 2002-2010 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% March 2002 - Original version
% December 2002 - Updated comments
% August 2005 - Changed so that code calls nonmaxsuppts
% August 2010 - Changed to use Farid and Simoncelli's derivative filters
function [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)
error(nargchk(2,5,nargin));
if nargin == 4
disp = 0;
end
if ~isa(im,'double')
im = double(im);
end
subpixel = nargout == 5;
% Compute derivatives and elements of the structure tensor.
[Ix, Iy] = derivative5(im, 'x', 'y');
Ix2 = gaussfilt(Ix.^2, sigma);
Iy2 = gaussfilt(Iy.^2, sigma);
Ixy = gaussfilt(Ix.*Iy, sigma);
% Compute the Harris corner measure. Note that there are two measures
% that can be calculated. I prefer the first one below as given by
% Nobel in her thesis (reference above). The second one (commented out)
% requires setting a parameter, it is commonly suggested that k=0.04 - I
% find this a bit arbitrary and unsatisfactory.
cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % My preferred measure.
% k = 0.04;
% cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; % Original Harris measure.
if nargin > 2 % We should perform nonmaximal suppression and threshold
if disp % Call nonmaxsuppts to so that image is displayed
if subpixel
[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh, im);
else
[r,c] = nonmaxsuppts(cim, radius, thresh, im);
end
else % Just do the nonmaximal suppression
if subpixel
[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh);
else
[r,c] = nonmaxsuppts(cim, radius, thresh);
end
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
hnormalise.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/hnormalise.m
| 1,010 |
utf_8
|
5c1ed3ba361fa6f28b1517af1924af40
|
% HNORMALISE - Normalises array of homogeneous coordinates to a scale of 1
%
% Usage: nx = hnormalise(x)
%
% Argument:
% x - an Nxnpts array of homogeneous coordinates.
%
% Returns:
% nx - an Nxnpts array of homogeneous coordinates rescaled so
% that the scale values nx(N,:) are all 1.
%
% Note that any homogeneous coordinates at infinity (having a scale value of
% 0) are left unchanged.
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk
%
% February 2004
function nx = hnormalise(x)
[rows,npts] = size(x);
nx = x;
% Find the indices of the points that are not at infinity
finiteind = find(abs(x(rows,:)) > eps);
%if length(finiteind) ~= npts
% warning('Some points are at infinity');
%end
% Normalise points not at infinity
for r = 1:rows-1
nx(r,finiteind) = x(r,finiteind)./x(rows,finiteind);
end
nx(rows,finiteind) = 1;
|
github
|
jianxiongxiao/ProfXkit-master
|
homography2d.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/homography2d.m
| 2,493 |
utf_8
|
60985e0ab95fe690d769c83adff61080
|
% HOMOGRAPHY2D - computes 2D homography
%
% Usage: H = homography2d(x1, x2)
% H = homography2d(x)
%
% Arguments:
% x1 - 3xN set of homogeneous points
% x2 - 3xN set of homogeneous points such that x1<->x2
%
% x - If a single argument is supplied it is assumed that it
% is in the form x = [x1; x2]
% Returns:
% H - the 3x3 homography such that x2 = H*x1
%
% This code follows the normalised direct linear transformation
% algorithm given by Hartley and Zisserman "Multiple View Geometry in
% Computer Vision" p92.
%
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% May 2003 - Original version.
% Feb 2004 - Single argument allowed for to enable use with RANSAC.
% Feb 2005 - SVD changed to 'Economy' decomposition (thanks to Paul O'Leary)
function H = homography2d(varargin)
[x1, x2] = checkargs(varargin(:));
% Attempt to normalise each set of points so that the origin
% is at centroid and mean distance from origin is sqrt(2).
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
% Note that it may have not been possible to normalise
% the points if one was at infinity so the following does not
% assume that scale parameter w = 1.
Npts = length(x1);
A = zeros(3*Npts,9);
O = [0 0 0];
for n = 1:Npts
X = x1(:,n)';
x = x2(1,n); y = x2(2,n); w = x2(3,n);
A(3*n-2,:) = [ O -w*X y*X];
A(3*n-1,:) = [ w*X O -x*X];
A(3*n ,:) = [-y*X x*X O ];
end
[U,D,V] = svd(A,0); % 'Economy' decomposition for speed
% Extract homography
H = reshape(V(:,9),3,3)';
% Denormalise
H = T2\H*T1;
%--------------------------------------------------------------------------
% Function to check argument values and set defaults
function [x1, x2] = checkargs(arg);
if length(arg) == 2
x1 = arg{1};
x2 = arg{2};
if ~all(size(x1)==size(x2))
error('x1 and x2 must have the same size');
elseif size(x1,1) ~= 3
error('x1 and x2 must be 3xN');
end
elseif length(arg) == 1
if size(arg{1},1) ~= 6
error('Single argument x must be 6xN');
else
x1 = arg{1}(1:3,:);
x2 = arg{1}(4:6,:);
end
else
error('Wrong number of arguments supplied');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
iscolinear.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/iscolinear.m
| 2,318 |
utf_8
|
65025b7413f8f6b4cb16dd1689a5900f
|
% ISCOLINEAR - are 3 points colinear
%
% Usage: r = iscolinear(p1, p2, p3, flag)
%
% Arguments:
% p1, p2, p3 - Points in 2D or 3D.
% flag - An optional parameter set to 'h' or 'homog'
% indicating that p1, p2, p3 are homogneeous
% coordinates with arbitrary scale. If this is
% omitted it is assumed that the points are
% inhomogeneous, or that they are homogeneous with
% equal scale.
%
% Returns:
% r = 1 if points are co-linear, 0 otherwise
% Copyright (c) 2004-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2004
% January 2005 - modified to allow for homogeneous points of arbitrary
% scale (thanks to Michael Kirchhof)
function r = iscolinear(p1, p2, p3, flag)
if nargin == 3 % Assume inhomogeneous coords
flag = 'inhomog';
end
if ~all(size(p1)==size(p2)) | ~all(size(p1)==size(p3)) | ...
~(length(p1)==2 | length(p1)==3)
error('points must have the same dimension of 2 or 3');
end
% If data is 2D, assume they are 2D inhomogeneous coords. Make them
% homogeneous with scale 1.
if length(p1) == 2
p1(3) = 1; p2(3) = 1; p3(3) = 1;
end
if flag(1) == 'h'
% Apply test that allows for homogeneous coords with arbitrary
% scale. p1 X p2 generates a normal vector to plane defined by
% origin, p1 and p2. If the dot product of this normal with p3
% is zero then p3 also lies in the plane, hence co-linear.
r = abs(dot(cross(p1, p2),p3)) < eps;
else
% Assume inhomogeneous coords, or homogeneous coords with equal
% scale.
r = norm(cross(p2-p1, p3-p1)) < eps;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
monofilt.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/monofilt.m
| 6,435 |
utf_8
|
07ef46eb32d19a4d79e9ec304c6cb2d3
|
% MONOFILT - Apply monogenic filters to an image to obtain 2D analytic signal
%
% Implementation of Felsberg's monogenic filters
%
% Usage: [f, h1f, h2f, A, theta, psi] = ...
% monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap)
% 3 4 2 0.65 1/0
% Arguments:
% The convolutions are done via the FFT. Many of the parameters relate
% to the specification of the filters in the frequency plane.
%
% Variable Suggested Description
% name value
% ----------------------------------------------------------
% im Image to be convolved.
% nscale = 3; Number of filter scales.
% minWaveLength = 4; Wavelength of smallest scale filter.
% mult = 2; Scaling factor between successive filters.
% sigmaOnf = 0.65; Ratio of the standard deviation of the
% Gaussian describing the log Gabor filter's
% transfer function in the frequency domain
% to the filter center frequency.
% orientWrap 1/0 Optional flag 1/0 to turn on/off
% 'wrapping' of orientation data from a
% range of -pi .. pi to the range 0 .. pi.
% This affects the interpretation of the
% phase angle - see note below. Defaults to 0.
% Returns:
%
% f - cell array of bandpass filter responses with respect to scale.
% h1f - cell array of bandpass h1 filter responses wrt scale.
% h2f - cell array of bandpass h2 filter responses.
% A - cell array of monogenic energy responses.
% theta - cell array of phase orientation responses.
% psi - cell array of phase angle responses.
%
% If orientWrap is 1 (on) theta will be returned in the range 0 .. pi and
% psi (the phase angle) will be returned in the range -pi .. pi. If
% orientWrap is 0 theta will be returned in the range -pi .. pi and psi will
% be returned in the range -pi/2 .. pi/2. Try both options on an image of a
% circle to see what this means!
%
% Experimentation with sigmaOnf can be useful depending on your application.
% I have found values as low as 0.2 (a filter with a *very* large bandwidth)
% to be useful on some occasions.
%
% See also: GABORCONVOLVE
% References:
% Michael Felsberg and Gerald Sommer. "A New Extension of Linear Signal
% Processing for Estimating Local Properties and Detecting Features"
% DAGM Symposium 2000, Kiel
%
% Michael Felsberg and Gerald Sommer. "The Monogenic Signal" IEEE
% Transactions on Signal Processing, 49(12):3136-3144, December 2001
% Copyright (c) 2004-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% October 2004 - Original version.
% May 2005 - Orientation wrapping and code cleaned up.
% August 2005 - Phase calculation improved.
function [f, h1f, h2f, A, theta, psi] = ...
monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap)
if nargin == 5
orientWrap = 0; % Default is no orientation wrapping
end
if nargout > 4
thetaPhase = 1; % Calculate orientation and phase
else
thetaPhase = 0; % Only return filter outputs
end
[rows,cols] = size(im);
IM = fft2(double(im));
% Generate horizontal and vertical frequency grids that vary from
% -0.5 to 0.5
[u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ...
([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2)));
u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners
u2 = ifftshift(u2);
radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency
% values as a radius from centre
% (but quadrant shifted)
% Get rid of the 0 radius value in the middle (at top left corner after
% fftshifting) so that taking the log of the radius, or dividing by the
% radius, will not cause trouble.
radius(1,1) = 1;
H1 = i*u1./radius; % The two monogenic filters in the frequency domain
H2 = i*u2./radius;
% The two monogenic filters H1 and H2 are oriented in frequency space
% but are not selective in terms of the magnitudes of the
% frequencies. The code below generates bandpass log-Gabor filters
% which are point-wise multiplied by H1 and H2 to produce different
% bandpass versions of H1 and H2
for s = 1:nscale
wavelength = minWaveLength*mult^(s-1);
fo = 1.0/wavelength; % Centre frequency of filter.
logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2));
logGabor(1,1) = 0; % undo the radius fudge.
% Generate bandpass versions of H1 and H2 at this scale
H1s = H1.*logGabor;
H2s = H2.*logGabor;
% Apply filters to image in the frequency domain and get spatial
% results
f{s} = real(ifft2(IM.*logGabor));
h1f{s} = real(ifft2(IM.*H1s));
h2f{s} = real(ifft2(IM.*H2s));
A{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2); % Magnitude of Energy.
% If requested calculate the orientation and phase angles
if thetaPhase
theta{s} = atan2(h2f{s}, h1f{s}); % Orientation.
% Here phase is measured relative to the h1f-h2f plane as an
% 'elevation' angle that ranges over +- pi/2
psi{s} = atan2(f{s}, sqrt(h1f{s}.^2 + h2f{s}.^2));
if orientWrap
% Wrap orientation values back into the range 0-pi
negind = find(theta{s}<0);
theta{s}(negind) = theta{s}(negind) + pi;
% Where orientation values have been wrapped we should
% adjust phase accordingly **check**
psi{s}(negind) = pi-psi{s}(negind);
morethanpi = find(psi{s}>pi);
psi{s}(morethanpi) = psi{s}(morethanpi)-2*pi;
end
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
ransacfithomography.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/ransacfithomography.m
| 4,920 |
utf_8
|
d479d49f7c8e8689283005bcbe340b61
|
% RANSACFITHOMOGRAPHY - fits 2D homography using RANSAC
%
% Usage: [H, inliers] = ransacfithomography(x1, x2, t)
%
% Arguments:
% x1 - 2xN or 3xN set of homogeneous points. If the data is
% 2xN it is assumed the homogeneous scale factor is 1.
% x2 - 2xN or 3xN set of homogeneous points such that x1<->x2.
% t - The distance threshold between data point and the model
% used to decide whether a point is an inlier or not.
% Note that point coordinates are normalised to that their
% mean distance from the origin is sqrt(2). The value of
% t should be set relative to this, say in the range
% 0.001 - 0.01
%
% Note that it is assumed that the matching of x1 and x2 are putative and it
% is expected that a percentage of matches will be wrong.
%
% Returns:
% H - The 3x3 homography such that x2 = H*x1.
% inliers - An array of indices of the elements of x1, x2 that were
% the inliers for the best model.
%
% See Also: ransac, homography2d, homography1d
% Copyright (c) 2004-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2004 - original version
% July 2004 - error in denormalising corrected (thanks to Andrew Stein)
% August 2005 - homogdist2d modified to fit new ransac specification.
function [H, inliers] = ransacfithomography(x1, x2, t)
if ~all(size(x1)==size(x2))
error('Data sets x1 and x2 must have the same dimension');
end
[rows,npts] = size(x1);
if rows~=2 & rows~=3
error('x1 and x2 must have 2 or 3 rows');
end
if npts < 4
error('Must have at least 4 points to fit homography');
end
if rows == 2 % Pad data with homogeneous scale factor of 1
x1 = [x1; ones(1,npts)];
x2 = [x2; ones(1,npts)];
end
% Normalise each set of points so that the origin is at centroid and
% mean distance from origin is sqrt(2). normalise2dpts also ensures the
% scale parameter is 1. Note that 'homography2d' will also call
% 'normalise2dpts' but the code in 'ransac' that calls the distance
% function will not - so it is best that we normalise beforehand.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
s = 4; % Minimum No of points needed to fit a homography.
fittingfn = @homography2d;
distfn = @homogdist2d;
degenfn = @isdegenerate;
% x1 and x2 are 'stacked' to create a 6xN array for ransac
[H, inliers] = ransac([x1; x2], fittingfn, distfn, degenfn, s, t);
% Now do a final least squares fit on the data points considered to
% be inliers.
H = homography2d(x1(:,inliers), x2(:,inliers));
% Denormalise
H = T2\H*T1;
%----------------------------------------------------------------------
% Function to evaluate the symmetric transfer error of a homography with
% respect to a set of matched points as needed by RANSAC.
function [inliers, H] = homogdist2d(H, x, t);
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
% Calculate, in both directions, the transfered points
Hx1 = H*x1;
invHx2 = H\x2;
% Normalise so that the homogeneous scale parameter for all coordinates
% is 1.
x1 = hnormalise(x1);
x2 = hnormalise(x2);
Hx1 = hnormalise(Hx1);
invHx2 = hnormalise(invHx2);
d2 = sum((x1-invHx2).^2) + sum((x2-Hx1).^2);
inliers = find(abs(d2) < t);
%----------------------------------------------------------------------
% Function to determine if a set of 4 pairs of matched points give rise
% to a degeneracy in the calculation of a homography as needed by RANSAC.
% This involves testing whether any 3 of the 4 points in each set is
% colinear.
function r = isdegenerate(x)
x1 = x(1:3,:); % Extract x1 and x2 from x
x2 = x(4:6,:);
r = ...
iscolinear(x1(:,1),x1(:,2),x1(:,3)) | ...
iscolinear(x1(:,1),x1(:,2),x1(:,4)) | ...
iscolinear(x1(:,1),x1(:,3),x1(:,4)) | ...
iscolinear(x1(:,2),x1(:,3),x1(:,4)) | ...
iscolinear(x2(:,1),x2(:,2),x2(:,3)) | ...
iscolinear(x2(:,1),x2(:,2),x2(:,4)) | ...
iscolinear(x2(:,1),x2(:,3),x2(:,4)) | ...
iscolinear(x2(:,2),x2(:,3),x2(:,4));
|
github
|
jianxiongxiao/ProfXkit-master
|
fundmatrix.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/fundmatrix.m
| 3,961 |
utf_8
|
250dfa8051640daab30229f35667f4d6
|
% FUNDMATRIX - computes fundamental matrix from 8 or more points
%
% Function computes the fundamental matrix from 8 or more matching points in
% a stereo pair of images. The normalised 8 point algorithm given by
% Hartley and Zisserman p265 is used. To achieve accurate results it is
% recommended that 12 or more points are used
%
% Usage: [F, e1, e2] = fundmatrix(x1, x2)
% [F, e1, e2] = fundmatrix(x)
%
% Arguments:
% x1, x2 - Two sets of corresponding 3xN set of homogeneous
% points.
%
% x - If a single argument is supplied it is assumed that it
% is in the form x = [x1; x2]
% Returns:
% F - The 3x3 fundamental matrix such that x2'*F*x1 = 0.
% e1 - The epipole in image 1 such that F*e1 = 0
% e2 - The epipole in image 2 such that F'*e2 = 0
%
% Copyright (c) 2002-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% Feb 2002 - Original version.
% May 2003 - Tidied up and numerically improved.
% Feb 2004 - Single argument allowed to enable use with RANSAC.
% Mar 2005 - Epipole calculation added, 'economy' SVD used.
% Aug 2005 - Octave compatibility
function [F,e1,e2] = fundmatrix(varargin)
[x1, x2, npts] = checkargs(varargin(:));
Octave = exist('OCTAVE_VERSION') ~= 0; % Are we running under Octave?
% Normalise each set of points so that the origin
% is at centroid and mean distance from origin is sqrt(2).
% normalise2dpts also ensures the scale parameter is 1.
[x1, T1] = normalise2dpts(x1);
[x2, T2] = normalise2dpts(x2);
% Build the constraint matrix
A = [x2(1,:)'.*x1(1,:)' x2(1,:)'.*x1(2,:)' x2(1,:)' ...
x2(2,:)'.*x1(1,:)' x2(2,:)'.*x1(2,:)' x2(2,:)' ...
x1(1,:)' x1(2,:)' ones(npts,1) ];
if Octave
[U,D,V] = svd(A); % Don't seem to be able to use the economy
% decomposition under Octave here
else
[U,D,V] = svd(A,0); % Under MATLAB use the economy decomposition
end
% Extract fundamental matrix from the column of V corresponding to
% smallest singular value.
F = reshape(V(:,9),3,3)';
% Enforce constraint that fundamental matrix has rank 2 by performing
% a svd and then reconstructing with the two largest singular values.
[U,D,V] = svd(F,0);
F = U*diag([D(1,1) D(2,2) 0])*V';
% Denormalise
F = T2'*F*T1;
if nargout == 3 % Solve for epipoles
[U,D,V] = svd(F,0);
e1 = hnormalise(V(:,3));
e2 = hnormalise(U(:,3));
end
%--------------------------------------------------------------------------
% Function to check argument values and set defaults
function [x1, x2, npts] = checkargs(arg);
if length(arg) == 2
x1 = arg{1};
x2 = arg{2};
if ~all(size(x1)==size(x2))
error('x1 and x2 must have the same size');
elseif size(x1,1) ~= 3
error('x1 and x2 must be 3xN');
end
elseif length(arg) == 1
if size(arg{1},1) ~= 6
error('Single argument x must be 6xN');
else
x1 = arg{1}(1:3,:);
x2 = arg{1}(4:6,:);
end
else
error('Wrong number of arguments supplied');
end
npts = size(x1,2);
if npts < 8
error('At least 8 points are needed to compute the fundamental matrix');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
hline.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/hline.m
| 1,584 |
utf_8
|
7887599478d2ebb7e50fdef565f8f3f5
|
% HLINE - Plot 2D lines defined in homogeneous coordinates.
%
% Function for ploting 2D homogeneous lines defined by 2 points
% or a line defined by a single homogeneous vector
%
% Usage: hline(p1,p2) where p1 and p2 are 2D homogeneous points.
% hline(p1,p2,'colour_name') 'black' 'red' 'white' etc
% hline(l) where l is a line in homogeneous coordinates
% hline(l,'colour_name')
%
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk @ csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% April 2000
function hline(a,b,c)
col = 'blue'; % default colour
if nargin >= 2 & isa(a,'double') & isa(b,'double') % Two points specified
p1 = a./a(3); % make sure homogeneous points lie in z=1 plane
p2 = b./b(3);
if nargin == 3 & isa(c,'char') % 2 points and a colour specified
col = c;
end
elseif nargin >= 1 & isa(a,'double') % A single line specified
a = a./a(3); % ensure line in z = 1 plane (not needed??)
if abs(a(1)) > abs(a(2)) % line is more vertical
ylim = get(get(gcf,'CurrentAxes'),'Ylim');
p1 = hcross(a, [0 1 0]');
p2 = hcross(a, [0 -1/ylim(2) 1]');
else % line more horizontal
xlim = get(get(gcf,'CurrentAxes'),'Xlim');
p1 = hcross(a, [1 0 0]');
p2 = hcross(a, [-1/xlim(2) 0 1]');
end
if nargin == 2 & isa(b,'char') % 1 line vector and a colour specified
col = b;
end
else
error('Bad arguments passed to hline');
end
line([p1(1) p2(1)], [p1(2) p2(2)], 'color', col);
|
github
|
jianxiongxiao/ProfXkit-master
|
ransac.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/ransac.m
| 9,583 |
utf_8
|
f79cf643308f984914c65e4023a0ac9b
|
% RANSAC - Robustly fits a model to data with the RANSAC algorithm
%
% Usage:
%
% [M, inliers] = ransac(x, fittingfn, distfn, degenfn s, t, feedback, ...
% maxDataTrials, maxTrials)
%
% Arguments:
% x - Data sets to which we are seeking to fit a model M
% It is assumed that x is of size [d x Npts]
% where d is the dimensionality of the data and Npts is
% the number of data points.
%
% fittingfn - Handle to a function that fits a model to s
% data from x. It is assumed that the function is of the
% form:
% M = fittingfn(x)
% Note it is possible that the fitting function can return
% multiple models (for example up to 3 fundamental matrices
% can be fitted to 7 matched points). In this case it is
% assumed that the fitting function returns a cell array of
% models.
% If this function cannot fit a model it should return M as
% an empty matrix.
%
% distfn - Handle to a function that evaluates the
% distances from the model to data x.
% It is assumed that the function is of the form:
% [inliers, M] = distfn(M, x, t)
% This function must evaluate the distances between points
% and the model returning the indices of elements in x that
% are inliers, that is, the points that are within distance
% 't' of the model. Additionally, if M is a cell array of
% possible models 'distfn' will return the model that has the
% most inliers. If there is only one model this function
% must still copy the model to the output. After this call M
% will be a non-cell object representing only one model.
%
% degenfn - Handle to a function that determines whether a
% set of datapoints will produce a degenerate model.
% This is used to discard random samples that do not
% result in useful models.
% It is assumed that degenfn is a boolean function of
% the form:
% r = degenfn(x)
% It may be that you cannot devise a test for degeneracy in
% which case you should write a dummy function that always
% returns a value of 1 (true) and rely on 'fittingfn' to return
% an empty model should the data set be degenerate.
%
% s - The minimum number of samples from x required by
% fittingfn to fit a model.
%
% t - The distance threshold between a data point and the model
% used to decide whether the point is an inlier or not.
%
% feedback - An optional flag 0/1. If set to one the trial count and the
% estimated total number of trials required is printed out at
% each step. Defaults to 0.
%
% maxDataTrials - Maximum number of attempts to select a non-degenerate
% data set. This parameter is optional and defaults to 100.
%
% maxTrials - Maximum number of iterations. This parameter is optional and
% defaults to 1000.
%
% Returns:
% M - The model having the greatest number of inliers.
% inliers - An array of indices of the elements of x that were
% the inliers for the best model.
%
% For an example of the use of this function see RANSACFITHOMOGRAPHY or
% RANSACFITPLANE
% References:
% M.A. Fishler and R.C. Boles. "Random sample concensus: A paradigm
% for model fitting with applications to image analysis and automated
% cartography". Comm. Assoc. Comp, Mach., Vol 24, No 6, pp 381-395, 1981
%
% Richard Hartley and Andrew Zisserman. "Multiple View Geometry in
% Computer Vision". pp 101-113. Cambridge University Press, 2001
% Copyright (c) 2003-2006 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% May 2003 - Original version
% February 2004 - Tidied up.
% August 2005 - Specification of distfn changed to allow model fitter to
% return multiple models from which the best must be selected
% Sept 2006 - Random selection of data points changed to ensure duplicate
% points are not selected.
% February 2007 - Jordi Ferrer: Arranged warning printout.
% Allow maximum trials as optional parameters.
% Patch the problem when non-generated data
% set is not given in the first iteration.
% August 2008 - 'feedback' parameter restored to argument list and other
% breaks in code introduced in last update fixed.
% December 2008 - Octave compatibility mods
% June 2009 - Argument 'MaxTrials' corrected to 'maxTrials'!
function [M, inliers] = ransac(x, fittingfn, distfn, degenfn, s, t, feedback, ...
maxDataTrials, maxTrials)
Octave = exist('OCTAVE_VERSION') ~= 0;
% Test number of parameters
error ( nargchk ( 6, 9, nargin ) );
if nargin < 9; maxTrials = 50000; end;
if nargin < 8; maxDataTrials = 1000; end;
if nargin < 7; feedback = 0; end;
[rows, npts] = size(x);
p = 0.99; % Desired probability of choosing at least one sample
% free from outliers
bestM = NaN; % Sentinel value allowing detection of solution failure.
trialcount = 0;
bestscore = 0;
N = 1; % Dummy initialisation for number of trials.
% for debugging, we fix the set
stream = RandStream.getGlobalStream;
reset(stream);
while N > trialcount
% Select at random s datapoints to form a trial model, M.
% In selecting these points we have to check that they are not in
% a degenerate configuration.
degenerate = 1;
count = 1;
while degenerate
% Generate s random indicies in the range 1..npts
% (If you do not have the statistics toolbox, or are using Octave,
% use the function RANDOMSAMPLE from my webpage)
if Octave | ~exist('randsample.m')
ind = randomsample(npts, s);
else
ind = randsample(npts, s);
end
% Test that these points are not a degenerate configuration.
degenerate = feval(degenfn, x(:,ind));
if ~degenerate
% Fit model to this random selection of data points.
% Note that M may represent a set of models that fit the data in
% this case M will be a cell array of models
M = feval(fittingfn, x(:,ind));
% Depending on your problem it might be that the only way you
% can determine whether a data set is degenerate or not is to
% try to fit a model and see if it succeeds. If it fails we
% reset degenerate to true.
if isempty(M)
degenerate = 1;
end
end
% Safeguard against being stuck in this loop forever
count = count + 1;
if count > maxDataTrials
warning('Unable to select a nondegenerate data set');
break
end
end
% Once we are out here we should have some kind of model...
% Evaluate distances between points and model returning the indices
% of elements in x that are inliers. Additionally, if M is a cell
% array of possible models 'distfn' will return the model that has
% the most inliers. After this call M will be a non-cell object
% representing only one model.
[inliers, M] = feval(distfn, M, x, t);
% Find the number of inliers to this model.
ninliers = length(inliers);
% Jianxiong: I change it from > to >=
if ninliers >= bestscore % Largest set of inliers so far...
bestscore = ninliers; % Record data for this model
bestinliers = inliers;
bestM = M;
% Update estimate of N, the number of trials to ensure we pick,
% with probability p, a data set with no outliers.
fracinliers = ninliers/npts;
pNoOutliers = 1 - fracinliers^s;
pNoOutliers = max(eps, pNoOutliers); % Avoid division by -Inf
pNoOutliers = min(1-eps, pNoOutliers);% Avoid division by 0.
N = log(1-p)/log(pNoOutliers);
N = max(N,10); % at least try 20 times
end
trialcount = trialcount+1;
if feedback
fprintf('trial %d out of %d \r',trialcount, ceil(N));
end
% Safeguard against being stuck in this loop forever
if trialcount > maxTrials
warning( ...
sprintf('ransac reached the maximum number of %d trials',...
maxTrials));
break
end
end
%fprintf('\n');
if ~isnan(bestM) % We got a solution
M = bestM;
inliers = bestinliers;
else
M = [];
inliers = [];
error('ransac was unable to find a useful solution');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
gaussfilt.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/gaussfilt.m
| 892 |
utf_8
|
266e718eee73f61a8bc07650565a1692
|
% GAUSSFILT - Small wrapper function for convenient Gaussian filtering
%
% Usage: smim = gaussfilt(im, sigma)
%
% Arguments: im - Image to be smoothed.
% sigma - Standard deviation of Gaussian filter.
%
% Returns: smim - Smoothed image.
%
% See also: INTEGGAUSSFILT
% Peter Kovesi
% Centre for Explortion Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
% March 2010
function smim = gaussfilt(im, sigma)
assert(ndims(im) == 2, 'Image must be greyscale');
% If needed convert im to double
if ~strcmp(class(im),'double')
im = double(im);
end
sze = ceil(6*sigma);
if ~mod(sze,2) % Ensure filter size is odd
sze = sze+1;
end
sze = max(sze,1); % and make sure it is at least 1
h = fspecial('gaussian', [sze sze], sigma);
smim = filter2(h, im);
|
github
|
jianxiongxiao/ProfXkit-master
|
derivative5.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/derivative5.m
| 4,808 |
utf_8
|
989b39a3f681a8cad7375573fa1a7a0f
|
% DERIVATIVE5 - 5-Tap 1st and 2nd discrete derivatives
%
% This function computes 1st and 2nd derivatives of an image using the 5-tap
% coefficients given by Farid and Simoncelli. The results are significantly
% more accurate than MATLAB's GRADIENT function on edges that are at angles
% other than vertical or horizontal. This in turn improves gradient orientation
% estimation enormously. If you are after extreme accuracy try using DERIVATIVE7.
%
% Usage: [gx, gy, gxx, gyy, gxy] = derivative5(im, derivative specifiers)
%
% Arguments:
% im - Image to compute derivatives from.
% derivative specifiers - A comma separated list of character strings
% that can be any of 'x', 'y', 'xx', 'yy' or 'xy'
% These can be in any order, the order of the
% computed output arguments will match the order
% of the derivative specifier strings.
% Returns:
% Function returns requested derivatives which can be:
% gx, gy - 1st derivative in x and y
% gxx, gyy - 2nd derivative in x and y
% gxy - 1st derivative in y of 1st derivative in x
%
% Examples:
% Just compute 1st derivatives in x and y
% [gx, gy] = derivative5(im, 'x', 'y');
%
% Compute 2nd derivative in x, 1st derivative in y and 2nd derivative in y
% [gxx, gy, gyy] = derivative5(im, 'xx', 'y', 'yy')
%
% See also: DERIVATIVE7
% Reference: Hany Farid and Eero Simoncelli "Differentiation of Discrete
% Multi-Dimensional Signals" IEEE Trans. Image Processing. 13(4): 496-508 (2004)
% Copyright (c) 2010 Peter Kovesi
% Centre for Exploration Targeting
% The University of Western Australia
% http://www.csse.uwa.edu.au/~pk/research/matlabfns/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
%
% April 2010
function varargout = derivative5(im, varargin)
varargin = varargin(:);
varargout = cell(size(varargin));
% Check if we are just computing 1st derivatives. If so use the
% interpolant and derivative filters optimized for 1st derivatives, else
% use 2nd derivative filters and interpolant coefficients.
% Detection is done by seeing if any of the derivative specifier
% arguments is longer than 1 char, this implies 2nd derivative needed.
secondDeriv = false;
for n = 1:length(varargin)
if length(varargin{n}) > 1
secondDeriv = true;
break
end
end
if ~secondDeriv
% 5 tap 1st derivative cofficients. These are optimal if you are just
% seeking the 1st deriavtives
p = [0.037659 0.249153 0.426375 0.249153 0.037659];
d1 =[0.109604 0.276691 0.000000 -0.276691 -0.109604];
else
% 5-tap 2nd derivative coefficients. The associated 1st derivative
% coefficients are not quite as optimal as the ones above but are
% consistent with the 2nd derivative interpolator p and thus are
% appropriate to use if you are after both 1st and 2nd derivatives.
p = [0.030320 0.249724 0.439911 0.249724 0.030320];
d1 = [0.104550 0.292315 0.000000 -0.292315 -0.104550];
d2 = [0.232905 0.002668 -0.471147 0.002668 0.232905];
end
% Compute derivatives. Note that in the 1st call below MATLAB's conv2
% function performs a 1D convolution down the columns using p then a 1D
% convolution along the rows using d1. etc etc.
gx = false;
for n = 1:length(varargin)
if strcmpi('x', varargin{n})
varargout{n} = conv2(p, d1, im, 'same');
gx = true; % Record that gx is available for gxy if needed
gxn = n;
elseif strcmpi('y', varargin{n})
varargout{n} = conv2(d1, p, im, 'same');
elseif strcmpi('xx', varargin{n})
varargout{n} = conv2(p, d2, im, 'same');
elseif strcmpi('yy', varargin{n})
varargout{n} = conv2(d2, p, im, 'same');
elseif strcmpi('xy', varargin{n}) | strcmpi('yx', varargin{n})
if gx
varargout{n} = conv2(d1, p, varargout{gxn}, 'same');
else
gx = conv2(p, d1, im, 'same');
varargout{n} = conv2(d1, p, gx, 'same');
end
else
error(sprintf('''%s'' is an unrecognized derivative option',varargin{n}));
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
quaternion2matrix.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/quaternion2matrix.m
| 1,413 |
utf_8
|
7296cadf62f6ca9273e726ffd7e19d95
|
% QUATERNION2MATRIX - Quaternion to a 4x4 homogeneous transformation matrix
%
% Usage: T = quaternion2matrix(Q)
%
% Argument: Q - a quaternion in the form [w xi yj zk]
% Returns: T - 4x4 Homogeneous rotation matrix
%
% See also MATRIX2QUATERNION, NEWQUATERNION, QUATERNIONROTATE
% Copyright (c) 2008 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
function T = quaternion2matrix(Q)
Q = Q/norm(Q); % Ensure Q has unit norm
% Set up convenience variables
w = Q(1); x = Q(2); y = Q(3); z = Q(4);
w2 = w^2; x2 = x^2; y2 = y^2; z2 = z^2;
xy = x*y; xz = x*z; yz = y*z;
wx = w*x; wy = w*y; wz = w*z;
T = [w2+x2-y2-z2 , 2*(xy - wz) , 2*(wy + xz) , 0
2*(wz + xy) , w2-x2+y2-z2 , 2*(yz - wx) , 0
2*(xz - wy) , 2*(wx + yz) , w2-x2-y2+z2 , 0
0 , 0 , 0 , 1];
|
github
|
jianxiongxiao/ProfXkit-master
|
matchbymonogenicphase.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/matchbymonogenicphase.m
| 9,328 |
utf_8
|
e63225faedcf391fb6411d27d71a208e
|
% MATCHBYMONOGENICPHASE - match image feature points using monogenic phase data
%
% Function generates putative matches between previously detected
% feature points in two images by looking for points that have minimal
% differences in monogenic phase data within windows surrounding each point.
% Only points that correlate most strongly with each other in *both*
% directions are returned. This is a simple-minded N^2 comparison.
%
% This matcher performs rather well relative to normalised greyscale
% correlation. Typically there are more putative matches found and fewer
% outliers. There is a greater computational cost in the pre-filtering stage
% but potentially the matching stage is much faster as each pixel is effectively
% encoded with only 3 bits. (Though this potential speed is not realized in this
% implementation)
%
% Usage: [m1,m2] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ...
% nscale, minWaveLength, mult, sigmaOnf)
%
% Arguments:
% im1, im2 - Images containing points that we wish to match.
% p1, p2 - Coordinates of feature pointed detected in im1 and
% im2 respectively using a corner detector (say Harris
% or phasecong2). p1 and p2 are [2xnpts] arrays though
% p1 and p2 are not expected to have the same number
% of points. The first row of p1 and p2 gives the row
% coordinate of each feature point, the second row
% gives the column of each point.
% w - Window size (in pixels) over which the phase bit codes
% around each feature point are matched. This should
% be an odd number.
% dmax - Maximum search radius for matching points. Used to
% improve speed when there is little disparity between
% images. Even setting it to a generous value of 1/4 of
% the image size gives a useful speedup.
% nscale - Number of filter scales.
% minWaveLength - Wavelength of smallest scale filter.
% mult - Scaling factor between successive filters.
% sigmaOnf - Ratio of the standard deviation of the Gaussian
% describing the log Gabor filter's transfer function in
% the frequency domain to the filter center frequency.
%
%
% Returns:
% m1, m2 - Coordinates of points selected from p1 and p2
% respectively such that (putatively) m1(:,i) matches
% m2(:,i). m1 and m2 are [2xnpts] arrays defining the
% points in each of the images in the form [row;col].
%
%
% I have had good success with the folowing parameters:
%
% w = 11; Window size for correlation matching, 7 or greater
% seems fine.
% dmax = 50;
% nscale = 1; Just one scale can give very good results. Adding
% another scale doubles computation
% minWaveLength = 10;
% mult = 4; This is irrelevant if only one scale is used. If you do
% use more than one scale try values in the range 2-4.
% sigmaOnf = .2; This results in a *very* large bandwidth filter. A
% large bandwidth seems to be very important in the
% matching performance.
%
% See Also: MATCHBYCORRELATION, MONOFILT
% Copyright (c) 2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% May 2005 - Original version adapted from matchbycorrelation.m
function [m1,m2,cormat] = matchbymonogenicphase(im1, p1, im2, p2, w, dmax, ...
nscale, minWaveLength, mult, sigmaOnf)
orientWrap = 0;
[f1, h1f1, h2f1, A1] = ...
monofilt(im1, nscale, minWaveLength, mult, sigmaOnf, orientWrap);
[f2, h1f2, h2f2, A2] = ...
monofilt(im2, nscale, minWaveLength, mult, sigmaOnf, orientWrap);
% Normalise filter outputs to unit vectors (should also have masking for
% unreliable filter outputs)
for s = 1:nscale
% f1{s} = f1{s}./A1{s}; f2{s} = f2{s}./A2{s};
% h1f1{s} = h1f1{s}./A1{s}; h1f2{s} = h1f2{s}./A2{s};
% h2f1{s} = h2f1{s}./A1{s}; h2f2{s} = h2f2{s}./A2{s};
% Try quantizing oriented phase vector to 8 octants to see what
% effect this has (Performance seems to be reduced only slightly)
f1{s} = sign(f1{s}); f2{s} = sign(f2{s});
h1f1{s} = sign(h1f1{s}); h1f2{s} = sign(h1f2{s});
h2f1{s} = sign(h2f1{s}); h2f2{s} = sign(h2f2{s});
end
% Generate correlation matrix
cormat = correlationmatrix(f1, h1f1, h2f1, p1, ...
f2, h1f2, h2f2, p2, w, dmax);
[corrows,corcols] = size(cormat);
% Find max along rows give strongest match in p2 for each p1
[mp2forp1, colp2forp1] = max(cormat,[],2);
% Find max down cols give strongest match in p1 for each p2
[mp1forp2, rowp1forp2] = max(cormat,[],1);
% Now find matches that were consistent in both directions
p1ind = zeros(1,length(p1)); % Arrays for storing matched indices
p2ind = zeros(1,length(p2));
indcount = 0;
for n = 1:corrows
if rowp1forp2(colp2forp1(n)) == n % consistent both ways
indcount = indcount + 1;
p1ind(indcount) = n;
p2ind(indcount) = colp2forp1(n);
end
end
% Trim arrays of indices of matched points
p1ind = p1ind(1:indcount);
p2ind = p2ind(1:indcount);
% Extract matched points from original arrays
m1 = p1(:,p1ind);
m2 = p2(:,p2ind);
%-------------------------------------------------------------------------
% Function that does the work. This function builds a 'correlation' matrix
% that holds the correlation strength of every point relative to every other
% point. While this seems a bit wasteful we need all this data if we want
% to find pairs of points that correlate maximally in both directions.
function cormat = correlationmatrix(f1, h1f1, h2f1, p1, ...
f2, h1f2, h2f2, p2, w, dmax)
if mod(w, 2) == 0 | w < 3
error('Window size should be odd and >= 3');
end
r = (w-1)/2; % 'radius' of correlation window
[rows1, npts1] = size(p1);
[rows2, npts2] = size(p2);
if rows1 ~= 2 | rows2 ~= 2
error('Feature points must be specified in 2xN arrays');
end
% Reorganize monogenic phase data into a 4D matrices for convenience
[im1rows,im1cols] = size(f1{1});
[im2rows,im2cols] = size(f2{1});
nscale = length(f1);
phase1 = zeros(im1rows,im1cols,nscale,3);
phase2 = zeros(im2rows,im2cols,nscale,3);
for s = 1:nscale
phase1(:,:,s,1) = f1{s}; phase1(:,:,s,2) = h1f1{s}; phase1(:,:,s,3) = h2f1{s};
phase2(:,:,s,1) = f2{s}; phase2(:,:,s,2) = h1f2{s}; phase2(:,:,s,3) = h2f2{s};
end
% Initialize correlation matrix values to -infinity
cormat = repmat(-inf, npts1, npts2);
% For every feature point in the first image extract a window of data
% and correlate with a window corresponding to every feature point in
% the other image. Any feature point less than distance 'r' from the
% boundary of an image is not considered.
% Find indices of points that are distance 'r' or greater from
% boundary on image1 and image2;
n1ind = find(p1(1,:)>r & p1(1,:)<im1rows+1-r & ...
p1(2,:)>r & p1(2,:)<im1cols+1-r);
n2ind = find(p2(1,:)>r & p2(1,:)<im2rows+1-r & ...
p2(2,:)>r & p2(2,:)<im2cols+1-r);
for n1 = n1ind
% Identify the indices of points in p2 that we need to consider.
if dmax == inf
n2indmod = n2ind; % We have to consider all of n2ind
else % Compute distances from p1(:,n1) to all available p2.
p1pad = repmat(p1(:,n1),1,length(n2ind));
dists2 = sum((p1pad-p2(:,n2ind)).^2);
% Find indices of points in p2 that are within distance dmax of
% p1(:,n1)
n2indmod = n2ind(find(dists2 < dmax^2));
end
% Generate window in 1st image
w1 = phase1(p1(1,n1)-r:p1(1,n1)+r, p1(2,n1)-r:p1(2,n1)+r, :, :);
for n2 = n2indmod
% Generate window in 2nd image
w2 = phase2(p2(1,n2)-r:p2(1,n2)+r, p2(2,n2)-r:p2(2,n2)+r, :, :);
% Compute dot product as correlation measure
cormat(n1,n2) = w1(:)'*w2(:);
% *** Need to add mask stuff
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
normalise2dpts.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/normalise2dpts.m
| 2,361 |
utf_8
|
2b9d94a3681186006a3fd47a45faf939
|
% NORMALISE2DPTS - normalises 2D homogeneous points
%
% Function translates and normalises a set of 2D homogeneous points
% so that their centroid is at the origin and their mean distance from
% the origin is sqrt(2). This process typically improves the
% conditioning of any equations used to solve homographies, fundamental
% matrices etc.
%
% Usage: [newpts, T] = normalise2dpts(pts)
%
% Argument:
% pts - 3xN array of 2D homogeneous coordinates
%
% Returns:
% newpts - 3xN array of transformed 2D homogeneous coordinates. The
% scaling parameter is normalised to 1 unless the point is at
% infinity.
% T - The 3x3 transformation matrix, newpts = T*pts
%
% If there are some points at infinity the normalisation transform
% is calculated using just the finite points. Being a scaling and
% translating transform this will not affect the points at infinity.
% Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% pk at csse uwa edu au
% http://www.csse.uwa.edu.au/~pk
%
% May 2003 - Original version
% February 2004 - Modified to deal with points at infinity.
% December 2008 - meandist calculation modified to work with Octave 3.0.1
% (thanks to Ron Parr)
function [newpts, T] = normalise2dpts(pts)
if size(pts,1) ~= 3
error('pts must be 3xN');
end
% Find the indices of the points that are not at infinity
finiteind = find(abs(pts(3,:)) > eps);
if length(finiteind) ~= size(pts,2)
warning('Some points are at infinity');
end
% For the finite points ensure homogeneous coords have scale of 1
pts(1,finiteind) = pts(1,finiteind)./pts(3,finiteind);
pts(2,finiteind) = pts(2,finiteind)./pts(3,finiteind);
pts(3,finiteind) = 1;
c = mean(pts(1:2,finiteind)')'; % Centroid of finite points
newp(1,finiteind) = pts(1,finiteind)-c(1); % Shift origin to centroid.
newp(2,finiteind) = pts(2,finiteind)-c(2);
dist = sqrt(newp(1,finiteind).^2 + newp(2,finiteind).^2);
meandist = mean(dist(:)); % Ensure dist is a column vector for Octave 3.0.1
scale = sqrt(2)/meandist;
T = [scale 0 -scale*c(1)
0 scale -scale*c(2)
0 0 1 ];
newpts = T*pts;
|
github
|
jianxiongxiao/ProfXkit-master
|
hcross.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/hcross.m
| 919 |
utf_8
|
dbb3f3d4ef79e25ca3000ea976409e0c
|
% HCROSS - Homogeneous cross product, result normalised to s = 1.
%
% Function to form cross product between two points, or lines,
% in homogeneous coodinates. The result is normalised to lie
% in the scale = 1 plane.
%
% Usage: c = hcross(a,b)
%
% Copyright (c) 2000-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% April 2000
function c = hcross(a,b)
c = cross(a,b);
c = c/c(3);
|
github
|
jianxiongxiao/ProfXkit-master
|
matchbycorrelation.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/peter/matchbycorrelation.m
| 7,076 |
utf_8
|
12d7e8d4ad6e140c94444ddc3682d518
|
% MATCHBYCORRELATION - match image feature points by correlation
%
% Function generates putative matches between previously detected
% feature points in two images by looking for points that are maximally
% correlated with each other within windows surrounding each point.
% Only points that correlate most strongly with each other in *both*
% directions are returned.
% This is a simple-minded N^2 comparison.
%
% Usage: [m1, m2, p1ind, p2ind, cormat] = ...
% matchbycorrelation(im1, p1, im2, p2, w, dmax)
%
% Arguments:
% im1, im2 - Images containing points that we wish to match.
% p1, p2 - Coordinates of feature pointed detected in im1 and
% im2 respectively using a corner detector (say Harris
% or phasecong2). p1 and p2 are [2xnpts] arrays though
% p1 and p2 are not expected to have the same number
% of points. The first row of p1 and p2 gives the row
% coordinate of each feature point, the second row
% gives the column of each point.
% w - Window size (in pixels) over which the correlation
% around each feature point is performed. This should
% be an odd number.
% dmax - (Optional) Maximum search radius for matching
% points. Used to improve speed when there is little
% disparity between images. Even setting it to a generous
% value of 1/4 of the image size gives a useful
% speedup. If this parameter is omitted it defaults to Inf.
%
%
% Returns:
% m1, m2 - Coordinates of points selected from p1 and p2
% respectively such that (putatively) m1(:,i) matches
% m2(:,i). m1 and m2 are [2xnpts] arrays defining the
% points in each of the images in the form [row;col].
% p1ind, p2ind - Indices of points in p1 and p2 that form a match. Thus,
% m1 = p1(:,p1ind) and m2 = p2(:,p2ind)
% cormat - Correlation matrix; rows correspond to points in p1,
% columns correspond to points in p2
% Copyright (c) 2004-2009 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% February 2004 - Original version
% May 2004 - Speed improvements + constraint on search radius for
% additional speed
% August 2004 - Vectorized distance calculation for more speed
% (thanks to Daniel Wedge)
% December 2009 - Added return of indices of matching points from original
% point arrays
function [m1, m2, p1ind, p2ind, cormat] = ...
matchbycorrelation(im1, p1, im2, p2, w, dmax)
if nargin == 5
dmax = Inf;
end
im1 = double(im1);
im2 = double(im2);
% Subtract image smoothed with an averaging filter of size wXw from
% each of the images. This compensates for brightness differences in
% each image. Doing it now allows faster correlation calculation.
im1 = im1 - filter2(fspecial('average',w),im1);
im2 = im2 - filter2(fspecial('average',w),im2);
% Generate correlation matrix
cormat = correlatiomatrix(im1, p1, im2, p2, w, dmax);
[corrows,corcols] = size(cormat);
% Find max along rows give strongest match in p2 for each p1
[mp2forp1, colp2forp1] = max(cormat,[],2);
% Find max down cols give strongest match in p1 for each p2
[mp1forp2, rowp1forp2] = max(cormat,[],1);
% Now find matches that were consistent in both directions
p1ind = zeros(1,length(p1)); % Arrays for storing matched indices
p2ind = zeros(1,length(p2));
indcount = 0;
for n = 1:corrows
if rowp1forp2(colp2forp1(n)) == n % consistent both ways
indcount = indcount + 1;
p1ind(indcount) = n;
p2ind(indcount) = colp2forp1(n);
end
end
% Trim arrays of indices of matched points
p1ind = p1ind(1:indcount);
p2ind = p2ind(1:indcount);
% Extract matched points from original arrays
m1 = p1(:,p1ind);
m2 = p2(:,p2ind);
%-------------------------------------------------------------------------
% Function that does the work. This function builds a correlation matrix
% that holds the correlation strength of every point relative to every
% other point. While this seems a bit wasteful we need all this data if
% we want to find pairs of points that correlate maximally in both
% directions.
%
% This code assumes im1 and im2 have zero mean. This speeds the
% calculation of the normalised correlation measure.
function cormat = correlatiomatrix(im1, p1, im2, p2, w, dmax)
if mod(w, 2) == 0
error('Window size should be odd');
end
[rows1, npts1] = size(p1);
[rows2, npts2] = size(p2);
% Initialize correlation matrix values to -infinty
cormat = -ones(npts1,npts2)*Inf;
if rows1 ~= 2 | rows2 ~= 2
error('Feature points must be specified in 2xN arrays');
end
[im1rows, im1cols] = size(im1);
[im2rows, im2cols] = size(im2);
r = (w-1)/2; % 'radius' of correlation window
% For every feature point in the first image extract a window of data
% and correlate with a window corresponding to every feature point in
% the other image. Any feature point less than distance 'r' from the
% boundary of an image is not considered.
% Find indices of points that are distance 'r' or greater from
% boundary on image1 and image2;
n1ind = find(p1(1,:)>r & p1(1,:)<im1rows+1-r & ...
p1(2,:)>r & p1(2,:)<im1cols+1-r);
n2ind = find(p2(1,:)>r & p2(1,:)<im2rows+1-r & ...
p2(2,:)>r & p2(2,:)<im2cols+1-r);
for n1 = n1ind
% Generate window in 1st image
w1 = im1(p1(1,n1)-r:p1(1,n1)+r, p1(2,n1)-r:p1(2,n1)+r);
% Pre-normalise w1 to a unit vector.
w1 = w1./sqrt(sum(sum(w1.*w1)));
% Identify the indices of points in p2 that we need to consider.
if dmax == inf
n2indmod = n2ind; % We have to consider all of n2ind
else % Compute distances from p1(:,n1) to all available p2.
p1pad = repmat(p1(:,n1),1,length(n2ind));
dists2 = sum((p1pad-p2(:,n2ind)).^2);
% Find indices of points in p2 that are within distance dmax of
% p1(:,n1)
n2indmod = n2ind(find(dists2 < dmax^2));
end
% Calculate noralised correlation measure. Note this gives
% significantly better matches than the unnormalised one.
for n2 = n2indmod
% Generate window in 2nd image
w2 = im2(p2(1,n2)-r:p2(1,n2)+r, p2(2,n2)-r:p2(2,n2)+r);
cormat(n1,n2) = sum(sum(w1.*w2))/sqrt(sum(sum(w2.*w2)));
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_compile.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/vl_compile.m
| 5,060 |
utf_8
|
978f5189bb9b2a16db3368891f79aaa6
|
function vl_compile(compiler)
% VL_COMPILE Compile VLFeat MEX files
% VL_COMPILE() uses MEX() to compile VLFeat MEX files. This command
% works only under Windows and is used to re-build problematic
% binaries. The preferred method of compiling VLFeat on both UNIX
% and Windows is through the provided Makefiles.
%
% VL_COMPILE() only compiles the MEX files and assumes that the
% VLFeat DLL (i.e. the file VLFEATROOT/bin/win{32,64}/vl.dll) has
% already been built. This file is built by the Makefiles.
%
% By default VL_COMPILE() assumes that Visual C++ is the active
% MATLAB compiler. VL_COMPILE('lcc') assumes that the active
% compiler is LCC instead (see MEX -SETUP). Unfortunately LCC does
% not seem to be able to compile the latest versions of VLFeat due
% to bugs in the support of 64-bit integers. Therefore it is
% recommended to use Visual C++ instead.
%
% See also: VL_NOPREFIX(), VL_HELP().
% Authors: Andrea Vedadli, Jonghyun Choi
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 1, compiler = 'visualc' ; end
switch lower(compiler)
case 'visualc'
fprintf('%s: assuming that Visual C++ is the active compiler\n', mfilename) ;
useLcc = false ;
case 'lcc'
fprintf('%s: assuming that LCC is the active compiler\n', mfilename) ;
warning('LCC may fail to compile VLFeat. See help vl_compile.') ;
useLcc = true ;
otherwise
error('Unknown compiler ''%s''.', compiler)
end
vlDir = vl_root ;
toolboxDir = fullfile(vlDir, 'toolbox') ;
switch computer
case 'PCWIN'
fprintf('%s: compiling for PCWIN (32 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw32') ;
binwDir = fullfile(vlDir, 'bin', 'win32') ;
case 'PCWIN64'
fprintf('%s: compiling for PCWIN64 (64 bit)\n', mfilename);
mexwDir = fullfile(toolboxDir, 'mex', 'mexw64') ;
binwDir = fullfile(vlDir, 'bin', 'win64') ;
otherwise
error('The architecture is neither PCWIN nor PCWIN64. See help vl_compile.') ;
end
impLibPath = fullfile(binwDir, 'vl.lib') ;
libDir = fullfile(binwDir, 'vl.dll') ;
mkd(mexwDir) ;
% find the subdirectories of toolbox that we should process
subDirs = dir(toolboxDir) ;
subDirs = subDirs([subDirs.isdir]) ;
discard = regexp({subDirs.name}, '^(.|..|noprefix|mex.*)$', 'start') ;
keep = cellfun('isempty', discard) ;
subDirs = subDirs(keep) ;
subDirs = {subDirs.name} ;
% Copy support files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if ~exist(fullfile(binwDir, 'vl.dll'))
error('The VLFeat DLL (%s) could not be found. See help vl_compile.', ...
fullfile(binwDir, 'vl.dll')) ;
end
tmp = dir(fullfile(binwDir, '*.dll')) ;
supportFileNames = {tmp.name} ;
for fi = 1:length(supportFileNames)
name = supportFileNames{fi} ;
cp(fullfile(binwDir, name), ...
fullfile(mexwDir, name) ) ;
end
% Ensure implib for LCC ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if useLcc
lccImpLibDir = fullfile(mexwDir, 'lcc') ;
lccImpLibPath = fullfile(lccImpLibDir, 'VL.lib') ;
lccRoot = fullfile(matlabroot, 'sys', 'lcc', 'bin') ;
lccImpExePath = fullfile(lccRoot, 'lcc_implib.exe') ;
mkd(lccImpLibDir) ;
cp(fullfile(binwDir, 'vl.dll'), fullfile(lccImpLibDir, 'vl.dll')) ;
cmd = ['"' lccImpExePath '"', ' -u ', '"' fullfile(lccImpLibDir, 'vl.dll') '"'] ;
fprintf('Running:\n> %s\n', cmd) ;
curPath = pwd ;
try
cd(lccImpLibDir) ;
[d,w] = system(cmd) ;
if d, error(w); end
cd(curPath) ;
catch
cd(curPath) ;
error(lasterr) ;
end
end
% Compile each mex file ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for i = 1:length(subDirs)
thisDir = fullfile(toolboxDir, subDirs{i}) ;
fileNames = ls(fullfile(thisDir, '*.c'));
for f = 1:size(fileNames,1)
fileName = fileNames(f, :) ;
sp = strfind(fileName, ' ');
if length(sp) > 0, fileName = fileName(1:sp-1); end
filePath = fullfile(thisDir, fileName);
fprintf('MEX %s\n', filePath);
dot = strfind(fileName, '.');
mexFile = fullfile(mexwDir, [fileName(1:dot) 'dll']);
if exist(mexFile)
delete(mexFile)
end
cmd = {['-I' toolboxDir], ...
['-I' vlDir], ...
'-O', ...
'-outdir', mexwDir, ...
filePath } ;
if useLcc
cmd{end+1} = lccImpLibPath ;
else
cmd{end+1} = impLibPath ;
end
mex(cmd{:}) ;
end
end
% --------------------------------------------------------------------
function cp(src,dst)
% --------------------------------------------------------------------
if ~exist(dst,'file')
fprintf('Copying ''%s'' to ''%s''.\n', src,dst) ;
copyfile(src,dst) ;
end
% --------------------------------------------------------------------
function mkd(dst)
% --------------------------------------------------------------------
if ~exist(dst, 'dir')
fprintf('Creating directory ''%s''.', dst) ;
mkdir(dst) ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_noprefix.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/vl_noprefix.m
| 1,875 |
utf_8
|
97d8755f0ba139ac1304bc423d3d86d3
|
function vl_noprefix
% VL_NOPREFIX Create a prefix-less version of VLFeat commands
% VL_NOPREFIX() creats prefix-less stubs for VLFeat functions
% (e.g. SIFT for VL_SIFT). This function is seldom used as the stubs
% are included in the VLFeat binary distribution anyways. Moreover,
% on UNIX platforms, the stubs are generally constructed by the
% Makefile.
%
% See also: VL_COMPILE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
root = fileparts(which(mfilename)) ;
list = listMFilesX(root);
outDir = fullfile(root, 'noprefix') ;
if ~exist(outDir, 'dir')
mkdir(outDir) ;
end
for li = 1:length(list)
name = list(li).name(1:end-2) ; % remove .m
nname = name(4:end) ; % remove vl_
stubPath = fullfile(outDir, [nname '.m']) ;
fout = fopen(stubPath, 'w') ;
fprintf('Creating stub %s for %s\n', stubPath, nname) ;
fprintf(fout, 'function varargout = %s(varargin)\n', nname) ;
fprintf(fout, '%% %s Stub for %s\n', upper(nname), upper(name)) ;
fprintf(fout, '[varargout{1:nargout}] = %s(varargin{:})\n', name) ;
fclose(fout) ;
end
end
function list = listMFilesX(root)
list = struct('name', {}, 'path', {}) ;
files = dir(root) ;
for fi = 1:length(files)
name = files(fi).name ;
if files(fi).isdir
if any(regexp(name, '^(\.|\.\.|noprefix)$'))
continue ;
else
tmp = listMFilesX(fullfile(root, name)) ;
list = [list, tmp] ;
end
end
if any(regexp(name, '^vl_(demo|test).*m$'))
continue ;
elseif any(regexp(name, '^vl_(demo|setup|compile|help|root|noprefix)\.m$'))
continue ;
elseif any(regexp(name, '\.m$'))
list(end+1) = struct(...
'name', {name}, ...
'path', {fullfile(root, name)}) ;
end
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_pegasos.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/misc/vl_pegasos.m
| 2,837 |
utf_8
|
d5e0915c439ece94eb5597a07090b67d
|
% VL_PEGASOS [deprecated]
% VL_PEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_pegasos(X,Y,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
% parameters for vl_maketrainingset
setvarargin = {};
if (sum(strcmpi('HOMKERMAP',varargin)))
setvarargin{end+1} = 'HOMKERMAP';
setvarargin{end+1} = varargin{find(strcmpi('HOMKERMAP',varargin),1)+1};
varargin(find(strcmpi('HOMKERMAP',varargin),1)+1)=[];
varargin(find(strcmpi('HOMKERMAP',varargin),1))=[];
end
if (sum(strcmpi('KChi2',varargin)))
setvarargin{end+1} = 'KChi2';
varargin(find(strcmpi('KChi2',varargin),1))=[];
end
if (sum(strcmpi('KINTERS',varargin)))
setvarargin{end+1} = 'KINTERS';
varargin(find(strcmpi('KINTERS',varargin),1))=[];
end
if (sum(strcmpi('KL1',varargin)))
setvarargin{end+1} = 'KL1';
varargin(find(strcmpi('KL1',varargin),1))=[];
end
if (sum(strcmpi('KJS',varargin)))
setvarargin{end+1} = 'KJS';
varargin(find(strcmpi('KJS',varargin),1))=[];
end
if (sum(strcmpi('Period',varargin)))
setvarargin{end+1} = 'Period';
setvarargin{end+1} = varargin{find(strcmpi('Period',varargin),1)+1};
varargin(find(strcmpi('Period',varargin),1)+1)=[];
varargin(find(strcmpi('Period',varargin),1))=[];
end
if (sum(strcmpi('Window',varargin)))
setvarargin{end+1} = 'Window';
setvarargin{end+1} = varargin{find(strcmpi('Window',varargin),1)+1};
varargin(find(strcmpi('Window',varargin),1)+1)=[];
varargin(find(strcmpi('Window',varargin),1))=[];
end
if (sum(strcmpi('Gamma',varargin)))
setvarargin{end+1} = 'Gamma';
setvarargin{end+1} = varargin{find(strcmpi('Gamma',varargin),1)+1};
varargin(find(strcmpi('Gamma',varargin),1)+1)=[];
varargin(find(strcmpi('Gamma',varargin),1))=[];
end
setvarargin{:}
DATA = vl_maketrainingset(double(X),int8(Y),setvarargin{:});
DATA
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_pegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_svmpegasos.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/misc/vl_svmpegasos.m
| 1,178 |
utf_8
|
009c2a2b87a375d529ed1a4dbe3af59f
|
% VL_SVMPEGASOS [deprecated]
% VL_SVMPEGASOS is deprecated. Please use VL_SVMTRAIN() instead.
function [w b info] = vl_svmpegasos(DATA,LAMBDA, varargin)
% Verbose not supported
if (sum(strcmpi('Verbose',varargin)))
varargin(find(strcmpi('Verbose',varargin),1))=[];
fprintf('Option VERBOSE is no longer supported.\n');
end
% DiagnosticCallRef not supported
if (sum(strcmpi('DiagnosticCallRef',varargin)))
varargin(find(strcmpi('DiagnosticCallRef',varargin),1)+1)=[];
varargin(find(strcmpi('DiagnosticCallRef',varargin),1))=[];
fprintf('Option DIAGNOSTICCALLREF is no longer supported.\n Please follow the VLFeat tutorial on SVMs for more information on diagnostics\n');
end
% different default value for MaxIterations
if (sum(strcmpi('MaxIterations',varargin)) == 0)
varargin{end+1} = 'MaxIterations';
varargin{end+1} = ceil(10/LAMBDA);
end
% different default value for BiasMultiplier
if (sum(strcmpi('BiasMultiplier',varargin)) == 0)
varargin{end+1} = 'BiasMultiplier';
varargin{end+1} = 0;
end
[w b info] = vl_svmtrain(DATA,LAMBDA,varargin{:});
fprintf('\n vl_svmpegasos is DEPRECATED. Please use vl_svmtrain instead. \n\n');
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_override.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/misc/vl_override.m
| 4,654 |
utf_8
|
e233d2ecaeb68f56034a976060c594c5
|
function config = vl_override(config,update,varargin)
% VL_OVERRIDE Override structure subset
% CONFIG = VL_OVERRIDE(CONFIG, UPDATE) copies recursively the fileds
% of the structure UPDATE to the corresponding fields of the
% struture CONFIG.
%
% Usually CONFIG is interpreted as a list of paramters with their
% default values and UPDATE as a list of new paramete values.
%
% VL_OVERRIDE(..., 'Warn') prints a warning message whenever: (i)
% UPDATE has a field not found in CONFIG, or (ii) non-leaf values of
% CONFIG are overwritten.
%
% VL_OVERRIDE(..., 'Skip') skips fields of UPDATE that are not found
% in CONFIG instead of copying them.
%
% VL_OVERRIDE(..., 'CaseI') matches field names in a
% case-insensitive manner.
%
% Remark::
% Fields are copied at the deepest possible level. For instance,
% if CONFIG has fields A.B.C1=1 and A.B.C2=2, and if UPDATE is the
% structure A.B.C1=3, then VL_OVERRIDE() returns a strucuture with
% fields A.B.C1=3, A.B.C2=2. By contrast, if UPDATE is the
% structure A.B=4, then the field A.B is copied, and VL_OVERRIDE()
% returns the structure A.B=4 (specifying 'Warn' would warn about
% the fact that the substructure B.C1, B.C2 is being deleted).
%
% Remark::
% Two fields are matched if they correspond exactly. Specifically,
% two fileds A(IA).(FA) and B(IA).FB of two struct arrays A and B
% match if, and only if, (i) A and B have the same dimensions,
% (ii) IA == IB, and (iii) FA == FB.
%
% See also: VL_ARGPARSE(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
warn = false ;
skip = false ;
err = false ;
casei = false ;
if length(varargin) == 1 & ~ischar(varargin{1})
% legacy
warn = 1 ;
end
if ~warn & length(varargin) > 0
for i=1:length(varargin)
switch lower(varargin{i})
case 'warn'
warn = true ;
case 'skip'
skip = true ;
case 'err'
err = true ;
case 'argparse'
argparse = true ;
case 'casei'
casei = true ;
otherwise
error(sprintf('Unknown option ''%s''.',varargin{i})) ;
end
end
end
% if CONFIG is not a struct array just copy UPDATE verbatim
if ~isstruct(config)
config = update ;
return ;
end
% if CONFIG is a struct array but UPDATE is not, no match can be
% established and we simply copy UPDATE verbatim
if ~isstruct(update)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays, but have different
% dimensions then nom atch can be established and we simply copy
% UPDATE verbatim
if numel(update) ~= numel(config)
config = update ;
return ;
end
% if CONFIG and UPDATE are both struct arrays of the same
% dimension, we override recursively each field
for idx=1:numel(update)
fields = fieldnames(update) ;
for i = 1:length(fields)
updateFieldName = fields{i} ;
if casei
configFieldName = findFieldI(config, updateFieldName) ;
else
configFieldName = findField(config, updateFieldName) ;
end
if ~isempty(configFieldName)
config(idx).(configFieldName) = ...
vl_override(config(idx).(configFieldName), ...
update(idx).(updateFieldName)) ;
else
if warn
warning(sprintf('copied field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if err
error(sprintf('The field ''%s'' is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
if skip
if warn
warning(sprintf('skipping field ''%s'' which is in UPDATE but not in CONFIG', ...
updateFieldName)) ;
end
continue ;
end
config(idx).(updateFieldName) = update(idx).(updateFieldName) ;
end
end
end
% --------------------------------------------------------------------
function field = findFieldI(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmpi(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
% --------------------------------------------------------------------
function field = findField(S, matchField)
% --------------------------------------------------------------------
field = '' ;
fieldNames = fieldnames(S) ;
for fi=1:length(fieldNames)
if strcmp(fieldNames{fi}, matchField)
field = fieldNames{fi} ;
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_quickvis.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/quickshift/vl_quickvis.m
| 3,696 |
utf_8
|
27f199dad4c5b9c192a5dd3abc59f9da
|
function [Iedge dists map gaps] = vl_quickvis(I, ratio, kernelsize, maxdist, maxcuts)
% VL_QUICKVIS Create an edge image from a Quickshift segmentation.
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. RATIO controls the tradeoff
% between color consistency and spatial consistency (See VL_QUICKSEG) and
% KERNELSIZE controls the bandwidth of the density estimator (See VL_QUICKSEG,
% VL_QUICKSHIFT). MAXDIST is the maximum distance between neighbors which
% increase the density.
%
% VL_QUICKVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at
% most MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS) also
% returns the DIST thresholds that were chosen.
%
% IEDGE = VL_QUICKVIS(I, RATIO, KERNELSIZE, DISTS) will use the DISTS
% specified
%
% [IEDGE,DISTS,MAP,GAPS] = VL_QUICKVIS(I, RATIO, KERNELSIZE, MAXDIST, MAXCUTS)
% also returns the MAP and GAPS from VL_QUICKSHIFT.
%
% See Also: VL_QUICKSHIFT(), VL_QUICKSEG(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin == 4
dists = maxdist;
maxdist = max(dists);
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
else
[Iseg labels map gaps E] = vl_quickseg(I, ratio, kernelsize, maxdist);
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
[Iedge dists] = mapvis(map, gaps, dists);
function [Iedge dists] = mapvis(map, gaps, maxdist, maxcuts)
% MAPVIS Create an edge image from a Quickshift segmentation.
% IEDGE = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) creates an edge
% stability image from a Quickshift segmentation. MAXDIST is the maximum
% distance between neighbors which increase the density.
%
% MAPVIS takes at most MAXCUTS thresholds less than MAXDIST, forming at most
% MAXCUTS segmentations. The edges between regions in each of these
% segmentations are labeled in IEDGE, where the label corresponds to the
% largest DIST which preserves the edge.
%
% [IEDGE,DISTS] = MAPVIS(MAP, GAPS, MAXDIST, MAXCUTS) also returns the DIST
% thresholds that were chosen.
%
% IEDGE = MAPVIS(MAP, GAPS, DISTS) will use the DISTS specified
%
% See Also: VL_QUICKVIS, VL_QUICKSHIFT, VL_QUICKSEG
if nargin == 3
dists = maxdist;
maxdist = max(dists);
else
dists = unique(floor(gaps(:)));
dists = dists(2:end-1); % remove the inf thresh and the lowest level thresh
% throw away min region size instead of maxdist?
ind = find(dists < maxdist);
dists = dists(ind);
if length(dists) > maxcuts
ind = round(linspace(1,length(dists), maxcuts));
dists = dists(ind);
end
end
Iedge = zeros(size(map));
for i = 1:length(dists)
s = find(gaps >= dists(i));
mapdist = map;
mapdist(s) = s;
[mapped labels] = vl_flatmap(mapdist);
fprintf('%d/%d %d regions\n', i, length(dists), length(unique(mapped)))
borders = getborders(mapped);
Iedge(borders) = dists(i);
%Iedge(borders) = Iedge(borders) + 1;
%Iedge(borders) = i;
end
%%%%%%%%% GETBORDERS
function borders = getborders(map)
dx = conv2(map, [-1 1], 'same');
dy = conv2(map, [-1 1]', 'same');
borders = find(dx ~= 0 | dy ~= 0);
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_demo_aib.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/demo/vl_demo_aib.m
| 2,928 |
utf_8
|
590c6db09451ea608d87bfd094662cac
|
function vl_demo_aib
% VL_DEMO_AIB Test Agglomerative Information Bottleneck (AIB)
D = 4 ;
K = 20 ;
randn('state',0) ;
rand('state',0) ;
X1 = randn(2,300) ; X1(1,:) = X1(1,:) + 2 ;
X2 = randn(2,300) ; X2(1,:) = X2(1,:) - 2 ;
X3 = randn(2,300) ; X3(2,:) = X3(2,:) + 2 ;
figure(1) ; clf ; hold on ;
vl_plotframe(X1,'color','r') ;
vl_plotframe(X2,'color','g') ;
vl_plotframe(X3,'color','b') ;
axis equal ;
xlim([-4 4]);
ylim([-4 4]);
axis off ;
rectangle('position',D*[-1 -1 2 2])
vl_demo_print('aib_basic_data', .6) ;
C = 1:K*K ;
Pcx = zeros(3,K*K) ;
f1 = quantize(X1,D,K) ;
f2 = quantize(X2,D,K) ;
f3 = quantize(X3,D,K) ;
Pcx(1,:) = vl_binsum(Pcx(1,:), ones(size(f1)), f1) ;
Pcx(2,:) = vl_binsum(Pcx(2,:), ones(size(f2)), f2) ;
Pcx(3,:) = vl_binsum(Pcx(3,:), ones(size(f3)), f3) ;
Pcx = Pcx / sum(Pcx(:)) ;
[parents, cost] = vl_aib(Pcx) ;
cutsize = [K*K, 10, 3, 2, 1] ;
for i=1:length(cutsize)
[cut,map,short] = vl_aibcut(parents, cutsize(i)) ;
parents_cut(short > 0) = parents(short(short > 0)) ;
C = short(1:K*K+1) ; [drop1,drop2,C] = unique(C) ;
figure(i+1) ; clf ;
plotquantization(D,K,C) ; hold on ;
%plottree(D,K,parents_cut) ;
axis equal ;
axis off ;
title(sprintf('%d clusters', cutsize(i))) ;
vl_demo_print(sprintf('aib_basic_clust_%d',i),.6) ;
end
% --------------------------------------------------------------------
function f = quantize(X,D,K)
% --------------------------------------------------------------------
d = 2*D / K ;
j = round((X(1,:) + D) / d) ;
i = round((X(2,:) + D) / d) ;
j = max(min(j,K),1) ;
i = max(min(i,K),1) ;
f = sub2ind([K K],i,j) ;
% --------------------------------------------------------------------
function [i,j] = plotquantization(D,K,C)
% --------------------------------------------------------------------
hold on ;
cl = [[.3 .3 .3] ; .5*hsv(max(C)-1)+.5] ;
d = 2*D / K ;
for i=0:K-1
for j=0:K-1
patch(d*(j+[0 1 1 0])-D, ...
d*(i+[0 0 1 1])-D, ...
cl(C(j*K+i+1),:)) ;
end
end
% --------------------------------------------------------------------
function h = plottree(D,K,parents)
% --------------------------------------------------------------------
d = 2*D / K ;
C = zeros(2,2*K*K-1)+NaN ;
N = zeros(1,2*K*K-1) ;
for i=0:K-1
for j=0:K-1
C(:,j*K+i+1) = [d*j-D; d*i-D]+d/2 ;
N(:,j*K+i+1) = 1 ;
end
end
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
if all(isnan(C(:,i))), continue; end
if all(isnan(C(:,p)))
C(:,p) = C(:,i) / N(i) ;
else
C(:,p) = C(:,p) + C(:,i) / N(i) ;
end
N(p) = N(p) + 1 ;
end
C(1,:) = C(1,:) ./ N ;
C(2,:) = C(2,:) ./ N ;
xt = zeros(3, 2*length(parents)-1)+NaN ;
yt = zeros(3, 2*length(parents)-1)+NaN ;
for i=1:length(parents)
p = parents(i) ;
if p==0, continue ; end;
xt(1,i) = C(1,i) ; xt(2,i) = C(1,p) ;
yt(1,i) = C(2,i) ; yt(2,i) = C(2,p) ;
end
h=line(xt(:),yt(:),'linestyle','-','marker','.','linewidth',3) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_demo_alldist.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/demo/vl_demo_alldist.m
| 5,460 |
utf_8
|
6d008a64d93445b9d7199b55d58db7eb
|
function vl_demo_alldist
%
numRepetitions = 3 ;
numDimensions = 1000 ;
numSamplesRange = [300] ;
settingsRange = {{'alldist2', 'double', 'l2', }, ...
{'alldist', 'double', 'l2', 'nosimd'}, ...
{'alldist', 'double', 'l2' }, ...
{'alldist2', 'single', 'l2', }, ...
{'alldist', 'single', 'l2', 'nosimd'}, ...
{'alldist', 'single', 'l2' }, ...
{'alldist2', 'double', 'l1', }, ...
{'alldist', 'double', 'l1', 'nosimd'}, ...
{'alldist', 'double', 'l1' }, ...
{'alldist2', 'single', 'l1', }, ...
{'alldist', 'single', 'l1', 'nosimd'}, ...
{'alldist', 'single', 'l1' }, ...
{'alldist2', 'double', 'chi2', }, ...
{'alldist', 'double', 'chi2', 'nosimd'}, ...
{'alldist', 'double', 'chi2' }, ...
{'alldist2', 'single', 'chi2', }, ...
{'alldist', 'single', 'chi2', 'nosimd'}, ...
{'alldist', 'single', 'chi2' }, ...
{'alldist2', 'double', 'hell', }, ...
{'alldist', 'double', 'hell', 'nosimd'}, ...
{'alldist', 'double', 'hell' }, ...
{'alldist2', 'single', 'hell', }, ...
{'alldist', 'single', 'hell', 'nosimd'}, ...
{'alldist', 'single', 'hell' }, ...
{'alldist2', 'double', 'kl2', }, ...
{'alldist', 'double', 'kl2', 'nosimd'}, ...
{'alldist', 'double', 'kl2' }, ...
{'alldist2', 'single', 'kl2', }, ...
{'alldist', 'single', 'kl2', 'nosimd'}, ...
{'alldist', 'single', 'kl2' }, ...
{'alldist2', 'double', 'kl1', }, ...
{'alldist', 'double', 'kl1', 'nosimd'}, ...
{'alldist', 'double', 'kl1' }, ...
{'alldist2', 'single', 'kl1', }, ...
{'alldist', 'single', 'kl1', 'nosimd'}, ...
{'alldist', 'single', 'kl1' }, ...
{'alldist2', 'double', 'kchi2', }, ...
{'alldist', 'double', 'kchi2', 'nosimd'}, ...
{'alldist', 'double', 'kchi2' }, ...
{'alldist2', 'single', 'kchi2', }, ...
{'alldist', 'single', 'kchi2', 'nosimd'}, ...
{'alldist', 'single', 'kchi2' }, ...
{'alldist2', 'double', 'khell', }, ...
{'alldist', 'double', 'khell', 'nosimd'}, ...
{'alldist', 'double', 'khell' }, ...
{'alldist2', 'single', 'khell', }, ...
{'alldist', 'single', 'khell', 'nosimd'}, ...
{'alldist', 'single', 'khell' }, ...
} ;
%settingsRange = settingsRange(end-5:end) ;
styles = {} ;
for marker={'x','+','.','*','o'}
for color={'r','g','b','k','y'}
styles{end+1} = {'color', char(color), 'marker', char(marker)} ;
end
end
for ni=1:length(numSamplesRange)
for ti=1:length(settingsRange)
tocs = [] ;
for ri=1:numRepetitions
rand('state',ri) ;
randn('state',ri) ;
numSamples = numSamplesRange(ni) ;
settings = settingsRange{ti} ;
[tocs(end+1), D] = run_experiment(numDimensions, ...
numSamples, ...
settings) ;
end
means(ni,ti) = mean(tocs) ;
stds(ni,ti) = std(tocs) ;
if mod(ti-1,3) == 0
D0 = D ;
else
err = max(abs(D(:)-D0(:))) ;
fprintf('err %f\n', err) ;
if err > 1, keyboard ; end
end
end
end
if 0
figure(1) ; clf ; hold on ;
numStyles = length(styles) ;
for ti=1:length(settingsRange)
si = mod(ti - 1, numStyles) + 1 ;
h(ti) = plot(numSamplesRange, means(:,ti), styles{si}{:}) ;
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
errorbar(numSamplesRange, means(:,ti), stds(:,ti), 'linestyle', 'none') ;
end
end
for ti=1:length(settingsRange)
leg{ti} = sprintf('%s ', settingsRange{ti}{:}) ;
end
figure(1) ; clf ;
barh(means(end,:)) ;
set(gca,'ytick', 1:length(leg), 'yticklabel', leg,'ydir','reverse') ;
xlabel('Time [s]') ;
function [elaps, D] = run_experiment(numDimensions, numSamples, settings)
distType = 'l2' ;
algType = 'alldist' ;
classType = 'double' ;
useSimd = true ;
for si=1:length(settings)
arg = settings{si} ;
switch arg
case {'l1', 'l2', 'chi2', 'hell', 'kl2', 'kl1', 'kchi2', 'khell'}
distType = arg ;
case {'alldist', 'alldist2'}
algType = arg ;
case {'single', 'double'}
classType = arg ;
case 'simd'
useSimd = true ;
case 'nosimd'
useSimd = false ;
otherwise
assert(false) ;
end
end
X = rand(numDimensions, numSamples) ;
X(X < .3) = 0 ;
switch classType
case 'double'
case 'single'
X = single(X) ;
end
vl_simdctrl(double(useSimd)) ;
switch algType
case 'alldist'
tic ; D = vl_alldist(X, distType) ; elaps = toc ;
case 'alldist2'
tic ; D = vl_alldist2(X, distType) ; elaps = toc ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_demo_svm.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/demo/vl_demo_svm.m
| 1,235 |
utf_8
|
7cf6b3504e4fc2cbd10ff3fec6e331a7
|
% VL_DEMO_SVM Demo: SVM: 2D linear learning
function vl_demo_svm
y=[];X=[];
% Load training data X and their labels y
load('vl_demo_svm_data.mat')
Xp = X(:,y==1);
Xn = X(:,y==-1);
figure
plot(Xn(1,:),Xn(2,:),'*r')
hold on
plot(Xp(1,:),Xp(2,:),'*b')
axis equal ;
vl_demo_print('svm_training') ;
% Parameters
lambda = 0.01 ; % Regularization parameter
maxIter = 1000 ; % Maximum number of iterations
energy = [] ;
% Diagnostic function
function diagnostics(svm)
energy = [energy [svm.objective ; svm.dualObjective ; svm.dualityGap ] ] ;
end
% Training the SVM
energy = [] ;
[w b info] = vl_svmtrain(X, y, lambda,...
'MaxNumIterations',maxIter,...
'DiagnosticFunction',@diagnostics,...
'DiagnosticFrequency',1)
% Visualisation
eq = [num2str(w(1)) '*x+' num2str(w(2)) '*y+' num2str(b)];
line = ezplot(eq, [-0.9 0.9 -0.9 0.9]);
set(line, 'Color', [0 0.8 0],'linewidth', 2);
vl_demo_print('svm_training_result') ;
figure
hold on
plot(energy(1,:),'--b') ;
plot(energy(2,:),'-.g') ;
plot(energy(3,:),'r') ;
legend('Primal objective','Dual objective','Duality gap')
xlabel('Diagnostics iteration')
ylabel('Energy')
vl_demo_print('svm_energy') ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_demo_kdtree_sift.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/demo/vl_demo_kdtree_sift.m
| 6,832 |
utf_8
|
e676f80ac330a351f0110533c6ebba89
|
function vl_demo_kdtree_sift
% VL_DEMO_KDTREE_SIFT
% Demonstrates the use of a kd-tree forest to match SIFT
% features. If FLANN is present, this function runs a comparison
% against it.
% AUTORIGHS
rand('state',0) ;
randn('state',0);
do_median = 0 ;
do_mean = 1 ;
% try to setup flann
if ~exist('flann_search', 'file')
if exist(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab'))
addpath(fullfile(vl_root, 'opt', 'flann', 'build', 'matlab')) ;
end
end
do_flann = exist('nearest_neighbors') == 3 ;
if ~do_flann
warning('FLANN not found. Comparison disabled.') ;
end
maxNumComparisonsRange = [1 10 50 100 200 300 400] ;
numTreesRange = [1 2 5 10] ;
% get data (SIFT features)
im1 = imread(fullfile(vl_root, 'data', 'roofs1.jpg')) ;
im2 = imread(fullfile(vl_root, 'data', 'roofs2.jpg')) ;
im1 = single(rgb2gray(im1)) ;
im2 = single(rgb2gray(im2)) ;
[f1,d1] = vl_sift(im1,'firstoctave',-1,'floatdescriptors','verbose') ;
[f2,d2] = vl_sift(im2,'firstoctave',-1,'floatdescriptors','verbose') ;
% add some noise to make matches unique
d1 = single(d1) + rand(size(d1)) ;
d2 = single(d2) + rand(size(d2)) ;
% match exhaustively to get the ground truth
elapsedDirect = tic ;
D = vl_alldist(d1,d2) ;
[drop, best] = min(D, [], 1) ;
elapsedDirect = toc(elapsedDirect) ;
for ti=1:length(numTreesRange)
for vi=1:length(maxNumComparisonsRange)
v = maxNumComparisonsRange(vi) ;
t = numTreesRange(ti) ;
if do_median
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'median', ...
'numtrees', t) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons',v) ;
elapsedKD_median(vi,ti) = toc ;
errors_median(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_median(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_mean
tic ;
kdtree = vl_kdtreebuild(d1, ...
'verbose', ...
'thresholdmethod', 'mean', ...
'numtrees', t) ;
%kdtree = readflann(kdtree, '/tmp/flann.txt') ;
%checkx(kdtree, d1, 1, 1) ;
[i, d] = vl_kdtreequery(kdtree, d1, d2, ...
'verbose', ...
'maxcomparisons', v) ;
elapsedKD_mean(vi,ti) = toc ;
errors_mean(vi,ti) = sum(double(i) ~= best) / length(best) ;
errorsD_mean(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
if do_flann
tic ;
[i, d] = flann_search(d1, d2, 1, struct('algorithm','kdtree', ...
'trees', t, ...
'checks', v));
ifla = i ;
elapsedKD_flann(vi,ti) = toc;
errors_flann(vi,ti) = sum(i ~= best) / length(best) ;
errorsD_flann(vi,ti) = mean(abs(d - drop) ./ drop) ;
end
end
end
figure(1) ; clf ;
leg = {} ;
hnd = [] ;
sty = {{'color','r'},{'color','g'},...
{'color','b'},{'color','c'},...
{'color','k'}} ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errors_median(:,ti),'-*',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errors_mean(:,ti), '-o',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errors_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('percentage of incorrect matches (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_incorrect',.6) ;
figure(2) ; clf ;
leg = {} ;
hnd = [] ;
for ti=1:length(numTreesRange)
s = sty{mod(ti,length(sty))+1} ;
if do_median
h1=loglog(elapsedDirect ./ elapsedKD_median(:,ti),100*errorsD_median(:,ti),'*-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat median (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h1 ;
end
if do_mean
h2=loglog(elapsedDirect ./ elapsedKD_mean(:,ti), 100*errorsD_mean(:,ti), 'o-',s{:}) ; hold on ;
leg{end+1} = sprintf('VLFeat (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h2 ;
end
if do_flann
h3=loglog(elapsedDirect ./ elapsedKD_flann(:,ti), 100*errorsD_flann(:,ti), '+--',s{:}) ; hold on ;
leg{end+1} = sprintf('FLANN (%d tr.)', numTreesRange(ti)) ;
hnd(end+1) = h3 ;
end
end
set([hnd], 'linewidth', 2) ;
xlabel('speedup over linear search (log times)') ;
ylabel('relative overestimation of minmium distannce (%)') ;
h=legend(hnd, leg{:}, 'location', 'southeast') ;
set(h,'fontsize',8) ;
grid on ;
axis square ;
vl_demo_print('kdtree_sift_distortion',.6) ;
% --------------------------------------------------------------------
function checkx(kdtree, X, t, n, mib, mab)
% --------------------------------------------------------------------
if nargin <= 4
mib = -inf * ones(size(X,1),1) ;
mab = +inf * ones(size(X,1),1) ;
end
lc = kdtree.trees(t).nodes.lowerChild(n) ;
uc = kdtree.trees(t).nodes.upperChild(n) ;
if lc < 0
for i=-lc:-uc-1
di = kdtree.trees(t).dataIndex(i) ;
if any(X(:,di) > mab)
error('a') ;
end
if any(X(:,di) < mib)
error('b') ;
end
end
return
end
i = kdtree.trees(t).nodes.splitDimension(n) ;
v = kdtree.trees(t).nodes.splitThreshold(n) ;
mab_ = mab ;
mab_(i) = min(mab(i), v) ;
checkx(kdtree, X, t, lc, mib, mab_) ;
mib_ = mib ;
mib_(i) = max(mib(i), v) ;
checkx(kdtree, X, t, uc, mib_, mab) ;
% --------------------------------------------------------------------
function kdtree = readflann(kdtree, path)
% --------------------------------------------------------------------
data = textread(path)' ;
for i=1:size(data,2)
nodeIds = data(1,:) ;
ni = find(nodeIds == data(1,i)) ;
if ~isnan(data(2,i))
% internal node
li = find(nodeIds == data(4,i)) ;
ri = find(nodeIds == data(5,i)) ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(li) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(ri) ;
kdtree.trees(1).nodes.splitThreshold(ni) = single(data(2,i)) ;
kdtree.trees(1).nodes.splitDimension(ni) = single(data(3,i)+1) ;
else
di = data(3,i) + 1 ;
kdtree.trees(1).nodes.lowerChild(ni) = int32(- di) ;
kdtree.trees(1).nodes.upperChild(ni) = int32(- di - 1) ;
end
kdtree.trees(1).dataIndex = uint32(1:kdtree.numData) ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_impattern.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/imop/vl_impattern.m
| 6,876 |
utf_8
|
1716a4d107f0186be3d11c647bc628ce
|
function im = vl_impattern(varargin)
% VL_IMPATTERN Generate an image from a stock pattern
% IM=VLPATTERN(NAME) returns an instance of the specified
% pattern. These stock patterns are useful for testing algoirthms.
%
% All generated patterns are returned as an image of class
% DOUBLE. Both gray-scale and colour images have range in [0,1].
%
% VL_IMPATTERN() without arguments shows a gallery of the stock
% patterns. The following patterns are supported:
%
% Wedge::
% The image of a wedge.
%
% Cone::
% The image of a cone.
%
% SmoothChecker::
% A checkerboard with Gaussian filtering on top. Use the
% option-value pair 'sigma', SIGMA to specify the standard
% deviation of the smoothing and the pair 'step', STEP to specfity
% the checker size in pixels.
%
% ThreeDotsSquare::
% A pattern with three small dots and two squares.
%
% UniformNoise::
% Random i.i.d. noise.
%
% Blobs:
% Gaussian blobs of various sizes and anisotropies.
%
% Blobs1:
% Gaussian blobs of various orientations and anisotropies.
%
% Blob:
% One Gaussian blob. Use the option-value pairs 'sigma',
% 'orientation', and 'anisotropy' to specify the respective
% parameters. 'sigma' is the scalar standard deviation of an
% isotropic blob (the image domain is the rectangle
% [-1,1]^2). 'orientation' is the clockwise rotation (as the Y
% axis points downards). 'anisotropy' (>= 1) is the ratio of the
% the largest over the smallest axis of the blob (the smallest
% axis length is set by 'sigma'). Set 'cut' to TRUE to cut half
% half of the blob.
%
% A stock image::
% Any of 'box', 'roofs1', 'roofs2', 'river1', 'river2', 'spotted'.
%
% All pattern accept a SIZE parameter [WIDTH,HEIGHT]. For all but
% the stock images, the default size is [128,128].
% Author: Andrea Vedaldi
% Copyright (C) 2012 Andrea Vedaldi.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin > 0
pattern=varargin{1} ;
varargin=varargin(2:end) ;
else
pattern = 'gallery' ;
end
patterns = {'wedge','cone','smoothChecker','threeDotsSquare', ...
'blob', 'blobs', 'blobs1', ...
'box', 'roofs1', 'roofs2', 'river1', 'river2'} ;
% spooling
switch lower(pattern)
case 'wedge', im = wedge(varargin) ;
case 'cone', im = cone(varargin) ;
case 'smoothchecker', im = smoothChecker(varargin) ;
case 'threedotssquare', im = threeDotSquare(varargin) ;
case 'uniformnoise', im = uniformNoise(varargin) ;
case 'blob', im = blob(varargin) ;
case 'blobs', im = blobs(varargin) ;
case 'blobs1', im = blobs1(varargin) ;
case {'box','roofs1','roofs2','river1','river2','spots'}
im = stockImage(pattern, varargin) ;
case 'gallery'
clf ;
num = numel(patterns) ;
for p = 1:num
vl_tightsubplot(num,p,'box','outer') ;
imagesc(vl_impattern(patterns{p}),[0 1]) ;
axis image off ;
title(patterns{p}) ;
end
colormap gray ;
return ;
otherwise
error('Unknown patter ''%s''.', pattern) ;
end
if nargout == 0
clf ; imagesc(im) ; hold on ;
colormap gray ; axis image off ;
title(pattern) ;
clear im ;
end
function [u,v,opts,args] = commonOpts(args)
opts.size = [128 128] ;
[opts,args] = vl_argparse(opts, args) ;
ur = linspace(-1,1,opts.size(2)) ;
vr = linspace(-1,1,opts.size(1)) ;
[u,v] = meshgrid(ur,vr);
function im = wedge(args)
[u,v,opts,args] = commonOpts(args) ;
im = abs(u) + abs(v) > (1/4) ;
im(v < 0) = 0 ;
function im = cone(args)
[u,v,opts,args] = commonOpts(args) ;
im = sqrt(u.^2+v.^2) ;
im = im / max(im(:)) ;
function im = smoothChecker(args)
opts.size = [128 128] ;
opts.step = 16 ;
opts.sigma = 2 ;
opts = vl_argparse(opts, args) ;
[u,v] = meshgrid(0:opts.size(1)-1, 0:opts.size(2)-1) ;
im = xor((mod(u,opts.step*2) < opts.step),...
(mod(v,opts.step*2) < opts.step)) ;
im = double(im) ;
im = vl_imsmooth(im, opts.sigma) ;
function im = threeDotSquare(args)
[u,v,opts,args] = commonOpts(args) ;
im = ones(size(u)) ;
im(-2/3<u & u<2/3 & -2/3<v & v<2/3) = .75 ;
im(-1/3<u & u<1/3 & -1/3<v & v<1/3) = .50 ;
[drop,i] = min(abs(v(:,1))) ;
[drop,j1] = min(abs(u(1,:)-1/6)) ;
[drop,j2] = min(abs(u(1,:))) ;
[drop,j3] = min(abs(u(1,:)+1/6)) ;
im(i,j1) = 0 ;
im(i,j2) = 0 ;
im(i,j3) = 0 ;
function im = blobs(args)
[u,v,opts,args] = commonOpts(args) ;
im = zeros(size(u)) ;
num = 5 ;
square = 2 / num ;
sigma = square / 2 / 3 ;
scales = logspace(log10(0.5), log10(1), num) ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
A = sigma * diag([scales(i) scales(i)/skews(j)]) * [1 -1 ; 1 1] / sqrt(2) ;
C = inv(A'*A) ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = blob(args)
[u,v,opts,args] = commonOpts(args) ;
opts.sigma = 0.15 ;
opts.anisotropy = .5 ;
opts.orientation = 2/3 * pi ;
opts.cut = false ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
th = opts.orientation ;
R = [cos(th) -sin(th) ; sin(th) cos(th)] ;
A = opts.sigma * R * diag([opts.anisotropy 1]) ;
T = [0;0] ;
[x,y] = vl_waffine(inv(A),-inv(A)*T,u,v) ;
im = exp(-0.5 *(x.^2 + y.^2)) ;
if opts.cut
im = im .* double(x > 0) ;
end
function im = blobs1(args)
[u,v,opts,args] = commonOpts(args) ;
opts.number = 5 ;
opts.sigma = [] ;
opts = vl_argparse(opts, args) ;
im = zeros(size(u)) ;
square = 2 / opts.number ;
num = opts.number ;
if isempty(opts.sigma)
sigma = 1/6 * square ;
else
sigma = opts.sigma * square ;
end
rotations = linspace(0,pi,num+1) ;
rotations(end) = [] ;
skews = linspace(1,2,num) ;
for i=1:num
for j=1:num
cy = (i-1) * square + square/2 - 1;
cx = (j-1) * square + square/2 - 1;
th = rotations(i) ;
R = [cos(th) -sin(th); sin(th) cos(th)] ;
A = sigma * R * diag([1 1/skews(j)]) ;
C = inv(A*A') ;
x = u - cx ;
y = v - cy ;
im = im + exp(-0.5 *(x.*x*C(1,1) + y.*y*C(2,2) + 2*x.*y*C(1,2))) ;
end
end
im = im / max(im(:)) ;
function im = uniformNoise(args)
opts.size = [128 128] ;
opts.seed = 1 ;
opts = vl_argparse(opts, args) ;
state = vl_twister('state') ;
vl_twister('state',opts.seed) ;
im = vl_twister(opts.size([2 1])) ;
vl_twister('state',state) ;
function im = stockImage(pattern,args)
opts.size = [] ;
opts = vl_argparse(opts, args) ;
switch pattern
case 'river1', path='river1.jpg' ;
case 'river2', path='river2.jpg' ;
case 'roofs1', path='roofs1.jpg' ;
case 'roofs2', path='roofs2.jpg' ;
case 'box', path='box.pgm' ;
case 'spots', path='spots.jpg' ;
end
im = imread(fullfile(vl_root,'data',path)) ;
im = im2double(im) ;
if ~isempty(opts.size)
im = imresize(im, opts.size) ;
im = max(im,0) ;
im = min(im,1) ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_tpsu.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/imop/vl_tpsu.m
| 1,755 |
utf_8
|
09f36e1a707c069b375eb2817d0e5f13
|
function [U,dU,delta]=vl_tpsu(X,Y)
% VL_TPSU Compute the U matrix of a thin-plate spline transformation
% U=VL_TPSU(X,Y) returns the matrix
%
% [ U(|X(:,1) - Y(:,1)|) ... U(|X(:,1) - Y(:,N)|) ]
% [ ]
% [ U(|X(:,M) - Y(:,1)|) ... U(|X(:,M) - Y(:,N)|) ]
%
% where X is a 2xM matrix and Y a 2xN matrix of points and U(r) is
% the opposite -r^2 log(r^2) of the radial basis function of the
% thin plate spline specified by X and Y.
%
% [U,dU]=vl_tpsu(x,y) returns the derivatives of the columns of U with
% respect to the parameters Y. The derivatives are arranged in a
% Mx2xN array, one layer per column of U.
%
% See also: VL_TPS(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if exist('tpsumx')
U = tpsumx(X,Y) ;
else
M=size(X,2) ;
N=size(Y,2) ;
% Faster than repmat, but still fairly slow
r2 = ...
(X( ones(N,1), :)' - Y( ones(1,M), :)).^2 + ...
(X( 1+ones(N,1), :)' - Y(1+ones(1,M), :)).^2 ;
U = - rb(r2) ;
end
if nargout > 1
M=size(X,2) ;
N=size(Y,2) ;
dx = X( ones(N,1), :)' - Y( ones(1,M), :) ;
dy = X(1+ones(N,1), :)' - Y(1+ones(1,M), :) ;
r2 = (dx.^2 + dy.^2) ;
r = sqrt(r2) ;
coeff = drb(r)./(r+eps) ;
dU = reshape( [coeff .* dx ; coeff .* dy], M, 2, N) ;
end
% The radial basis function
function y = rb(r2)
y = zeros(size(r2)) ;
sel = find(r2 ~= 0) ;
y(sel) = - r2(sel) .* log(r2(sel)) ;
% The derivative of the radial basis function
function y = drb(r)
y = zeros(size(r)) ;
sel = find(r ~= 0) ;
y(sel) = - 4 * r(sel) .* log(r(sel)) - 2 * r(sel) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_xyz2lab.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/imop/vl_xyz2lab.m
| 1,570 |
utf_8
|
09f95a6f9ae19c22486ec1157357f0e3
|
function J=vl_xyz2lab(I,il)
% VL_XYZ2LAB Convert XYZ color space to LAB
% J = VL_XYZ2LAB(I) converts the image from XYZ format to LAB format.
%
% VL_XYZ2LAB(I,IL) uses one of the illuminants A, B, C, E, D50, D55,
% D65, D75, D93. The default illuminatn is E.
%
% See also: VL_XYZ2LUV(), VL_HELP().
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
if nargin < 2
il='E' ;
end
switch lower(il)
case 'a'
xw = 0.4476 ;
yw = 0.4074 ;
case 'b'
xw = 0.3324 ;
yw = 0.3474 ;
case 'c'
xw = 0.3101 ;
yw = 0.3162 ;
case 'e'
xw = 1/3 ;
yw = 1/3 ;
case 'd50'
xw = 0.3457 ;
yw = 0.3585 ;
case 'd55'
xw = 0.3324 ;
yw = 0.3474 ;
case 'd65'
xw = 0.312713 ;
yw = 0.329016 ;
case 'd75'
xw = 0.299 ;
yw = 0.3149 ;
case 'd93'
xw = 0.2848 ;
yw = 0.2932 ;
end
J=zeros(size(I)) ;
% Reference white
Yw = 1.0 ;
Xw = xw/yw ;
Zw = (1-xw-yw)/yw * Yw ;
% XYZ components
X = I(:,:,1) ;
Y = I(:,:,2) ;
Z = I(:,:,3) ;
x = X/Xw ;
y = Y/Yw ;
z = Z/Zw ;
L = 116 * f(y) - 16 ;
a = 500*(f(x) - f(y)) ;
b = 200*(f(y) - f(z)) ;
J = cat(3,L,a,b) ;
% --------------------------------------------------------------------
function b=f(a)
% --------------------------------------------------------------------
sp = find(a > 0.00856) ;
sm = find(a <= 0.00856) ;
k = 903.3 ;
b=zeros(size(a)) ;
b(sp) = a(sp).^(1/3) ;
b(sm) = (k*a(sm) + 16)/116 ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_gmm.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_gmm.m
| 1,332 |
utf_8
|
76782cae6c98781c6c38d4cbf5549d94
|
function results = vl_test_gmm(varargin)
% VL_TEST_GMM
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
end
function s = setup()
randn('state',0) ;
s.X = randn(128, 1000) ;
end
function test_multithreading(s)
dataTypes = {'single','double'} ;
for dataType = dataTypes
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
vl_threads(0) ;
[means, covariances, priors, ll, posteriors] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_twister('state',0) ;
vl_threads(1) ;
[means_, covariances_, priors_, ll_, posteriors_] = ...
vl_gmm(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Initialization', 'rand') ;
vl_assert_almost_equal(means, means_, 1e-2) ;
vl_assert_almost_equal(covariances, covariances_, 1e-2) ;
vl_assert_almost_equal(priors, priors_, 1e-2) ;
vl_assert_almost_equal(ll, ll_, 1e-2 * abs(ll)) ;
vl_assert_almost_equal(posteriors, posteriors_, 1e-2) ;
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_twister.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_twister.m
| 1,251 |
utf_8
|
2bfb5a30cbd6df6ac80c66b73f8646da
|
function results = vl_test_twister(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_illegal_args()
vl_assert_exception(@() vl_twister(-1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister(1, -1), 'vl:invalidArgument') ;
vl_assert_exception(@() vl_twister([1, -1]), 'vl:invalidArgument') ;
function test_seed_by_scalar()
rand('twister',1) ; a = rand ;
vl_twister('state',1) ; b = vl_twister ;
vl_assert_equal(a,b,'seed by scalar + VL_TWISTER()') ;
function test_get_set_state()
rand('twister',1) ; a = rand('twister') ;
vl_twister('state',1) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'read state') ;
a(1) = a(1) + 1 ;
vl_twister('state',a) ; b = vl_twister('state') ;
vl_assert_equal(a,b,'set state') ;
function test_multi_dimensions()
b = rand('twister') ;
rand('twister',b) ;
vl_twister('state',b) ;
a=rand([1 2 3 4 5]) ;
b=vl_twister([1 2 3 4 5]) ;
vl_assert_equal(a,b,'VL_TWISTER([M N P ...])') ;
function test_multi_multi_args()
rand('twister',1) ; a=rand(1, 2, 3, 4, 5) ;
vl_twister('state',1) ; b=vl_twister(1, 2, 3, 4, 5) ;
vl_assert_equal(a,b,'VL_TWISTER(M, N, P, ...)') ;
function test_square()
rand('twister',1) ; a=rand(10) ;
vl_twister('state',1) ; b=vl_twister(10) ;
vl_assert_equal(a,b,'VL_TWISTER(N)') ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_kdtree.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_kdtree.m
| 2,449 |
utf_8
|
9d7ad2b435a88c22084b38e5eb5f9eb9
|
function results = vl_test_kdtree(varargin)
% VL_TEST_KDTREE
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = single(randn(10, 1000)) ;
s.Q = single(randn(10, 10)) ;
function test_nearest(s)
for tmethod = {'median', 'mean'}
for type = {@single, @double}
conv = type{1} ;
tmethod = char(tmethod) ;
X = conv(s.X) ;
Q = conv(s.Q) ;
tree = vl_kdtreebuild(X,'ThresholdMethod', tmethod) ;
[nn, d2] = vl_kdtreequery(tree, X, Q) ;
D2 = vl_alldist2(X, Q, 'l2') ;
[d2_, nn_] = min(D2) ;
vl_assert_equal(...
nn,uint32(nn_),...
'incorrect nns: type=%s th. method=%s', func2str(conv), tmethod) ;
vl_assert_almost_equal(...
d2,d2_,...
'incorrect distances: type=%s th. method=%s', func2str(conv), tmethod) ;
end
end
function test_nearests(s)
numNeighbors = 7 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
vl_assert_equal(nn,uint32(nn_)) ;
vl_assert_almost_equal(d2,d2_) ;
function test_ann(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 50 ;
tree = vl_kdtreebuild(s.X) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
function test_ann_forest(s)
vl_twister('state', 1) ;
numNeighbors = 7 ;
maxComparisons = numNeighbors * 25 ;
numTrees = 5 ;
tree = vl_kdtreebuild(s.X, 'numTrees', 5) ;
[nn, d2] = vl_kdtreequery(tree, s.X, s.Q, ...
'numNeighbors', numNeighbors, ...
'maxComparisons', maxComparisons) ;
D2 = vl_alldist2(s.X, s.Q, 'l2') ;
[d2_, nn_] = sort(D2) ;
d2_ = d2_(1:numNeighbors, :) ;
nn_ = nn_(1:numNeighbors, :) ;
for i=1:size(s.Q,2)
overlap = numel(intersect(nn(:,i), nn_(:,i))) / ...
numel(union(nn(:,i), nn_(:,i))) ;
assert(overlap > 0.6, 'ANN did not return enough correct nearest neighbors') ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_imwbackward.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_imwbackward.m
| 514 |
utf_8
|
33baa0784c8f6f785a2951d7f1b49199
|
function results = vl_test_imwbackward(varargin)
% VL_TEST_IMWBACKWARD
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
function test_identity(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_almost_equal(s.I, vl_imwbackward(xr,yr,s.I,x,y)) ;
function test_invalid_args(s)
xr = 1:size(s.I,2) ;
yr = 1:size(s.I,1) ;
[x,y] = meshgrid(xr,yr) ;
vl_assert_exception(@() vl_imwbackward(xr,yr,single(s.I),x,y), 'vl:invalidArgument') ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_alphanum.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_alphanum.m
| 1,624 |
utf_8
|
2da2b768c2d0f86d699b8f31614aa424
|
function results = vl_test_alphanum(varargin)
% VL_TEST_ALPHANUM
vl_test_init ;
function s = setup()
s.strings = ...
{'1000X Radonius Maximus','10X Radonius','200X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','Allegia 50 Clasteron','Allegia 500 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 6R Clasteron','Alpha 100','Alpha 2','Alpha 200','Alpha 2A','Alpha 2A-8000','Alpha 2A-900','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 5000','Callisto Morphamax 600','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 700','Callisto Morphamax 7000','Xiph Xlater 10000','Xiph Xlater 2000','Xiph Xlater 300','Xiph Xlater 40','Xiph Xlater 5','Xiph Xlater 50','Xiph Xlater 500','Xiph Xlater 5000','Xiph Xlater 58'} ;
s.sortedStrings = ...
{'10X Radonius','20X Radonius','20X Radonius Prime','30X Radonius','40X Radonius','200X Radonius','1000X Radonius Maximus','Allegia 6R Clasteron','Allegia 50 Clasteron','Allegia 50B Clasteron','Allegia 51 Clasteron','Allegia 500 Clasteron','Alpha 2','Alpha 2A','Alpha 2A-900','Alpha 2A-8000','Alpha 100','Alpha 200','Callisto Morphamax','Callisto Morphamax 500','Callisto Morphamax 600','Callisto Morphamax 700','Callisto Morphamax 5000','Callisto Morphamax 6000 SE','Callisto Morphamax 6000 SE2','Callisto Morphamax 7000','Xiph Xlater 5','Xiph Xlater 40','Xiph Xlater 50','Xiph Xlater 58','Xiph Xlater 300','Xiph Xlater 500','Xiph Xlater 2000','Xiph Xlater 5000','Xiph Xlater 10000'} ;
function test_basic(s)
sorted = vl_alphanum(s.strings) ;
assert(isequal(sorted,s.sortedStrings)) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_printsize.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_printsize.m
| 1,447 |
utf_8
|
0f0b6437c648b7a2e1310900262bd765
|
function results = vl_test_printsize(varargin)
% VL_TEST_PRINTSIZE
vl_test_init ;
function s = setup()
s.fig = figure(1) ;
s.usletter = [8.5, 11] ; % inches
s.a4 = [8.26772, 11.6929] ;
clf(s.fig) ; plot(1:10) ;
function teardown(s)
close(s.fig) ;
function test_basic(s)
for sigma = [1 0.5 0.2]
vl_printsize(s.fig, sigma) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), sigma*s.usletter(1), 1e-4) ;
vl_assert_almost_equal(pos(1), 0, 1e-4) ;
vl_assert_almost_equal(pos(3), sigma*s.usletter(1), 1e-4) ;
end
function test_papertype(s)
vl_printsize(s.fig, 1, 'papertype', 'a4') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.a4(1), 1e-4) ;
function test_margin(s)
m = 0.5 ;
vl_printsize(s.fig, 1, 'margin', m) ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(1), s.usletter(1) * (1 + 2*m), 1e-4) ;
vl_assert_almost_equal(pos(1), s.usletter(1) * m, 1e-4) ;
function test_reference(s)
sigma = 1 ;
vl_printsize(s.fig, 1, 'reference', 'vertical') ;
set(1, 'PaperUnits', 'inches') ;
siz = get(1, 'PaperSize') ;
pos = get(1, 'PaperPosition') ;
vl_assert_almost_equal(siz(2), sigma*s.usletter(2), 1e-4) ;
vl_assert_almost_equal(pos(2), 0, 1e-4) ;
vl_assert_almost_equal(pos(4), sigma*s.usletter(2), 1e-4) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_cummax.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_cummax.m
| 762 |
utf_8
|
3dddb5736dfffacdd94b156e67cb9c14
|
function results = vl_test_cummax(varargin)
% VL_TEST_CUMMAX
vl_test_init ;
function test_basic()
vl_assert_almost_equal(...
vl_cummax(1), 1) ;
vl_assert_almost_equal(...
vl_cummax([1 2 3 4], 2), [1 2 3 4]) ;
function test_multidim()
a = [1 2 3 4 3 2 1] ;
b = [1 2 3 4 4 4 4] ;
for k=1:6
dims = ones(1,6) ;
dims(k) = numel(a) ;
a = reshape(a, dims) ;
b = reshape(b, dims) ;
vl_assert_almost_equal(...
vl_cummax(a, k), b) ;
end
function test_storage_classes()
types = {@double, @single, @int64, @uint64, ...
@int32, @uint32, @int16, @uint16, ...
@int8, @uint8} ;
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_cummax(a(eye(3))), a(toeplitz([1 1 1], [1 0 0 ]))) ;
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_imintegral.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_imintegral.m
| 1,429 |
utf_8
|
4750f04ab0ac9fc4f55df2c8583e5498
|
function results = vl_test_imintegral(varargin)
% VL_TEST_IMINTEGRAL
vl_test_init ;
function state = setup()
state.I = ones(5,6) ;
state.correct = [ 1 2 3 4 5 6 ;
2 4 6 8 10 12 ;
3 6 9 12 15 18 ;
4 8 12 16 20 24 ;
5 10 15 20 25 30 ; ] ;
function test_matlab_equivalent(s)
vl_assert_equal(slow_imintegral(s.I), s.correct) ;
function test_basic(s)
vl_assert_equal(vl_imintegral(s.I), s.correct) ;
function test_multi_dimensional(s)
vl_assert_equal(vl_imintegral(repmat(s.I, [1 1 3])), ...
repmat(s.correct, [1 1 3])) ;
function test_random(s)
numTests = 50 ;
for i = 1:numTests
I = rand(5) ;
vl_assert_almost_equal(vl_imintegral(s.I), ...
slow_imintegral(s.I)) ;
end
function test_datatypes(s)
vl_assert_equal(single(vl_imintegral(s.I)), single(s.correct)) ;
vl_assert_equal(double(vl_imintegral(s.I)), double(s.correct)) ;
vl_assert_equal(uint32(vl_imintegral(s.I)), uint32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(s.I)), int32(s.correct)) ;
vl_assert_equal(int32(vl_imintegral(-s.I)), -int32(s.correct)) ;
function integral = slow_imintegral(I)
integral = zeros(size(I));
for k = 1:size(I,3)
for r = 1:size(I,1)
for c = 1:size(I,2)
integral(r,c,k) = sum(sum(I(1:r,1:c,k)));
end
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_sift.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_sift.m
| 1,318 |
utf_8
|
806c61f9db9f2ebb1d649c9bfcf3dc0a
|
function results = vl_test_sift(varargin)
% VL_TEST_SIFT
vl_test_init ;
function s = setup()
s.I = im2single(imread(fullfile(vl_root,'data','box.pgm'))) ;
[s.ubc.f, s.ubc.d] = ...
vl_ubcread(fullfile(vl_root,'data','box.sift')) ;
function test_ubc_descriptor(s)
err = [] ;
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'frames', s.ubc.f) ;
D2 = vl_alldist(f, s.ubc.f) ;
[drop, perm] = min(D2) ;
f = f(:,perm) ;
d = d(:,perm) ;
error = mean(sqrt(sum((single(s.ubc.d) - single(d)).^2))) ...
/ mean(sqrt(sum(single(s.ubc.d).^2))) ;
assert(error < 0.1, ...
'sift descriptor did not produce desctiptors similar to UBC ones') ;
function test_ubc_detector(s)
[f, d] = vl_sift(s.I,...
'firstoctave', -1, ...
'peakthresh', .01, ...
'edgethresh', 10) ;
s.ubc.f(4,:) = mod(s.ubc.f(4,:), 2*pi) ;
f(4,:) = mod(f(4,:), 2*pi) ;
% scale the components so that 1 pixel erro in x,y,z is equal to a
% 10-th of angle.
S = diag([1 1 1 20/pi]);
D2 = vl_alldist(S * s.ubc.f, S * f) ;
[d2,perm] = sort(min(D2)) ;
error = sqrt(d2) ;
quant80 = round(.8 * size(f,2)) ;
% check for less than one pixel error at 80% quantile
assert(error(quant80) < 1, ...
'sift detector did not produce enough keypoints similar to UBC ones') ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_binsum.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_binsum.m
| 1,301 |
utf_8
|
5bbd389cbc4d997e413d809fe4efda6d
|
function results = vl_test_binsum(varargin)
% VL_TEST_BINSUM
vl_test_init ;
function test_three_args()
vl_assert_almost_equal(...
vl_binsum([0 0], 1, 2), [0 1]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, 1), [0 7]) ;
vl_assert_almost_equal(...
vl_binsum([1 7], -1, [1 2 2 2 2 2 2 2]), [0 0]) ;
function test_four_args()
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1], [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), [1 1 1]', [1 2 3]', 2), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3], 1), 2*eye(3)) ;
vl_assert_almost_equal(...
vl_binsum(eye(3), 1, [1 2 3]', 2), 2*eye(3)) ;
function test_3d_one()
Z = zeros(3,3,3) ;
B = 3*ones(3,1,3) ;
R = Z ; R(:,3,:) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, 17, B, 2), R) ;
function test_3d_two()
Z = zeros(3,3,3) ;
B = 3*ones(3,3,1) ;
X = zeros(3,3,1) ; X(:,:,1) = 17 ;
R = Z ; R(:,:,3) = 17 ;
vl_assert_almost_equal(...
vl_binsum(Z, X, B, 3), R) ;
function test_storage_classes()
types = {@double, @single, @int64, @uint64, ...
@int32, @uint32, @int16, @uint16, ...
@int8, @uint8} ;
for a = types
a = a{1} ;
for b = types
b = b{1} ;
vl_assert_almost_equal(...
vl_binsum(a(eye(3)), a([1 1 1]), b([1 2 3]), 1), a(2*eye(3))) ;
end
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_lbp.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_lbp.m
| 1,056 |
utf_8
|
3b5cca50109af84014e56a4280a3352a
|
function results = vl_test_lbp(varargin)
% VL_TEST_TWISTER
vl_test_init ;
function test_one_on()
I = {} ;
I{1} = [0 0 0 ; 0 0 1 ; 0 0 0] ;
I{2} = [0 0 0 ; 0 0 0 ; 0 0 1] ;
I{3} = [0 0 0 ; 0 0 0 ; 0 1 0] ;
I{4} = [0 0 0 ; 0 0 0 ; 1 0 0] ;
I{5} = [0 0 0 ; 1 0 0 ; 0 0 0] ;
I{6} = [1 0 0 ; 0 0 0 ; 0 0 0] ;
I{7} = [0 1 0 ; 0 0 0 ; 0 0 0] ;
I{8} = [0 0 1 ; 0 0 0 ; 0 0 0] ;
for j=0:7
h = vl_lbp(single(I{j+1}), 3) ;
h = find(squeeze(h)) ;
vl_assert_equal(h, j * 7 + 1) ;
end
function test_two_on()
I = {} ;
I{1} = [0 0 0 ; 0 0 1 ; 0 0 1] ;
I{2} = [0 0 0 ; 0 0 0 ; 0 1 1] ;
I{3} = [0 0 0 ; 0 0 0 ; 1 1 0] ;
I{4} = [0 0 0 ; 1 0 0 ; 1 0 0] ;
I{5} = [1 0 0 ; 1 0 0 ; 0 0 0] ;
I{6} = [1 1 0 ; 0 0 0 ; 0 0 0] ;
I{7} = [0 1 1 ; 0 0 0 ; 0 0 0] ;
I{8} = [0 0 1 ; 0 0 1 ; 0 0 0] ;
for j=0:7
h = vl_lbp(single(I{j+1}), 3) ;
h = find(squeeze(h)) ;
vl_assert_equal(h, j * 7 + 2) ;
end
function test_fliplr()
randn('state',0) ;
I = randn(256,256,1,'single') ;
f = vl_lbp(fliplr(I), 8) ;
f_ = vl_lbpfliplr(vl_lbp(I, 8)) ;
vl_assert_almost_equal(f,f_,1e-3) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_colsubset.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_colsubset.m
| 828 |
utf_8
|
be0c080007445b36333b863326fb0f15
|
function results = vl_test_colsubset(varargin)
% VL_TEST_COLSUBSET
vl_test_init ;
function s = setup()
s.x = [5 2 3 6 4 7 1 9 8 0] ;
function test_beginning(s)
vl_assert_equal(1:5, vl_colsubset(1:10, 5, 'beginning')) ;
vl_assert_equal(1:5, vl_colsubset(1:10, .5, 'beginning')) ;
function test_ending(s)
vl_assert_equal(6:10, vl_colsubset(1:10, 5, 'ending')) ;
vl_assert_equal(6:10, vl_colsubset(1:10, .5, 'ending')) ;
function test_largest(s)
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, 5, 'largest')) ;
vl_assert_equal([5 6 7 9 8], vl_colsubset(s.x, .5, 'largest')) ;
function test_smallest(s)
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, 5, 'smallest')) ;
vl_assert_equal([2 3 4 1 0], vl_colsubset(s.x, .5, 'smallest')) ;
function test_random(s)
assert(numel(intersect(s.x, vl_colsubset(s.x, 5, 'random'))) == 5) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_alldist.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_alldist.m
| 2,373 |
utf_8
|
9ea1a36c97fe715dfa2b8693876808ff
|
function results = vl_test_alldist(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js', ...
'kchi2', 'kl2', 'kl1', 'khell', 'kjs'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) x - x .* log2(1 + y/x) + y - y .* log2(1 + x/y), ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y), ...
@(x,y) .5 * (x .* log2(1 + y/x) + y .* log2(1 + x/y))} ;
types = {'single', 'double'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
vl_assert_almost_equal(...
vl_alldist(X,Y,dists{d}), ...
makedist(distsEquiv{d},X,Y), ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell', 'js'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist(X,X,ker) ;
kyy = vl_alldist(Y,Y,ker) ;
kxy = vl_alldist(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_ihashsum.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_ihashsum.m
| 581 |
utf_8
|
edc283062469af62056b0782b171f5fc
|
function results = vl_test_ihashsum(varargin)
% VL_TEST_IHASHSUM
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(round(16*rand(2,100))) ;
sel = find(all(s.data==0)) ;
s.data(1,sel)=1 ;
function test_hash(s)
D = size(s.data,1) ;
K = 5 ;
h = zeros(1,K,'uint32') ;
id = zeros(D,K,'uint8');
next = zeros(1,K,'uint32') ;
[h,id,next] = vl_ihashsum(h,id,next,K,s.data) ;
sel = vl_ihashfind(id,next,K,s.data) ;
count = double(h(sel)) ;
[drop,i,j] = unique(s.data','rows') ;
for k=1:size(s.data,2)
count_(k) = sum(j == j(k)) ;
end
vl_assert_equal(count,count_) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_grad.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_grad.m
| 434 |
utf_8
|
4d03eb33a6a4f68659f868da95930ffb
|
function results = vl_test_grad(varargin)
% VL_TEST_GRAD
vl_test_init ;
function s = setup()
s.I = rand(150,253) ;
s.I_small = rand(2,2) ;
function test_equiv(s)
vl_assert_equal(gradient(s.I), vl_grad(s.I)) ;
function test_equiv_small(s)
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
function test_equiv_forward(s)
Ix = diff(s.I,2,1) ;
Iy = diff(s.I,2,1) ;
vl_assert_equal(gradient(s.I_small), vl_grad(s.I_small)) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_whistc.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_whistc.m
| 1,384 |
utf_8
|
81c446d35c82957659840ab2a579ec2c
|
function results = vl_test_whistc(varargin)
% VL_TEST_WHISTC
vl_test_init ;
function test_acc()
x = ones(1, 10) ;
e = 1 ;
o = 1:10 ;
vl_assert_equal(vl_whistc(x, o, e), 55) ;
function test_basic()
x = 1:10 ;
e = 1:10 ;
o = ones(1, 10) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
x = linspace(-1,11,100) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
function test_multidim()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_nan()
x = rand(10, 20, 30) ;
e = linspace(0,1,10) ;
o = ones(size(x)) ;
x(1:7:end) = NaN ;
vl_assert_equal(histc(x, e), vl_whistc(x, o, e)) ;
vl_assert_equal(histc(x, e, 1), vl_whistc(x, o, e, 1)) ;
vl_assert_equal(histc(x, e, 2), vl_whistc(x, o, e, 2)) ;
vl_assert_equal(histc(x, e, 3), vl_whistc(x, o, e, 3)) ;
function test_no_edges()
x = rand(10, 20, 30) ;
o = ones(size(x)) ;
vl_assert_equal(histc(1, []), vl_whistc(1, 1, [])) ;
vl_assert_equal(histc(x, []), vl_whistc(x, o, [])) ;
vl_assert_equal(histc(x, [], 1), vl_whistc(x, o, [], 1)) ;
vl_assert_equal(histc(x, [], 2), vl_whistc(x, o, [], 2)) ;
vl_assert_equal(histc(x, [], 3), vl_whistc(x, o, [], 3)) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_roc.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_roc.m
| 1,019 |
utf_8
|
9b2ae71c9dc3eda0fc54c65d55054d0c
|
function results = vl_test_roc(varargin)
% VL_TEST_ROC
vl_test_init ;
function s = setup()
s.scores0 = [5 4 3 2 1] ;
s.scores1 = [5 3 4 2 1] ;
s.labels = [1 1 -1 -1 -1] ;
function test_perfect_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(tpr, [0 1 2 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 3 2 1 0] / 3) ;
function test_perfect_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores0) ;
vl_assert_almost_equal(info.eer, 0) ;
vl_assert_almost_equal(info.auc, 1) ;
function test_swap1_tptn(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(tpr, [0 1 1 2 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 3 2 2 1 0] / 3) ;
function test_swap1_tptn_stable(s)
[tpr,tnr] = vl_roc(s.labels,s.scores1,'stable',true) ;
vl_assert_almost_equal(tpr, [1 2 1 2 2] / 2) ;
vl_assert_almost_equal(tnr, [3 2 2 1 0] / 3) ;
function test_swap1_metrics(s)
[tpr,tnr,info] = vl_roc(s.labels,s.scores1) ;
vl_assert_almost_equal(info.eer, 1/3) ;
vl_assert_almost_equal(info.auc, 1 - 1/(2*3)) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_dsift.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_dsift.m
| 2,048 |
utf_8
|
fbbfb16d5a21936c1862d9551f657ccc
|
function results = vl_test_dsift(varargin)
% VL_TEST_DSIFT
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = rgb2gray(single(I)) ;
function test_fast_slow(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSize = 5 ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
[f_, d_] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors', ...
'fast') ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift fast approximation not close') ;
function test_sift(s)
binSize = 4 ; % bin size in pixels
magnif = 3 ; % bin size / keypoint scale
scale = binSize / magnif ;
windowSizeRange = [1 1.2 5] ;
for wi = 1:length(windowSizeRange)
windowSize = windowSizeRange(wi) ;
[f, d] = vl_dsift(vl_imsmooth(s.I, sqrt(scale.^2 - .25)), ...
'size', binSize, ...
'step', 10, ...
'bounds', [20,20,210,140], ...
'windowsize', windowSize, ...
'floatdescriptors') ;
numKeys = size(f, 2) ;
f_ = [f ; ones(1, numKeys) * scale ; zeros(1, numKeys)] ;
[f_, d_] = vl_sift(s.I, ...
'magnif', magnif, ...
'frames', f_, ...
'firstoctave', -1, ...
'levels', 5, ...
'floatdescriptors', ...
'windowsize', windowSize) ;
error = std(d_(:) - d(:)) / std(d(:)) ;
assert(error < 0.1, 'dsift and sift equivalence') ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_alldist2.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_alldist2.m
| 2,284 |
utf_8
|
89a787e3d83516653ae8d99c808b9d67
|
function results = vl_test_alldist2(varargin)
% VL_TEST_ALLDIST
vl_test_init ;
% TODO: test integer classes
function s = setup()
vl_twister('state', 0) ;
s.X = 3.1 * vl_twister(10,10) ;
s.Y = 4.7 * vl_twister(10,7) ;
function test_null_args(s)
vl_assert_equal(...
vl_alldist2(zeros(15,12), zeros(15,0), 'kl2'), ...
zeros(12,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,0), 'kl2'), ...
zeros(0,0)) ;
vl_assert_equal(...
vl_alldist2(zeros(15,0), zeros(15,12), 'kl2'), ...
zeros(0,12)) ;
vl_assert_equal(...
vl_alldist2(zeros(0,15), zeros(0,12), 'kl2'), ...
zeros(15,12)) ;
function test_self(s)
vl_assert_almost_equal(...
vl_alldist2(s.X, 'kl2'), ...
makedist(@(x,y) x*y, s.X, s.X), ...
1e-6) ;
function test_distances(s)
dists = {'chi2', 'l2', 'l1', 'hell', ...
'kchi2', 'kl2', 'kl1', 'khell'} ;
distsEquiv = { ...
@(x,y) (x-y)^2 / (x + y), ...
@(x,y) (x-y)^2, ...
@(x,y) abs(x-y), ...
@(x,y) (sqrt(x) - sqrt(y))^2, ...
@(x,y) 2 * (x*y) / (x + y), ...
@(x,y) x*y, ...
@(x,y) min(x,y), ...
@(x,y) sqrt(x.*y)};
types = {'single', 'double', 'sparse'} ;
for simd = [0 1]
for d = 1:length(dists)
for t = 1:length(types)
vl_simdctrl(simd) ;
X = feval(str2func(types{t}), s.X) ;
Y = feval(str2func(types{t}), s.Y) ;
a = vl_alldist2(X,Y,dists{d}) ;
b = makedist(distsEquiv{d},X,Y) ;
vl_assert_almost_equal(a,b, ...
1e-4, ...
'alldist failed for dist=%s type=%s simd=%d', ...
dists{d}, ...
types{t}, ...
simd) ;
end
end
end
function test_distance_kernel_pairs(s)
dists = {'chi2', 'l2', 'l1', 'hell'} ;
for d = 1:length(dists)
dist = char(dists{d}) ;
X = s.X ;
Y = s.Y ;
ker = ['k' dist] ;
kxx = vl_alldist2(X,X,ker) ;
kyy = vl_alldist2(Y,Y,ker) ;
kxy = vl_alldist2(X,Y,ker) ;
kxx = repmat(diag(kxx), 1, size(s.Y,2)) ;
kyy = repmat(diag(kyy), 1, size(s.X,1))' ;
d2 = vl_alldist2(X,Y,dist) ;
vl_assert_almost_equal(d2, kxx + kyy - 2 * kxy, '1e-6') ;
end
function D = makedist(cmp,X,Y)
[d,m] = size(X) ;
[d,n] = size(Y) ;
D = zeros(m,n) ;
for i = 1:m
for j = 1:n
acc = 0 ;
for k = 1:d
acc = acc + cmp(X(k,i),Y(k,j)) ;
end
D(i,j) = acc ;
end
end
conv = str2func(class(X)) ;
D = conv(D) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_fisher.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_fisher.m
| 1,703 |
utf_8
|
41b28dce7f0d0ae5cb6abd942acbef56
|
function results = vl_test_fisher(varargin)
% VL_TEST_FISHER
vl_test_init ;
function s = setup()
randn('state',0) ;
dimension = 5 ;
numData = 21 ;
numComponents = 3 ;
s.x = randn(dimension,numData) ;
s.mu = randn(dimension,numComponents) ;
s.sigma2 = ones(dimension,numComponents) ;
s.prior = ones(1,numComponents) ;
s.prior = s.prior / sum(s.prior) ;
function test_basic(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior) ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_norm(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'normalized') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_sqrt(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'squareroot') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function test_improved(s)
phi_ = simple_fisher(s.x, s.mu, s.sigma2, s.prior) ;
phi_ = sign(phi_) .* sqrt(abs(phi_)) ;
phi_ = phi_ / norm(phi_) ;
phi = vl_fisher(s.x, s.mu, s.sigma2, s.prior, 'improved') ;
vl_assert_almost_equal(phi, phi_, 1e-10) ;
function enc = simple_fisher(x, mu, sigma2, pri)
sigma = sqrt(sigma2) ;
for i = 1:size(mu,2)
delta{i} = bsxfun(@times, bsxfun(@minus, x, mu(:,i)), 1./sigma(:,i)) ;
q(i,:) = log(pri(i)) - 0.5 * log(sigma2(i)) - 0.5 * sum(delta{i}.^2,1) ;
end
q = exp(bsxfun(@minus, q, max(q,[],1))) ;
q = bsxfun(@times, q, 1 ./ sum(q,1)) ;
n = size(x,2) ;
for i = 1:size(mu,2)
u{i} = delta{i} * q(i,:)' / n / sqrt(pri(i)) ;
v{i} = (delta{i}.^2 - 1) * q(i,:)' / n / sqrt(2*pri(i)) ;
end
enc = cat(1, u{:}, v{:}) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_imsmooth.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_imsmooth.m
| 1,837 |
utf_8
|
718235242cad61c9804ba5e881c22f59
|
function results = vl_test_imsmooth(varargin)
% VL_TEST_IMSMOOTH
vl_test_init ;
function s = setup()
I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
I = max(min(vl_imdown(I),1),0) ;
s.I = single(I) ;
function test_pad_by_continuity(s)
% Convolving a constant signal padded with continuity does not change
% the signal.
I = ones(3) ;
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
J = vl_imsmooth(I, 2, ...
'kernel', ker, ...
'padding', 'continuity') ;
vl_assert_almost_equal(J, I, 1e-4, ...
'padding by continutiy with kernel = %s', ker) ;
end
function test_kernels(s)
for ker = {'triangular', 'gaussian'}
ker = char(ker) ;
for type = {@single, @double}
for simd = [0 1]
for sigma = [1 2 7]
for step = [1 2 3]
vl_simdctrl(simd) ;
conv = type{1} ;
g = equivalent_kernel(ker, sigma) ;
J = vl_imsmooth(conv(s.I), sigma, ...
'kernel', ker, ...
'padding', 'zero', ...
'subsample', step) ;
J_ = conv(convolve(s.I, g, step)) ;
vl_assert_almost_equal(J, J_, 1e-4, ...
'kernel=%s sigma=%f step=%d simd=%d', ...
ker, sigma, step, simd) ;
end
end
end
end
end
function g = equivalent_kernel(ker, sigma)
switch ker
case 'gaussian'
W = ceil(4*sigma) ;
g = exp(-.5*((-W:W)/(sigma+eps)).^2) ;
case 'triangular'
W = max(round(sigma),1) ;
g = W - abs(-W+1:W-1) ;
end
g = g / sum(g) ;
function I = convolve(I, g, step)
if strcmp(class(I),'single')
g = single(g) ;
else
g = double(g) ;
end
for k=1:size(I,3)
I(:,:,k) = conv2(g,g,I(:,:,k),'same');
end
I = I(1:step:end,1:step:end,:) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_svmtrain.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_svmtrain.m
| 4,277 |
utf_8
|
071b7c66191a22e8236fda16752b27aa
|
function results = vl_test_svmtrain(varargin)
% VL_TEST_SVMTRAIN
vl_test_init ;
end
function s = setup()
randn('state',0) ;
Np = 10 ;
Nn = 10 ;
xp = diag([1 3])*randn(2, Np) ;
xn = diag([1 3])*randn(2, Nn) ;
xp(1,:) = xp(1,:) + 2 + 1 ;
xn(1,:) = xn(1,:) - 2 + 1 ;
s.x = [xp xn] ;
s.y = [ones(1,Np) -ones(1,Nn)] ;
s.lambda = 0.01 ;
s.biasMultiplier = 10 ;
if 0
figure(1) ; clf;
vl_plotframe(xp, 'g') ; hold on ;
vl_plotframe(xn, 'r') ;
axis equal ; grid on ;
end
% Run LibSVM as an accuate solver to compare results with. Note that
% LibSVM optimizes a slightly different cost function due to the way
% the bias is handled.
% [s.w, s.b] = accurate_solver(s.x, s.y, s.lambda, s.biasMultiplier) ;
s.w = [1.180762951236242; 0.098366470721632] ;
s.b = -1.540018443946204 ;
s.obj = obj(s, s.w, s.b) ;
end
function test_sgd_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sgd', ...
'BiasMultiplier', s.biasMultiplier, ...
'BiasLearningRate', 1/s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% there are no absolute guarantees on the objective gap, but
% the heuristic SGD uses as stopping criterion seems reasonable
% within a factor 10 at least.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-2) ;
end
end
function test_sdca_basic(s)
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
[w b info] = vl_svmtrain(s.x, s.y, s.lambda, ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e5, ...
'Epsilon', 1e-3) ;
% the gap with the accurate solver cannot be
% greater than the duality gap.
o = obj(s, w, b) ;
gap = o - s.obj ;
vl_assert_almost_equal(conv([w; b]), conv([s.w; s.b]), 0.1) ;
assert(gap <= 1e-3) ;
end
end
function test_weights(s)
for algo = {'sgd', 'sdca'}
for conv = {@single, @double}
conv = conv{1} ;
vl_twister('state',0) ;
numRepeats = 10 ;
pos = find(s.y > 0) ;
neg = find(s.y < 0) ;
weights = ones(1, numel(s.y)) ;
weights(pos) = numRepeats ;
% simulate weighting by repeating positives
[w b info] = vl_svmtrain(...
s.x(:, [repmat(pos,1,numRepeats) neg]), ...
s.y(:, [repmat(pos,1,numRepeats) neg]), ...
s.lambda / (numel(pos) *numRepeats + numel(neg)) / (numel(pos) + numel(neg)), ...
'Solver', 'sdca', ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4) ;
% apply weigthing
[w_ b_ info_] = vl_svmtrain(...
s.x, ...
s.y, ...
s.lambda, ...
'Solver', char(algo), ...
'BiasMultiplier', s.biasMultiplier, ...
'MaxNumIterations', 1e6, ...
'Epsilon', 1e-4, ...
'Weights', weights) ;
vl_assert_almost_equal(conv([w; b]), conv([w_; b_]), 0.05) ;
end
end
end
function test_homkermap(s)
for solver = {'sgd', 'sdca'}
for conv = {@single,@double}
conv = conv{1} ;
dataset = vl_svmdataset(conv(s.x), 'homkermap', struct('order',1)) ;
vl_twister('state',0) ;
[w_ b_] = vl_svmtrain(dataset, s.y, s.lambda) ;
x_hom = vl_homkermap(conv(s.x), 1) ;
vl_twister('state',0) ;
[w b] = vl_svmtrain(x_hom, s.y, s.lambda) ;
vl_assert_almost_equal([w; b],[w_; b_], 1e-7) ;
end
end
end
function [w,b] = accurate_solver(X, y, lambda, biasMultiplier)
addpath opt/libsvm/matlab/
N = size(X,2) ;
model = svmtrain(y', [(1:N)' X'*X], sprintf(' -c %f -t 4 -e 0.00001 ', 1/(lambda*N))) ;
w = X(:,model.SVs) * model.sv_coef ;
b = - model.rho ;
format long ;
disp('model w:')
disp(w)
disp('bias b:')
disp(b)
end
function o = obj(s, w, b)
o = (sum(w.*w) + b*b) * s.lambda / 2 + mean(max(0, 1 - s.y .* (w'*s.x + b))) ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_phow.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_phow.m
| 549 |
utf_8
|
f761a3bb218af855986263c67b2da411
|
function results = vl_test_phow(varargin)
% VL_TEST_PHOPW
vl_test_init ;
function s = setup()
s.I = im2double(imread(fullfile(vl_root,'data','spots.jpg'))) ;
s.I = single(s.I) ;
function test_gray(s)
[f,d] = vl_phow(s.I, 'color', 'gray') ;
assert(size(d,1) == 128) ;
function test_rgb(s)
[f,d] = vl_phow(s.I, 'color', 'rgb') ;
assert(size(d,1) == 128*3) ;
function test_hsv(s)
[f,d] = vl_phow(s.I, 'color', 'hsv') ;
assert(size(d,1) == 128*3) ;
function test_opponent(s)
[f,d] = vl_phow(s.I, 'color', 'opponent') ;
assert(size(d,1) == 128*3) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_kmeans.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_kmeans.m
| 3,632 |
utf_8
|
719f7fca81e19eed5cc45c2ca251aad0
|
function results = vl_test_kmeans(varargin)
% VL_TEST_KMEANS
% Copyright (C) 2007-12 Andrea Vedaldi and Brian Fulkerson.
% All rights reserved.
%
% This file is part of the VLFeat library and is made available under
% the terms of the BSD license (see the COPYING file).
vl_test_init ;
function s = setup()
randn('state',0) ;
s.X = randn(128, 100) ;
function test_basic(s)
[centers, assignments, en] = vl_kmeans(s.X, 10, 'NumRepetitions', 10) ;
[centers_, assignments_, en_] = simpleKMeans(s.X, 10) ;
assert(en_ <= 1.1 * en, 'vl_kmeans did not optimize enough') ;
function test_algorithms(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
X = conversion(s.X) ;
vl_twister('state',0) ;
[centers, assignments, en] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Lloyd', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers_, assignments_, en_] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'Elkan', ...
'Distance', distance) ;
vl_twister('state',0) ;
[centers__, assignments__, en__] = vl_kmeans(X, 10, ...
'NumRepetitions', 1, ...
'MaxNumIterations', 10, ...
'Algorithm', 'ANN', ...
'Distance', distance, ...
'NumTrees', 3, ...
'MaxNumComparisons',0) ;
vl_assert_almost_equal(centers, centers_, 1e-5) ;
vl_assert_almost_equal(assignments, assignments_, 1e-5) ;
vl_assert_almost_equal(en, en_, 1e-5) ;
vl_assert_almost_equal(centers, centers__, 1e-5) ;
vl_assert_almost_equal(assignments, assignments__, 1e-5) ;
vl_assert_almost_equal(en, en__, 1e-5) ;
vl_assert_almost_equal(centers_, centers__, 1e-5) ;
vl_assert_almost_equal(assignments_, assignments__, 1e-5) ;
vl_assert_almost_equal(en_, en__, 1e-5) ;
end
end
function test_patterns(s)
distances = {'l1', 'l2'} ;
dataTypes = {'single','double'} ;
for dataType = dataTypes
for distance = distances
distance = char(distance) ;
conversion = str2func(char(dataType)) ;
data = [1 1 0 0 ;
1 0 1 0] ;
data = conversion(data) ;
[centers, assignments, en] = vl_kmeans(data, 4, ...
'NumRepetitions', 100, ...
'Distance', distance) ;
assert(isempty(setdiff(data', centers', 'rows'))) ;
end
end
function [centers, assignments, en] = simpleKMeans(X, numCenters)
[dimension, numData] = size(X) ;
centers = randn(dimension, numCenters) ;
for iter = 1:10
[dists, assignments] = min(vl_alldist(centers, X)) ;
en = sum(dists) ;
centers = [zeros(dimension, numCenters) ; ones(1, numCenters)] ;
centers = vl_binsum(centers, ...
[X ; ones(1,numData)], ...
repmat(assignments, dimension+1, 1), 2) ;
centers = centers(1:end-1, :) ./ repmat(centers(end,:), dimension, 1) ;
end
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_hikmeans.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_hikmeans.m
| 463 |
utf_8
|
dc3b493646e66316184e86ff4e6138ab
|
function results = vl_test_hikmeans(varargin)
% VL_TEST_IKMEANS
vl_test_init ;
function s = setup()
rand('state',0) ;
s.data = uint8(rand(2,1000) * 255) ;
function test_basic(s)
[tree, assign] = vl_hikmeans(s.data,3,100) ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
function test_elkan(s)
[tree, assign] = vl_hikmeans(s.data,3,100,'method','elkan') ;
assign_ = vl_hikmeanspush(tree, s.data) ;
vl_assert_equal(assign,assign_) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_aib.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_aib.m
| 1,277 |
utf_8
|
78978ae54e7ebe991d136336ba4bf9c6
|
function results = vl_test_aib(varargin)
% VL_TEST_AIB
vl_test_init ;
function s = setup()
s = [] ;
function test_basic(s)
Pcx = [.3 .3 0 0
0 0 .2 .2] ;
% This results in the AIB tree
%
% 1 - \
% 5 - \
% 2 - / \
% - 7
% 3 - \ /
% 6 - /
% 4 - /
%
% coded by the map [5 5 6 6 7 1] (1 denotes the root).
[parents,cost] = vl_aib(Pcx) ;
vl_assert_equal(parents, [5 5 6 6 7 7 1]) ;
vl_assert_almost_equal(mi(Pcx)*[1 1 1], cost(1:3), 1e-3) ;
[cut,map,short] = vl_aibcut(parents,2) ;
vl_assert_equal(cut, [5 6]) ;
vl_assert_equal(map, [1 1 2 2 1 2 0]) ;
vl_assert_equal(short, [5 5 6 6 5 6 7]) ;
function test_cluster_null(s)
Pcx = [.5 .5 0 0
0 0 0 0] ;
% This results in the AIB tree
%
% 1 - \
% 5
% 2 - /
%
% 3 x
%
% 4 x
%
% If ClusterNull is specified, the values 3 and 4
% which have zero probability are merged first
%
% 1 ----------\
% 7
% 2 ----- \ /
% 6-/
% 3 -\ /
% 5 -/
% 4 -/
parents1 = vl_aib(Pcx) ;
parents2 = vl_aib(Pcx,'ClusterNull') ;
vl_assert_equal(parents1, [5 5 0 0 1 0 0]) ;
vl_assert_equal(parents2(3), parents2(4)) ;
function x = mi(P)
% mutual information
P1 = sum(P,1) ;
P2 = sum(P,2) ;
x = sum(sum(P .* log(max(P,1e-10) ./ (P2*P1)))) ;
|
github
|
jianxiongxiao/ProfXkit-master
|
vl_test_plotbox.m
|
.m
|
ProfXkit-master/depthImproveStructureIO/lib/vlfeat/toolbox/xtest/vl_test_plotbox.m
| 414 |
utf_8
|
aa06ce4932a213fb933bbede6072b029
|
function results = vl_test_plotbox(varargin)
% VL_TEST_PLOTBOX
vl_test_init ;
function test_basic(s)
figure(1) ; clf ;
vl_plotbox([-1 -1 1 1]') ;
xlim([-2 2]) ;
ylim([-2 2]) ;
close(1) ;
function test_multiple(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10)) ;
close(1) ;
function test_style(s)
figure(1) ; clf ;
randn('state', 0) ;
vl_plotbox(randn(4,10), 'r-.', 'LineWidth', 3) ;
close(1) ;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.