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
ojwoodford/ojwul-master
convert2gray.m
.m
ojwul-master/image/convert2gray.m
394
utf_8
20ef7eae75c457cf26bbaa3348131014
%CONVERT2GRAY Convert an RGB image to grayscale % % B = convert2gray(A) % %IN: % A - HxWxC input image, where C = 3 (RGB) or 1 (already grayscale). % %OUT: % B - HxW grayscale output image, of the same class as A. function im = convert2gray(im) if size(im, 3) == 3 im = cast(reshape(double(reshape(im, [], 3)) * [0.299; 0.587; 0.114], size(im, 1), size(im, 2)), 'like', im); end end
github
ojwoodford/ojwul-master
imwarp.m
.m
ojwul-master/image/imwarp.m
429
utf_8
e6216334a08f75eb5428bedae35469cf
%IMWARP Warp an image according to a homography % % im = imwarp(im, H) % %IN: % im - HxWxC image % H - 3x3 homography matrix from source to target % %OUT: % im - HxWxC resampled output image function im = imwarp(im, H) % Compute the coordinates to sample at X = proj(H \ homg(flipud(ndgrid_cols(1:size(im, 1), 1:size(im, 2))))); % Resample the image im = reshape(ojw_interp2(im, X(1,:), X(2,:), '6', 0), size(im)); end
github
ojwoodford/ojwul-master
im2mov.m
.m
ojwul-master/image/im2mov.m
5,227
utf_8
41e469b5c3e2fb96e4aa5403e2c49598
%IM2MOV Convert a sequence of images to a movie file % % Examples: % im2mov infile outfile % im2mov(A, outfile) % im2mov(..., '-fps', n) % im2mov(..., '-quality', q) % im2mov(..., '-profile', profile) % im2mov(..., '-nocrop') % % This function converts an image sequence to a movie. % % To create a video from a series of figures, export to an image sequence % using export_fig, then convert to a movie, as follows: % % frame_num = 0; % for a = 2 .^ (3:6) % peaks(a); % export_fig(sprintf('test.%3.3d.png', frame_num), '-nocrop'); % frame_num = frame_num + 1; % end % im2mov('test.000.png', 'output', '-fps', 0.5, '-profile', 'MPEG-4'); % %IN: % infile - string containing the name of the first input image. % outfile - string containing the name of the output video (without an % extension). % A - HxWxCxN array of input images, stacked along fourth dimension, to % be converted to a movie. % -nocrop - option indicating that the borders of the output are not to % be cropped. % -fps - option pair, the value of which gives the number of frames per % second. Default: 15. % -quality - option pair, the value of which gives the video quality, % from 0 to 100. Default: 75. % -profile - option pair, the value of which is a profile string passed % to VideoWriter object. Default: 'MPEG-4'. % Copyright (C) Oliver Woodford 2013 function im2mov(A, varargin) % Parse the input arguments [A, options] = parse_args(A, varargin{:}); % Get a consistent interface to the sequence if isnumeric(A) im = @(a) A(:,:,:,a); num_frames = size(A, 4); elseif ischar(A) im = imstream(A, 50); num_frames = im.num_frames; end crop_func = @(A) A; if options.crop ~= 0 %% Determine the borders A = im(1); [h, w, c] = size(A); L = w; R = w; T = h; B = h; bcol = A(1,1,:); for n = num_frames:-1:1 A = im(n); [h, w, c] = size(A); bail = false; for l = 1:min(L, w) for a = 1:c if ~all(col(A(:,l,a)) == bcol(a)) bail = true; break; end end if bail break; end end L = l; bail = false; for r = min(w, R):-1:L for a = 1:c if ~all(col(A(:,r,a)) == bcol(a)) bail = true; break; end end if bail break; end end R = r; bail = false; for t = 1:min(T, h) for a = 1:c if ~all(col(A(t,:,a)) == bcol(a)) bail = true; break; end end if bail break; end end T = t; bail = false; for b = min(h, B):-1:T for a = 1:c if ~all(col(A(b,:,a)) == bcol(a)) bail = true; break; end end if bail break; end end B = b; end crop_func = @(A) A(T:B,L:R,:); end % Create the movie object hMov = VideoWriter(options.outfile, options.profile); set(hMov, 'FrameRate', options.fps); try % Not all profiles support quality set(hMov, 'Quality', options.quality); catch end open(hMov); % Write out the frames for a = 1:num_frames writeVideo(hMov, crop_func(im(a))); end close(hMov); return %% Parse the input arguments function [infile, options] = parse_args(infile, varargin) % Set the defaults options = struct('outfile', '', ... 'crop', true, .... 'profile', 'MPEG-4', ... 'quality', 75, ... 'fps', 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; 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(infile) error('No output filename given.'); end % Generate the output filename from the input filename [path, outfile] = fileparts(infile); options.outfile = fullfile(path, outfile); end return function A = col(A) A = A(:); return
github
ojwoodford/ojwul-master
mov2im.m
.m
ojwul-master/image/mov2im.m
641
utf_8
f623093ad1a8a6cae5684eb639972909
%MOV2IM Convert a movie file to a sequence of images % % Examples: % mov2im infile outfile_format % %IN: % infile - string containing the name of the input video. % outfile_format - format string for the movie frames. The filename for % frame N is given by sprintf(outfile_format, N). % Copyright (C) Oliver Woodford 2015 function mov2im(infile, outfile_format, varargin) % Create the movie object hMov = VideoReader(infile); % Write out the frames frame = 0; while hasFrame(hMov) imwrite(readFrame(hMov), sprintf(outfile_format, frame), varargin{:}); frame = frame + 1; end end
github
ojwoodford/ojwul-master
imnorm.m
.m
ojwul-master/image/imnorm.m
1,278
utf_8
a6b4caa2db5fa5166a2b34ff89d87eb9
%IMNORM Spatially local image normalization % % B = imnorm(A, sigma, noise_variance) % B = imnorm(A, [szy szx], noise_variance) % % Apply a local normalization operator (subtracting the mean and % normalizing the variance) to an image, either with a Gaussian or window % average weighting. % %IN: % A - HxWxC input image. % sigma - scalar indicating the standard deviation of the Gaussian % weighting to apply, in pixels. % [szy szx] - 1x2 window size for window average weighting. % noise_variance - scalar variance of image noise. % %OUT: % B - HxWxC normalized image. function A = imnorm(A, sigma, noise_variance) % Compute the separable filters if isscalar(sigma) fx = max(floor(5/2 * sigma), 1); fx = gauss_mask(sigma, 0, -fx:fx); fx = fx / sum(fx); fy = fx; elseif isequal(size(sigma), [1 2]) && isequal(sigma, round(sigma)) fy = repmat(1 / sigma(1), sigma(1), 1); fx = repmat(1 / sigma(2), 1, sigma(2)); else error('sigma not recognized'); end % Filter the image A = double(A); % Subtract the mean A = A - imfiltsep(A, fy, fx); % Divide by the standard deviation noise_variance = max(noise_variance, 1e-100); A = A ./ sqrt(imfiltsep(A .* A, fy, fx) + noise_variance); end
github
ojwoodford/ojwul-master
rng_seeder.m
.m
ojwul-master/utils/rng_seeder.m
589
utf_8
37ed4745dc7d52079ad2aaced05010da
%RNG_SEEDER Seed the random number generator, and print the seed if generated % % seed = rng_seeder() % rng_seeder(seed) % % This function intializes the random number generator, and prints out the % seed if one is not given or output. % %IN: % seed - scalar seed for the random number generator. % %OUT: % seed - scalar seed used to initialize the random number generator. function seed = rng_seeder(seed) if nargin < 1 || isempty(seed) rng('shuffle'); seed = ceil(rand(1) * (2^31)); if nargout < 1 fprintf('RNG seed: %d\n', seed); end end rng(seed); end
github
ojwoodford/ojwul-master
qfig.m
.m
ojwul-master/utils/qfig.m
450
utf_8
9f8367ca4007ca0eb5e1e401272d1009
%QFIG Quietly select the figure % % fh = qfig(fn) % % Quietly selects the figure specified, without bringing it into focus % (unless the figure doesn't exist yet). % % IN: % fn - scalar positive integer, or figure handle indicating the figure % to select. % % OUT: % fh - handle to the figure. function f = qfig(f) try set(0, 'CurrentFigure', f); catch figure(f); end if nargout > 0 f = get(0, 'CurrentFigure'); end end
github
ojwoodford/ojwul-master
ojw_progressbar.m
.m
ojwul-master/utils/ojw_progressbar.m
9,531
utf_8
ca29d395f2e8d30da82e8b0f31717b83
%OJW_PROGRESSBAR Simple progress bar implementation % % [this, retval] = ojw_progressbar(tag, proportion, [total, [min_update_interval]]) % % Starts, updates and closes a progress bar according to the proportion of % time left. There are two ways of using the function: % % % Simple (one line) but more overhead % for iter = 1:total % % Code here % ojw_progressbar('Bar 1', iter/total); % end % % % More complicated (two lines!) but less overhead % pb = ojw_progressbar('Bar 2', total); % for iter = 1:total % % Code here % update(pb, iter); % end % % IN: % tag - String that appears on progress bar, specific to each function % calling OJW_PROGRESSBAR. % proportion - Proportion of time elapsed, as a function of total (below). % total - The value of proportion that will indicate completion. % Default: 1. % min_update_interval - Minimum time (in seconds) between updates of the % progress bar. The value is kept while the bar is % alive. Default: 0.5. % % OUT: % this - Handle to the progressbar object. % retval - 2 iff time since last report > min_update_interval, % 1 iff progress bar initialized or reset, % 0 otherwise. % Based on Andrew Fitzgibbon's awf_progressbar classdef ojw_progressbar < handle properties (Hidden = true, SetAccess = private) bar; min_update; prop; start_prop; next_prop; timer; last_update; text_version; tag; tag_title; total; inverse_total; end methods function [this, retval] = ojw_progressbar(tag, proportion, total, min_update_interval) % Check the input arguments if nargin < 2 error('At least 2 input arguments expected'); end if ~ischar(tag) error('First argument should be a string'); end if ~isscalar(proportion) || proportion < 0 error('Second argument should be a non-negative scalar'); end if nargin > 2 if ~isscalar(total) || total < 0 error('Third argument should be a non-negative scalar'); end total = double(total); else total = 1; % Default total proportion end if nargin > 3 if ~isscalar(min_update_interval) || min_update_interval < 0 error('Fourth argument should be a non-negative scalar'); end min_update_interval = double(min_update_interval); else min_update_interval = 0.5; % Default seconds between updates end % Record the time curr_time = clock(); proportion = double(proportion); % Must be a double % Check the tag exists tag_title = tag; tag = tag(isstrprop(tag, 'alphanum')); v = ojw_progressbar.GetSetPersistent(tag); if isempty(v) % No tag by this name if proportion >= total % No need to create one retval = 0; return; end % Create a data structure for this tag this.bar = []; this.min_update = min_update_interval; % Default seconds between updates this.prop = proportion; this.start_prop = proportion; this.next_prop = proportion; this.timer = curr_time; this.last_update = curr_time; this.tag_title = tag_title; this.tag = tag; this.total = total; this.inverse_total = 1 / total; this.text_version = ojw_progressbar.GetSetPersistent('text_version'); % Update our global variable with the changes to this tag ojw_progressbar.GetSetPersistent(tag, this); % Ensure it gets closed when the function exits [~, varname] = fileparts(tempname()); assignin('caller', varname, onCleanup(@() ojw_progressbar(tag, Inf))); else % Use the cached the data structure this = v; % Update the total if a new one is given if nargin > 2 this.total = total; this.inverse_total = 1 / total; this.next_prop = this.prop; % Update the minimum update interval if a new one is given if nargin > 3 this.min_update = min_update_interval; end end end % Update the bar retval = update(this, proportion, curr_time); end % Function for direct updating function retval = update(this, proportion, curr_time) % Check for a fast (i.e. no) update if proportion < this.next_prop && proportion >= this.prop retval = 1; return; end % Check for an end to the progress bar retval = 0; if proportion >= this.total % Close the progress bar if this.text_version fprintf([repmat(' ', 1, 200) repmat('\b', 1, 200)]); else close(this.bar); drawnow(); end ojw_progressbar.GetSetPersistent(this.tag, []); this.prop = this.total; return; end if nargin < 3 curr_time = clock(); proportion = double(proportion); % Must be a double end % Check to see if we haven't started again if proportion < this.prop || proportion == this.start_prop retval = 1; elseif etime(curr_time, this.last_update) >= this.min_update % An update of the progress bar is required retval = 1 + (proportion > this.start_prop); else % No update required return; end this.prop = proportion; proportion = proportion * this.inverse_total; if retval == 2 this.last_update = curr_time; t_elapsed = etime(curr_time, this.timer); prop_done = this.prop - this.start_prop; t_remaining = ((this.total - this.prop) * t_elapsed) / prop_done; this.next_prop = min(this.prop + prop_done * this.min_update * 1.1 / t_elapsed, this.total); newtitle = sprintf('Elapsed: %s', timestr(t_elapsed)); if proportion > 0.01 || t_elapsed > 30 if t_remaining < 600 newtitle = sprintf('%s, Remaining: %s ', newtitle, timestr(t_remaining)); else newtitle = sprintf('%s, ETA: %s', newtitle, datestr(datenum(curr_time) + (t_remaining * 1.15741e-5), 0)); end end else % Reset the information this.start_prop = this.prop; this.next_prop = this.prop; this.timer = curr_time; this.last_update = this.timer; newtitle = 'Starting...'; end % Update the waitbar if this.text_version % Text version proportion = floor(proportion * 50); str = sprintf(' %s |%s%s| %s', this.tag_title, repmat('#', 1, proportion), repmat(' ', 1, 50 - proportion), newtitle); fprintf([str repmat('\b', 1, numel(str))]); else % Graphics version if ishandle(this.bar) waitbar(proportion, this.bar, newtitle); else % Create the waitbar this.bar = waitbar(proportion, newtitle, 'Name', this.tag_title); end end drawnow(); end end methods (Static = true, Access = private) function val = GetSetPersistent(tag, val) % Ensure the global data structure exists persistent ojw_progressbar_data if isempty(ojw_progressbar_data) ojw_progressbar_data.text_version = ~usejava('desktop'); end if nargin < 2 if isfield(ojw_progressbar_data, tag) val = ojw_progressbar_data.(tag); else val = []; end else ojw_progressbar_data.(tag) = val; end end end end % Time string function function str = timestr(t) s = rem(t, 60); m = rem(floor(t/60), 60); h = floor(t/3600); if h > 0 str= sprintf('%dh%02dm%02.0fs', h, m, s); elseif m > 0 str = sprintf('%dm%02.0fs', m, s); else str = sprintf('%2.1fs', s); end end
github
ojwoodford/ojwul-master
add_genpath_exclude.m
.m
ojwul-master/utils/add_genpath_exclude.m
804
utf_8
ad7336761638201f97ff7c4fbd2a1b78
%ADD_GENPATH_EXCLUDE Add a folder and subdirectories to the path, with exclusions % % add_genpath_exclude(folder_path, ...) % % For example: % add_genpath_exclude('ojwul', '/.git', '\.git') % adds ojwul and subdirectories to the path, excluding .git folders. % %IN: % folder_path - Relative or absolute path to the folder to be added to % the path. % ... - Each trailing input can be a string to be matched within folders % to be excluded. function add_genpath_exclude(path, varargin) if ispc() token = ';'; else token = ':'; end path = cd(cd(path)); path = genpath(path); path = strsplit(path, token); path = path(1:end-1); for str = varargin path = path(cellfun(@isempty, strfind(path, str))); end path = sprintf(['%s' token], path{:}); addpath(path); end
github
ojwoodford/ojwul-master
string2hash.m
.m
ojwul-master/utils/string2hash.m
453
utf_8
89a6f95ed4a295f057af5040c85cac81
%STRING2HASH Convert a string to a 64 char hex hash string (256 bit hash) % % hash = string2hash(string) % %IN: % string - a string! % %OUT: % hash - a 64 character string, encoding the 256 bit SHA hash of string % in hexadecimal. function hash = string2hash(string) persistent md if isempty(md) md = java.security.MessageDigest.getInstance('SHA-256'); end hash = sprintf('%2.2x', typecast(md.digest(uint8(string)), 'uint8')'); end
github
ojwoodford/ojwul-master
col.m
.m
ojwul-master/utils/col.m
391
utf_8
7730db6cdeaee9ea0865f10334719fba
%COL Convert an array to a column vector along a particular dimension % % B = col(A, [dim]) % %IN: % A - Array of any size. % dim - Positive integer indicating the dimension to arrange the elements % of A along. Default: 1. % %OUT: % B - Result of shiftdim(A(:), 1-dim). function x = col(x, dim) x = reshape(x, numel(x), 1); if nargin > 1 x = shiftdim(x, 1-dim); end end
github
ojwoodford/ojwul-master
recurse_subdirs.m
.m
ojwul-master/utils/recurse_subdirs.m
1,769
utf_8
79eab70a46d565eaeeca552e4c34314e
%RECURSE_SUBDIRS Run a function recursively on a directory structure % % varargout = recurse_subdirs(func, base) % % This function calls a function, passing in the path to each subdirectory % in the tree of the current directory (i.e. including subdirectories of % subdirectories). % %IN: % func - A handle for the function to be called recursively. The function % should have the form: varargout = func(base). % base - The path to the directory the function is to be run on. % Default: cd(). % %OUT: % varargout - A cell array of cell arrays of outputs from each call to % func. function varargout = recurse_subdirs(func, base) if nargin < 2 base = cd(); end % Initialize the output [varargout{1:nargout}] = deal({}); % Run on this directory try fprintf('%s ...', base); if nargout == 0 func(base); else [varargout{1:nargout}] = func(base); varargout = cellfun(@(v) {{v}}, varargout); end fprintf(' DONE\n'); catch me fprintf(getReport(me)); end % Go through sub directories for d = dir(base)' if d.isdir && d.name(1) ~= '.' % Do the recursion name = sprintf('%s/%s', base, d.name); if nargout == 0 recurse_subdirs(func, name); else [v{1:nargout}] = recurse_subdirs(func, name); % Store the output if ~all(cellfun(@isempty, v)) if all(cellfun(@isempty, varargout)) varargout = v; else for a = 1:nargout varargout{a} = cat(2, varargout{a}, v{a}); end end end end end end end
github
ojwoodford/ojwul-master
ndgrid_cols.m
.m
ojwul-master/utils/ndgrid_cols.m
727
utf_8
5cbe7e8b53cc0ad85a2e74377eeaac21
%NDGRID_COLS Like NDGRID, but creates column vectors from the outputs % % [X, sz] = ndgrid_cols(...) % % This function applies passes its inputs directly to NDGRID, then converts % the outputs to row vectors, which are stacked vertically, so each % combination of inputs becomes a column vector in the output matrix. % %IN: % varargin - Same as inputs to NDGRID. % %OUT: % X - (nargin)xN matrix of permutation column vectors. % sz - 1xM array of sizes of outputs that ndgrid would produce with the % same inputs, such that N = prod(sz). function [X, sz] = ndgrid_cols(varargin) X = cell(nargin, 1); [X{:}] = ndgrid(varargin{:}); sz = size(X{1}); X = cell2mat(cellfun(@(x) x(:)', X, 'UniformOutput', false)); end
github
ojwoodford/ojwul-master
compile.m
.m
ojwul-master/utils/compile.m
15,693
utf_8
b2adcd1ca5e0fd46a553b939e43229cb
%COMPILE Mex compilation helper function % % Examples: % compile func1 func2 ... -option1 -option2 ... % % This function can be used to (re)compile a number of mex functions, but % is also a helper function enabling inline compilation. function varargout = compile(varargin) % There are two types of call: % 1. compile('func1', 'func2', ..., [options]). % 2. [varargout{1:nargout}] = compile(varargin), called from function to % be compiled. % Work out which this is % Try to get the source list try sourceList = evalin('caller', 'sourceList'); catch sourceList = []; end if iscell(sourceList) %OJW_MEXCOMPILE_SCRIPT Compilation helper script for mex files % % Should be placed in the m-file of a mexed function, after the % following lines of code, thus: % % function varargout = mymex(varargin) % sourceList = {'-Iinclude', '-Llib', 'mymex.c', 'mymexhelper.c', '-lmysharedlib'}; % [varargout{1:nargout} = ojw_mexcompile_script(varargin{:}); % % The script will compile the source inline (i.e. compile & then run) if % the function has been called without first being compiled. % % If varargin{1} == 'compile' and varargin{2} = last_compilation_time, % then the script calls ojw_mexcompile to compile the function if any of % the source files have changed since last_compilation_time. % Get the name of the calling function funcName = dbstack('-completenames'); funcPath = fileparts(funcName(2).file); funcName = funcName(2).name; % Go to the directory containing the file currDir = cd(funcPath); if nargin > 1 && isequal(varargin{1}, 'compile') % Standard compilation behaviour [varargout{1:nargout}] = ojw_mexcompile(funcName, sourceList, varargin{2:end}); % Return to the original directory cd(currDir); else % Function called without first being compiled fprintf('Missing mex file: %s.%s. Will attempt to compile and run.\n', funcName, mexext); retval = ojw_mexcompile(funcName, sourceList); % Return to the original directory cd(currDir); if retval <= 0 % Flag the error error('Unable to compile %s.', funcName); end % Make sure MATLAB registers the new function S = which(funcName, '-all'); % Call the now compiled function again [varargout{1:nargout}] = fevals(funcName, varargin{:}); end return; end % Check for compile flags for a = nargin:-1:1 M(a) = varargin{a}(1) == '-'; end for a = find(~M(:))' % Delete current mex S = which(varargin{a}, '-all'); if ~iscell(S) S = {S}; end s = cellfun(@(s) strcmp(s(end-numel(varargin{a})-1:end), [varargin{a} '.m']), S); if ~any(s) error('Function %s not found on the path', varargin{a}); end s = [S{find(s, 1)}(1:end-2) '.' mexext]; if exist(s, 'file') delete(s); assert(exist(s, 'file') == 0, 'Could not delete the mex file:\n %s\nEither it is write protected or it is locked in use by MATLAB.', s); S = which(varargin{a}, '-all'); % Refresh the function pointed to end % Compile fevals(varargin{a}, 'compile', 0, varargin{M}); % Clear functions and make sure the mex is pointed to clear(varargin{a}); S = which(varargin{a}, '-all'); assert(exist(s, 'file') ~= 0, 'Compilation of %s failed', varargin{a}); end end %OJW_MEXCOMPILE Mex compile helper function % % okay = ojw_mexcompile(funcName) % okay = ojw_mexcompile(..., inputStr) % okay = ojw_mexcompile(..., lastCompiled) % % Compile mexed function, given an optional list of source files and other % compile options. Can optionally check if source files have been modified % since the last compilation, and only compile if they have. % %IN: % funcName - string containg the name of the function to compile % inputStr - cell array of input strings to be passed to mex, e.g. source % file names, include paths, library paths, optimizer flags, % etc. Default: {[funcName '.c']}. % lastCompiled - datenum of the current mex file. Default: 0 (i.e. force % compilation). % %OUT: % okay - 1: function compiled; 0: up-to-date, no need to compile; -1: % compilation failed. function okay = ojw_mexcompile(funcName, varargin) % Determine architecture is64bit = mexext; is64bit = strcmp(is64bit(end-1:end), '64'); % Set defaults for optional inputs sourceList = [funcName '.c']; lastCompiled = 0; % Parse inputs extraOptions = {}; for a = 1:numel(varargin) if iscell(varargin{a}) && ischar(varargin{a}{1}) sourceList = varargin{a}; elseif isnumeric(varargin{a}) && isscalar(varargin{a}) lastCompiled = varargin{a}; elseif ischar(varargin{a}) extraOptions = [extraOptions varargin(a)]; end end sourceList = [sourceList extraOptions]; okay = 0; if lastCompiled compile = false; % Compile if current mex file is older than any of the source files % Note: this doesn't consider included files (e.g. header files) for a = 1:numel(sourceList) dirSource = dir(sourceList{a}); if ~isempty(dirSource) if datenum(dirSource.date) > lastCompiled compile = true; break; end end end else compile = true; end % Exit if not compiling if ~compile return; end okay = -1; debug = false; cudaOptions = cell(0, 1); compiler_options = ''; %L = {''}; % Parse the compile options for a = 1:numel(sourceList) if sourceList{a}(1) == '-' % Found an option (not a source file) switch sourceList{a}(2) case 'N' % Cuda nvcc option cudaOptions{end+1} = sourceList{a}(3:end); sourceList{a} = ''; case 'X' % Special option [sourceList{a}, co] = feval(sourceList{a}(3:end), debug); compiler_options = [compiler_options ' ' co]; case 'C' % Compiler option if ispc() opt = ['/' strrep(sourceList{a}(3:end), '=', ':')]; else opt = ['-' sourceList{a}(3:end)]; end compiler_options = [compiler_options ' ' opt]; sourceList{a} = ''; case 'g' % Debugging on debug = debug | (numel(sourceList{a}) == 2); end else sourceList{a} = ['"' sourceList{a} '"']; end end L = zeros(numel(sourceList), 1); gpucc = []; options_file = []; % Convert any CUDA files to C++, and any Fortran files to object files for a = 1:numel(sourceList) if isempty(sourceList{a}) || sourceList{a}(1) == '-' % Found an option (not a source file) continue; end [ext, ext, ext] = fileparts(sourceList{a}(2:end-1)); switch ext case '.cu' % GPU programming - Convert any *.cu files to *.cpp if isempty(gpucc) % Create nvcc call cudaDir = cuda_path(); options_file = ['"' tempname '.txt"']; fid = fopen(options_file(2:end-1), 'wt'); gpucc = sprintf('"%s%s" --options-file %s', cudaDir, nvcc(), options_file); fprintf(fid, ' -D_MATLAB_ -I"%s%sextern%sinclude" -m%d', matlabroot, filesep, filesep, 32*(1+is64bit)); % Add cuda specific options if ~isempty(cudaOptions) fprintf(fid, ' %s', cudaOptions{:}); end if ispc && is64bit cc = mex.getCompilerConfigurations(); fprintf(fid, ' -ccbin "%s\\VC\\bin" -I"%s\\VC\\include"', cc.Location, cc.Location); end % Add any include directories from source list and cuda % specific options for b = 1:numel(sourceList) if strcmp(sourceList{b}(1:min(2, end)), '-I') fprintf(fid, ' %s', sourceList{b}); end end % Add the debug flag if debug fprintf(fid, ' -g -UNDEBUG -DDEBUG'); else % Apply optimizations fprintf(fid, ' -O3 --use_fast_math'); end fclose(fid); end % Compile to object file outName = ['"' tempname '.o"']; cmd = sprintf('%s --compile "%s" --output-file %s', gpucc, sourceList{a}, outName); disp(cmd); if system(cmd) % Quit fprintf('ERROR while converting %s to %s.\n', sourceList{a}, outName); clean_up([reshape(sourceList(L == 1), [], 1); {options_file}]); return; end sourceList{a} = outName; L(a) = 1; case {'.f', '.f90'} L(a) = 2; end end % Delete the options file if ~isempty(options_file) delete(options_file(2:end-1)); options_file = []; end % Set the compiler flags if debug flags = '-UNDEBUG -DDEBUG'; else flags = '-O -DNDEBUG'; end if any(L == 1) flags = [flags ' ' cuda(debug)]; end switch mexext case {'mexglx', 'mexa64', 'mexmaci64', 'mexmaca64'} if ~debug compiler_options = [compiler_options ' -O3 -ffast-math -funroll-loops']; end flags = sprintf('%s CXXFLAGS="%s" CFLAGS="%s"', flags, compiler_options, compiler_options); case {'mexw32', 'mexw64'} flags = sprintf('%s COMPFLAGS="%s $COMPFLAGS"', flags, compiler_options); end % Call mex to compile the code cmd = sprintf('mex -D_MATLAB_=%d %s%s -output "%s"', [100 1] * sscanf(version(), '%d.%d', 2), flags, sprintf(' %s', sourceList{:}), funcName); disp(cmd); try eval(cmd); okay = 1; catch me fprintf('ERROR while compiling %s\n', funcName); fprintf('%s', getReport(me, 'basic')); end % Clean up clean_up(sourceList(L == 1)); end function clean_up(sourceList) % Delete the intermediate files for a = 1:numel(sourceList) delete(sourceList{a}(2:end-1)); end end function path_str = cuda_path() path_str = user_string('cuda_path'); if check_cuda_path(path_str) return; end % Check the environment variables path_str = fullfile(getenv('CUDA_PATH'), '/'); if check_cuda_path(path_str) user_string('cuda_path', path_str); return; end path_str = get_user_path('CUDA', check_cuda_path, 1); end function good = check_cuda_path(path_str) % Check the cuda path is valid [good, message] = system(sprintf('"%s%s" -h', path_str, nvcc())); good = good == 0; end function path_ = nvcc() path_ = ['bin' filesep 'nvcc']; if ispc path_ = [path_ '.exe']; end end function path_str = cuda_sdk path_str = get_user_path('CUDA SDK', @(p) exist([p 'inc' filesep 'cutil.h'], 'file'), 1, ['C' filesep 'common' filesep]); end % FEVAL for function which is not a subfunction in this file function varargout = fevals(func_name_str, varargin) [varargout{1:nargout}] = feval(str2func(sprintf('@(x) %s(x{:})', func_name_str)), varargin); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%% SPECIAL OPTIONS %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Create the compiler options for cuda function [str, co] = cuda(debug) co = ''; % Set gpu code compiler & linker flags is64bit = mexext; is64bit = strcmp(is64bit(end-1:end), '64'); bitStr = {'32', '', '64', 'Win32', 'x64'}; cudaDir = cuda_path(); str = sprintf('-I"%sinclude" -L"%slib/%s" -lcudart', cudaDir, cudaDir, bitStr{4+is64bit}); end function [str, co] = cudasdk(debug) co = ''; str = sprintf('-I"%sinc"', cuda_sdk); end % Create the compiler options for lapack/blas function [str, co] = lapack(debug) co = ''; str = '-lmwlapack -lmwblas'; % Use MATLAB's versions end % Create the compiler options for OpenMP function [str, co] = openmp(debug) str = ''; co = ''; if ~debug if ispc() co = '/openmp'; elseif ismac() co = '-Xpreprocessor -fopenmp'; str = get_user_path('OpenMP', @(p) exist([p 'include/omp.h'], 'file'), 1); if isfolder(sprintf("%s/sys/os/maci64", matlabroot())) str = sprintf('-I"%sinclude" -L"%s/sys/os/maci64" -liomp5', str, matlabroot()); else str = sprintf('-I"%sinclude" -L"%s/sys/os/maca64" -lomp', str, matlabroot()); end else co = '-fopenmp'; end end end % Create the compiler options for OpenCV function [str, co] = opencv(debug) co = ''; str = get_user_path('OpenCV', @(p) exist([p 'include/opencv2'], 'dir'), 1); str = sprintf('-I"%sinclude" -L"%slib" -lopencv_core -lopencv_calib3d -lopencv_imgproc', str, str); end % Add the boost library directory function [str, co] = boost(debug) co = ''; str = get_user_path('Boost', @(p) exist(sprintf('%sboost%sshared_ptr.hpp', p, filesep), 'file'), 1); str = sprintf('-I"%s" -L"%sstage%slib%s"', str, str, filesep, filesep); end % Add the directX library directory function [str, co] = directx(debug) if ~ispc() error('DirectX only supported on Windows'); end co = ''; str = get_user_path('DirectX SDK', @(p) exist(sprintf('%sLib%sx86%sdxguid.lib', p, filesep, filesep), 'file'), 1); str = sprintf('-L"%sLib%sx%d"', str, filesep, 86-22*is64bit()); end % Add the Eigen include directory function [str, co] = eigen(debug) co = ''; str = get_user_path('Eigen', @(p) exist(sprintf('%sEigen%sCore', p, filesep), 'file'), 1); str = sprintf('-I"%s"', str(1:end-1)); if ~debug str = [str ' -DEIGEN_NO_DEBUG']; end end % Add the Ceres library directory function [str, co] = ceres(debug) co = ''; str = get_user_path('Ceres', @(p) exist(sprintf('%sinclude%sceres%sceres.h', p, filesep, filesep), 'file'), 1); str = sprintf('-I"%sinclude" -I"%sconfig" -L"%slib" -lceres', str, str, str); end % Add the Suite Sparse library directory function [str, co] = suitesparse(debug) co = ''; str = get_user_path('SuiteSparse', @(p) exist(sprintf('%sinclude%sSuiteSparse_config.h', p, filesep), 'file'), 1); str = sprintf('-I"%sinclude" -L"%slib" -lcholmod', str, str); end % Add the glog library directory function [str, co] = glog(debug) co = ''; str = get_user_path('glog', @(p) exist(sprintf('%sinclude%sglog%slogging.h', p, filesep, filesep), 'file'), 1); str = sprintf('-I"%sinclude" -L"%slib" -lglog', str, str); end % Add the gflags library directory function [str, co] = gflags(debug) co = ''; str = get_user_path('glflags', @(p) exist(sprintf('%sinclude%sgflags%sgflags.h', p, filesep, filesep), 'file'), 1); str = sprintf('-I"%sinclude" -L"%slib" -lgflags', str, str); end % Add the Sophus include directory function [str, co] = sophus(debug) co = ''; str = get_user_path('Sophus', @(p) exist(sprintf('%ssophus%sse3.hpp', p, filesep), 'file'), 1); str = sprintf('-I"%s"', str(1:end-1)); end % Add the liegroups library function [str, co] = liegroups(debug) co = ''; str = get_user_path('liegroups', @(p) exist(sprintf('%sse3.hpp', p), 'file'), 1); if debug debug = 'Debug'; else debug = 'Release'; end str = sprintf('-I"%s/.." -L"%s/build/%s" -lliegroups', str, str, debug); end % Add the ojwul include directory function [str, co] = ojwul(debug) co = ''; str = sprintf('-I"%s"', fileparts(fileparts(mfilename('fullpath')))); end
github
ojwoodford/ojwul-master
temp_cd.m
.m
ojwul-master/utils/temp_cd.m
486
utf_8
d5d5464b0d93132d4d3e0090e0ec7165
%TEMP_CD Switch to a directory for the duration of the calling function % % cwd = temp_cd(dirname) % %IN: % dirname - Full or relative path to the directory to switch to. % %OUT: % cwd - Path string to current directory. function cwd = temp_cd(dirname) assert(evalin('caller', 'exist(''temp_cd_cleanupObj'', ''var'');') == 0, 'temp_cd cannot be called twice in the same function'); cwd = cd(dirname); co = onCleanup(@() cd(cwd)); assignin('caller', 'temp_cd_cleanupObj', co); end
github
ojwoodford/ojwul-master
str2fun.m
.m
ojwul-master/utils/str2fun.m
1,423
utf_8
cbdee8fc068af54566c8a6c414da697f
%STR2FUN Construct a function_handle from a function name or path. % FUNHANDLE = STR2FUN(S) constructs a function_handle FUNHANDLE to the % function named in the character vector S. The S input must be a % character vector. The S input cannot be a character array with % multiple rows or a cell array of character vectors. % % You can create a function handle using either the @function syntax or % the STR2FUN command. You can create an array of function handles from % character vectors by creating the handles individually with STR2FUN, % and then storing these handles in a cell array. % % Examples: % % To create a function handle from the function name, 'humps': % % fhandle = str2func('humps') % fhandle = % @humps % % To call STR2FUNC on a cell array of character vectors, use the % CELLFUN function. This returns a cell array of function handles: % % fh_array = cellfun(@str2func, {'sin' 'cos' 'tan'}, ... % 'UniformOutput', false); % fh_array{2}(5) % ans = % 0.2837 % % See also STR2FUNC, FUNCTION_HANDLE, FUNC2STR, FUNCTIONS. function fun = str2fun(str) assert(ischar(str)); if str(1) ~= '@' [p, str] = fileparts(str); if ~isempty(p) cwd = cd(p); cleanup_obj = onCleanup(@() cd(cwd)); end end fun = evalin('caller', sprintf('str2func(''%s'')', str)); end
github
ojwoodford/ojwul-master
vgg_argparse.m
.m
ojwul-master/utils/vgg_argparse.m
1,946
utf_8
9831dc65a204ed7cf28af3acd5487ffd
%VGG_ARGPARSE Parse variable arguments into a structure % opts = vgg_argparse(inopts,varargin) % inopts: structure (cells array) listing valid members and default values % varargin: variable arguments of form '<name>',<value>,... % opts: opts modified by varargin % % Example: % function f = foo(varargin) % opts = vgg_argparse(struct('maxiters',10,'verbose',0), varargin) % ... % % An unknown option (ie, present in varargin but absent in inopts) % causes an error. Calling the function as % [opts,rem_opts] = vgg_argparse(inopts,varargin) returns the unknown % option(s) in rem_opts for later use rather than causes an error. % % May also use OPTS = VGG_ARGPARSE(OPTS, ASTRUCT) where ASTRUCT is a struct % of options. % Author: Mark Everingham <[email protected]> % modified by werner, Jan 03 % modified by ojw, Mar 14 % Date: 16 Jan 02 function [opts, rem_opts] = vgg_argparse(opts, varargin) if iscell(opts) opts = struct(opts{:}); end inopts = -1; if isempty(varargin) inopts = struct([]); elseif nargin == 2 if isempty(varargin{1}) inopts = struct([]); elseif isstruct(varargin{1}) inopts = varargin{1}; elseif iscell(varargin{1}) varargin = varargin{1}; if isstruct(varargin{1}) inopts = varargin{1}; end else error('Single argument'); end end if isequal(inopts, -1) % Construct struct in for loop to allow duplicates (overwrite) inopts = struct(); for a = 1:2:numel(varargin)-1 inopts.(varargin{a}) = varargin{a+1}; end end rem_opts = []; for fn = fieldnames(inopts)' if isfield(opts, fn{1}) opts.(fn{1}) = inopts.(fn{1}); else rem_opts.(fn{1}) = inopts.(fn{1}); end end if nargout < 2 && ~isempty(rem_opts) v = fieldnames(rem_opts); error(['Bad arguments: ' sprintf('''%s'' ', v{:})]); end
github
ojwoodford/ojwul-master
user_string.m
.m
ojwul-master/utils/user_string.m
3,273
utf_8
1001def19cdf03ef0095097e934b6640
%USER_STRING Get/set a user specific string % % Examples: % string = user_string(string_name) % isSaved = user_string(string_name, new_string) % % Function to get and set a string in a system or user specific file. This % enables, for example, system specific paths to binaries to be saved. % % The specified string will be saved in a file named <string_name>.txt, % either in a subfolder named .ignore under this file's folder, or in the % user's prefdir folder (in case this file's folder is non-writable). % % IN: % string_name - String containing the name of the string required, which % sets the filename storing the string: <string_name>.txt % new_string - The new string to be saved in the <string_name>.txt file % % OUT: % string - The currently saved string. Default: '' % isSaved - Boolean indicating whether the save was succesful % Copyright (C) Oliver Woodford 2011-2014, Yair Altman 2015- % This method of saving paths avoids changing .m files which might be in a % version control system. Instead it saves the user dependent paths in % separate files with a .txt extension, which need not be checked in to % the version control system. Thank you to Jonas Dorn for suggesting this % approach. % 10/01/2013 - Access files in text, not binary mode, as latter can cause % errors. Thanks to Christian for pointing this out. % 29/05/2015 - Save file in prefdir if current folder is non-writable (issue #74) function string = user_string(string_name, string) if ~ischar(string_name) error('string_name must be a string.'); end % Create the full filename fname = [string_name '.txt']; dname = fullfile(fileparts(mfilename('fullpath')), '.ignore'); file_name = fullfile(dname, fname); if nargin > 1 % Set string if ~ischar(string) error('new_string must be a string.'); end % Make sure the save directory exists %dname = fileparts(file_name); if ~exist(dname, 'dir') % Create the directory try if ~mkdir(dname) string = false; return end catch string = false; return end % Make it hidden try fileattrib(dname, '+h'); catch end end % Write the file fid = fopen(file_name, 'wt'); if fid == -1 % file cannot be created/updated - use prefdir if file does not already exist % (if file exists but is simply not writable, don't create a duplicate in prefdir) if ~exist(file_name,'file') file_name = fullfile(prefdir, fname); fid = fopen(file_name, 'wt'); end if fid == -1 string = false; return; end end try fprintf(fid, '%s', string); catch fclose(fid); string = false; return end fclose(fid); string = true; else % Get string fid = fopen(file_name, 'rt'); if fid == -1 % file cannot be read, try to read the file in prefdir file_name = fullfile(prefdir, fname); fid = fopen(file_name, 'rt'); if fid == -1 string = ''; return end end string = fgetl(fid); fclose(fid); end end
github
ojwoodford/ojwul-master
bsxfun.m
.m
ojwul-master/utils/bsxfun.m
4,309
utf_8
2f5ffcbfa7ab333f15990ab47e3fe49f
% BSXFUN Binary Singleton Expansion Function % C = BSXFUN(FUNC,A,B) applies the element-by-element binary operation % specified by the function handle FUNC to arrays A and B, with singleton % expansion enabled. FUNC can be one of the following built-in functions: % % @plus Plus % @minus Minus % @times Array multiply % @rdivide Right array divide % @ldivide Left array divide % @power Array power % @max Binary maximum % @min Binary minimum % @rem Remainder after division % @mod Modulus after division % @atan2 Four-quadrant inverse tangent; result in radians % @atan2d Four-quadrant inverse tangent; result in dgrees % @hypot Square root of sum of squares % @eq Equal % @ne Not equal % @lt Less than % @le Less than or equal % @gt Greater than % @ge Greater than or equal % @and Element-wise logical AND % @or Element-wise logical OR % @xor Logical EXCLUSIVE OR % % FUNC can also be a handle to any binary element-wise function not listed % above. A binary element-wise function in the form of C = FUNC(A,B) % accepts arrays A and B of arbitrary but equal size and returns output % of the same size. Each element in the output array C is the result % of an operation on the corresponding elements of A and B only. FUNC must % also support scalar expansion, such that if A or B is a scalar, C is the % result of applying the scalar to every element in the other input array. % % The corresponding dimensions of A and B must be equal to each other, or % equal to one. Whenever a dimension of A or B is singleton (equal to % one), BSXFUN virtually replicates the array along that dimension to % match the other array. In the case where a dimension of A or B is % singleton and the corresponding dimension in the other array is zero, % BSXFUN virtually diminishes the singleton dimension to zero. % % The size of the output array C is equal to % max(size(A),size(B)).*(size(A)>0 & size(B)>0). For example, if % size(A) == [2 5 4] and size(B) == [2 1 4 3], then size(C) == [2 5 4 3]. % % Examples: % % Subtract the column means from the matrix A: % A = magic(5); % A = bsxfun(@minus, A, mean(A)); % % Scale each row of A by its maximum absolute value: % A = rand(5); % A = bsxfun(@rdivide, A, max(abs(A),[],2)); % % Compute z(x, y) = x.*sin(y) on a grid: % x = 1:10; % y = x.'; % z = bsxfun(@(x, y) x.*sin(y), x, y); % % See also REPMAT, ARRAYFUN function C = bsxfun(func, A, B) % Catch bsxfun on symbolic arrays if ~isa(A, 'sym') && ~isa(B, 'sym') % Call the normal bsxfun C = builtin('bsxfun', func, A, B); else % Repmat method if isscalar(A) C = reshape(func(A, B(:)), size(B)); return elseif isscalar(B) C = reshape(func(A(:), B), size(A)); return end sA = size(A); sB = size(B); % Enlarge the smaller of the two sizes s = numel(sA) - numel(sB); if s < 0 sA = [sA ones(1, -s)]; elseif s > 0 sB = [sB ones(1, s)]; end % Calculate the output array size sMax = max(sA, sB) .* (sA > 0 & sB > 0); % Make sure arrays have same size of dimension or size 1 a = sA ~= sMax; b = sB ~= sMax; if any(a & sA ~= 1) || any(b & sB ~= 1) error('A and B must have equal or singleton dimensions'); end if ~all(sMax) % Some entries are zero, so array is empty C = sym(zeros(sMax)); return end % Resize the arrays to have the same size, sMax if any(a) A = repmat(A, sMax ./ sA); end if any(b) B = repmat(B, sMax ./ sB); end % Apply the function C = reshape(func(A(:), B(:)), sMax); end end
github
ojwoodford/ojwul-master
maximize.m
.m
ojwul-master/utils/maximize.m
884
utf_8
2b1e724a67b717d50a29e1186d1e6612
%MAXIMIZE Maximize a figure window to fill the entire screen % % Examples: % maximize % maximize(hFig) % % Maximizes the current or input figure so that it fills the whole of the % screen that the figure is currently on. This function is platform % independent. % %IN: % hFig - Handle of figure to maximize. Default: gcf. function maximize(hFig) if nargin < 1 hFig = gcf(); end % Java-less method (since R2018a) if exist('verLessThan', 'file') && ~verLessThan('matlab', '9.4') set(hFig, 'WindowState', 'maximized'); return; end % Old Java version drawnow(); % Required to avoid Java errors set(hFig, 'WindowStyle', 'normal'); % Suppress warning about Java obsoletion oldState = warning('off', 'MATLAB:HandleGraphics:ObsoletedProperty:JavaFrame'); jFig = get(handle(hFig), 'JavaFrame'); jFig.setMaximized(true); warning(oldState); end
github
ojwoodford/ojwul-master
bitwise_hamming.m
.m
ojwul-master/bitwise/bitwise_hamming.m
4,768
utf_8
9f5bb67a39572295bc759ee01457d8c9
%BITWISE_HAMMING Compute all hamming distances between two sets of bit vectors % % C = bitwise_hamming(A, B, [thresh]) % % Given two sets of bit vectors (each column being a bit vector), compute % the hamming distances between all pairs of vectors between the two sets. % If a threshold is given, return only those values below the threshold. % %IN: % A - MxP matrix of bit vectors. % B - MxQ matrix of bit vectors. % thresh - A scalar bit count threshold. % %OUT: % C - PxQ matrix of bitwise hamming distances, or Nx3 is of values be;low % the threshold distance, thresh (if given), where each row is function C = bitwise_hamming(A, B, thresh) % Typecast to integer [A, bytelen] = cast_to_largest_integer(A); [B, bytelenb] = cast_to_largest_integer(B); assert(bytelen == bytelenb, 'Input columns must be of the same bit-length'); % Get the input sizes [a, a] = size(A); [c, b] = size(B); % Check if joint array less than 64MB if a * b * bytelen < 67108864 % Do the bitxor in one go A = repmat(A, [1 1 b]); B = repmat(reshape(B, c, 1, b), [1 a 1]); C = reshape(bitcount(bitxor(A, B)), a, b); if nargin > 2 M = find(C < thresh); L(:,3) = double(C(M)); [L(:,1), L(:,2)] = ind2sub(size(C), M); C = L; end else % Do the bitxor in a loop, to avoid too much memory use if nargin > 2 C = zeros(a*b, 3); I = 0; if c == 1 if b > a % Do the smallest for loop for i = a:-1:1 D = bitcount(bitxor(A(:,i), B))'; M = find(D < thresh); if isempty(M) continue; end I = I(end)+1:I(end)+numel(M); C(I,2) = M; C(I,3) = D(M); C(I,1) = i; end else for i = b:-1:1 D = bitcount(bitxor(B(:,i), A)); M = find(D < thresh); if isempty(M) continue; end I = I(end)+1:I(end)+numel(M); C(I,1) = M; C(I,3) = D(M); C(I,2) = i; end end else if b > a % Do the smallest for loop for i = a:-1:1 D = bitcount(bitxor(repmat(A(:,i), [1 b]), B))'; M = find(D < thresh); if isempty(M) continue; end I = I(end)+1:I(end)+numel(M); C(I,2) = M; C(I,3) = D(M); C(I,1) = i; end else for i = b:-1:1 D = bitcount(bitxor(repmat(B(:,i), [1 a]), A)); M = find(D < thresh); if isempty(M) continue; end I = I(end)+1:I(end)+numel(M); C(I,1) = M; C(I,3) = D(M); C(I,2) = i; end end end C = C(1:I(end),:); else if c == 1 if b > a % Do the smallest for loop for i = a:-1:1 C(i,:) = bitcount(bitxor(A(:,i), B)); end else for i = b:-1:1 C(:,i) = bitcount(bitxor(B(:,i), A))'; end end else if b > a % Do the smallest for loop for i = a:-1:1 C(i,:) = bitcount(bitxor(repmat(A(:,i), [1 b]), B)); end else for i = b:-1:1 C(:,i) = bitcount(bitxor(repmat(B(:,i), [1 a]), A))'; end end end end end end function [A, bytelen] = cast_to_largest_integer(A) [a, b] = size(A); switch class(A) case {'double', 'int64', 'uint64'} bytelen = 8 * a; case {'single', 'int32', 'uint32'} bytelen = 4 * a; case {'int16', 'uint16'} bytelen = 2 * a; case {'int8', 'uint8'} bytelen = a; otherwise error('Class %s not supported.', class(A)); end if mod(bytelen, 8) == 0 A = reshape(typecast(A(:), 'uint64'), bytelen/8, b); elseif mod(bytelen, 4) == 0 A = reshape(typecast(A(:), 'uint32'), bytelen/4, b); elseif mod(bytelen, 2) == 0 A = reshape(typecast(A(:), 'uint16'), bytelen/2, b); else A = reshape(typecast(A(:), 'uint8'), bytelen, b); end end
github
ojwoodford/ojwul-master
DataHash.m
.m
ojwul-master/bitwise/DataHash.m
22,490
utf_8
f8f52f3077dddaf31779b71355a47695
function Hash = DataHash(Data, varargin) % DATAHASH - Checksum for Matlab array of any type % This function creates a hash value for an input of any type. The type and % dimensions of the input are considered as default, such that UINT8([0,0]) and % UINT16(0) have different hash values. Nested STRUCTs and CELLs are parsed % recursively. % % Hash = DataHash(Data, Opts...) % INPUT: % Data: Array of these built-in types: % (U)INT8/16/32/64, SINGLE, DOUBLE, (real/complex, full/sparse) % CHAR, LOGICAL, CELL (nested), STRUCT (scalar or array, nested), % function_handle, string. % Opts: Char strings to specify the method, the input and theoutput types: % Input types: % 'array': The contents, type and size of the input [Data] are % considered for the creation of the hash. Nested CELLs % and STRUCT arrays are parsed recursively. Empty arrays of % different type reply different hashs. % 'file': [Data] is treated as file name and the hash is calculated % for the files contents. % 'bin': [Data] is a numerical, LOGICAL or CHAR array. Only the % binary contents of the array is considered, such that % e.g. empty arrays of different type reply the same hash. % 'ascii': Same as 'bin', but only the 8-bit ASCII part of the 16-bit % Matlab CHARs is considered. % Output types: % 'hex', 'HEX': Lower/uppercase hexadecimal string. % 'double', 'uint8': Numerical vector. % 'base64': Base64. % 'short': Base64 without padding. % Hashing method: % 'SHA-1', 'SHA-256', 'SHA-384', 'SHA-512', 'MD2', 'MD5'. % Call DataHash without inputs to get a list of available methods. % % Default: 'MD5', 'hex', 'array' % % OUTPUT: % Hash: String, DOUBLE or UINT8 vector. The length depends on the hashing % method. % If DataHash is called without inputs, a struct is replied: % .HashVersion: Version number of the hashing method of this tool. In % case of bugs or additions, the output can change. % .Date: Date of release of the current HashVersion. % .HashMethod: Cell string of the recognized hash methods. % % EXAMPLES: % % Default: MD5, hex: % DataHash([]) % 5b302b7b2099a97ba2a276640a192485 % % MD5, Base64: % DataHash(int32(1:10), 'short', 'MD5') % +tJN9yeF89h3jOFNN55XLg % % SHA-1, Base64: % S.a = uint8([]); % S.b = {{1:10}, struct('q', uint64(415))}; % DataHash(S, 'SHA-1', 'HEX') % 18672BE876463B25214CA9241B3C79CC926F3093 % % SHA-1 of binary values: % DataHash(1:8, 'SHA-1', 'bin') % 826cf9d3a5d74bbe415e97d4cecf03f445f69225 % % SHA-256, consider ASCII part only (Matlab's CHAR has 16 bits!): % DataHash('abc', 'SHA-256', 'ascii') % % ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad % % Or equivalently by converting the input to UINT8: % DataHash(uint8('abc'), 'SHA-256', 'bin') % % NOTES: % Function handles and user-defined objects cannot be converted uniquely: % - The subfunction ConvertFuncHandle uses the built-in function FUNCTIONS, % but the replied struct can depend on the Matlab version. % - It is tried to convert objects to UINT8 streams in the subfunction % ConvertObject. A conversion by STRUCT() might be more appropriate. % Adjust these subfunctions on demand. % % MATLAB CHARs have 16 bits! Use Opt.Input='ascii' for comparisons with e.g. % online hash generators. % % Matt Raum suggested this for e.g. user-defined objects: % DataHash(getByteStreamFromArray(Data)) % This works very well, but unfortunately getByteStreamFromArray is % undocumented, such that it might vanish in the future or reply different % output. % % For arrays the calculated hash value might be changed in new versions. % Calling this function without inputs replies the version of the hash. % % The older style for input arguments is accepted also: Struct with fields % 'Input', 'Method', 'OutFormat'. % % The C-Mex function GetMD5 is 2 to 100 times faster, but obtains MD5 only: % http://www.mathworks.com/matlabcentral/fileexchange/25921 % % Tested: Matlab 2009a, 2015b(32/64), 2016b, 2018b, Win7/10 % Author: Jan Simon, Heidelberg, (C) 2011-2019 matlab.2010(a)n(MINUS)simon.de % % See also: TYPECAST, CAST. % % Michael Kleder, "Compute Hash", no structs and cells: % http://www.mathworks.com/matlabcentral/fileexchange/8944 % Tim, "Serialize/Deserialize", converts structs and cells to a byte stream: % http://www.mathworks.com/matlabcentral/fileexchange/29457 % Copyright (c) 2018-2019, Jan Simon % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are met: % % * Redistributions of source code must retain the above copyright notice, this % list of conditions and the following disclaimer. % % * 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 % * Neither the name of nor the names of its % contributors may be used to endorse or promote products derived from this % software without specific prior written permission. % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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. % $JRev: R-R V:043 Sum:VbfXFn6217Hp Date:18-Apr-2019 12:11:42 $ % $License: BSD (use/copy/change/redistribute on own risk, mention the author) $ % $UnitTest: uTest_DataHash $ % $File: Tools\GLFile\DataHash.m $ % History: % 001: 01-May-2011 21:52, First version. % 007: 10-Jun-2011 10:38, [Opt.Input], binary data, complex values considered. % 011: 26-May-2012 15:57, Fixed: Failed for binary input and empty data. % 014: 04-Nov-2012 11:37, Consider Mex-, MDL- and P-files also. % Thanks to David (author 243360), who found this bug. % Jan Achterhold (author 267816) suggested to consider Java objects. % 016: 01-Feb-2015 20:53, Java heap space exhausted for large files. % Now files are process in chunks to save memory. % 017: 15-Feb-2015 19:40, Collsions: Same hash for different data. % Examples: zeros(1,1) and zeros(1,1,0) % complex(0) and zeros(1,1,0,0) % Now the number of dimensions is included, to avoid this. % 022: 30-Mar-2015 00:04, Bugfix: Failed for strings and [] without TYPECASTX. % Ross found these 2 bugs, which occur when TYPECASTX is not installed. % If you need the base64 format padded with '=' characters, adjust % fBase64_enc as you like. % 026: 29-Jun-2015 00:13, Changed hash for STRUCTs. % Struct arrays are analysed field by field now, which is much faster. % 027: 13-Sep-2015 19:03, 'ascii' input as abbrev. for Input='bin' and UINT8(). % 028: 15-Oct-2015 23:11, Example values in help section updated to v022. % 029: 16-Oct-2015 22:32, Use default options for empty input. % 031: 28-Feb-2016 15:10, New hash value to get same reply as GetMD5. % New Matlab version (at least 2015b) use a fast method for TYPECAST, such % that calling James Tursa's TYPECASTX is not needed anymore. % Matlab 6.5 not supported anymore: MException for CATCH. % 033: 18-Jun-2016 14:28, BUGFIX: Failed on empty files. % Thanks to Christian (AuthorID 2918599). % 035: 19-May-2018 01:11, STRING type considered. % 040: 13-Nov-2018 01:20, Fields of Opt not case-sensitive anymore. % 041: 09-Feb-2019 18:12, ismethod(class(V),) to support R2018b. % 042: 02-Mar-2019 18:39, base64: in Java, short: Base64 with padding. % Unit test. base64->short. % OPEN BUGS: % Nath wrote: % function handle refering to struct containing the function will create % infinite loop. Is there any workaround ? % Example: % d= dynamicprops(); % addprop(d,'f'); % d.f= @(varargin) struct2cell(d); % DataHash(d.f) % infinite loop % This is caught with an error message concerning the recursion limit now. %#ok<*CHARTEN> % Reply current version if called without inputs: ------------------------------ if nargin == 0 R = Version_L; if nargout == 0 disp(R); else Hash = R; end return; end % Parse inputs: ---------------------------------------------------------------- [Method, OutFormat, isFile, isBin, Data] = ParseInput(Data, varargin{:}); % Create the engine: ----------------------------------------------------------- try Engine = java.security.MessageDigest.getInstance(Method); catch ME % Handle errors during initializing the engine: if ~usejava('jvm') Error_L('needJava', 'DataHash needs Java.'); end Error_L('BadInput2', 'Invalid hashing algorithm: [%s]. %s', ... Method, ME.message); end % Create the hash value: ------------------------------------------------------- if isFile [FID, Msg] = fopen(Data, 'r'); % Open the file if FID < 0 Error_L('BadFile', ['Cannot open file: %s', char(10), '%s'], Data, Msg); end % Read file in chunks to save memory and Java heap space: Chunk = 1e6; % Fastest for 1e6 on Win7/64, HDD Count = Chunk; % Dummy value to satisfy WHILE condition while Count == Chunk [Data, Count] = fread(FID, Chunk, '*uint8'); if Count ~= 0 % Avoid error for empty file Engine.update(Data); end end fclose(FID); elseif isBin % Contents of an elementary array, type tested already: if ~isempty(Data) % Engine.update fails for empty input! if isnumeric(Data) if isreal(Data) Engine.update(typecast(Data(:), 'uint8')); else Engine.update(typecast(real(Data(:)), 'uint8')); Engine.update(typecast(imag(Data(:)), 'uint8')); end elseif islogical(Data) % TYPECAST cannot handle LOGICAL Engine.update(typecast(uint8(Data(:)), 'uint8')); elseif ischar(Data) % TYPECAST cannot handle CHAR Engine.update(typecast(uint16(Data(:)), 'uint8')); % Bugfix: Line removed elseif myIsString(Data) if isscalar(Data) Engine.update(typecast(uint16(Data{1}), 'uint8')); else Error_L('BadBinData', 'Bin type requires scalar string.'); end else % This should have been caught above! Error_L('BadBinData', 'Data type not handled: %s', class(Data)); end end else % Array with type: Engine = CoreHash(Data, Engine); end % Calculate the hash: ---------------------------------------------------------- Hash = typecast(Engine.digest, 'uint8'); % Convert hash specific output format: ----------------------------------------- switch OutFormat case 'hex' Hash = sprintf('%.2x', double(Hash)); case 'HEX' Hash = sprintf('%.2X', double(Hash)); case 'double' Hash = double(reshape(Hash, 1, [])); case 'uint8' Hash = reshape(Hash, 1, []); case 'short' Hash = fBase64_enc(double(Hash), 0); case 'base64' Hash = fBase64_enc(double(Hash), 1); otherwise Error_L('BadOutFormat', ... '[Opt.Format] must be: HEX, hex, uint8, double, base64.'); end end % ****************************************************************************** function Engine = CoreHash(Data, Engine) % Consider the type and dimensions of the array to distinguish arrays with the % same data, but different shape: [0 x 0] and [0 x 1], [1,2] and [1;2], % DOUBLE(0) and SINGLE([0,0]): % < v016: [class, size, data]. BUG! 0 and zeros(1,1,0) had the same hash! % >= v016: [class, ndims, size, data] Engine.update([uint8(class(Data)), ... typecast(uint64([ndims(Data), size(Data)]), 'uint8')]); if issparse(Data) % Sparse arrays to struct: [S.Index1, S.Index2, S.Value] = find(Data); Engine = CoreHash(S, Engine); elseif isstruct(Data) % Hash for all array elements and fields: F = sort(fieldnames(Data)); % Ignore order of fields for iField = 1:length(F) % Loop over fields aField = F{iField}; Engine.update(uint8(aField)); for iS = 1:numel(Data) % Loop over elements of struct array Engine = CoreHash(Data(iS).(aField), Engine); end end elseif iscell(Data) % Get hash for all cell elements: for iS = 1:numel(Data) Engine = CoreHash(Data{iS}, Engine); end elseif isempty(Data) % Nothing to do elseif isnumeric(Data) if isreal(Data) Engine.update(typecast(Data(:), 'uint8')); else Engine.update(typecast(real(Data(:)), 'uint8')); Engine.update(typecast(imag(Data(:)), 'uint8')); end elseif islogical(Data) % TYPECAST cannot handle LOGICAL Engine.update(typecast(uint8(Data(:)), 'uint8')); elseif ischar(Data) % TYPECAST cannot handle CHAR Engine.update(typecast(uint16(Data(:)), 'uint8')); elseif myIsString(Data) % [19-May-2018] String class in >= R2016b classUint8 = uint8([117, 105, 110, 116, 49, 54]); % 'uint16' for iS = 1:numel(Data) % Emulate without recursion: Engine = CoreHash(uint16(Data{iS}), Engine) aString = uint16(Data{iS}); Engine.update([classUint8, ... typecast(uint64([ndims(aString), size(aString)]), 'uint8')]); if ~isempty(aString) Engine.update(typecast(uint16(aString), 'uint8')); end end elseif isa(Data, 'function_handle') Engine = CoreHash(ConvertFuncHandle(Data), Engine); elseif (isobject(Data) || isjava(Data)) && ismethod(class(Data), 'hashCode') Engine = CoreHash(char(Data.hashCode), Engine); else % Most likely a user-defined object: try BasicData = ConvertObject(Data); catch ME error(['JSimon:', mfilename, ':BadDataType'], ... '%s: Cannot create elementary array for type: %s\n %s', ... mfilename, class(Data), ME.message); end try Engine = CoreHash(BasicData, Engine); catch ME if strcmpi(ME.identifier, 'MATLAB:recursionLimit') ME = MException(['JSimon:', mfilename, ':RecursiveType'], ... '%s: Cannot create hash for recursive data type: %s', ... mfilename, class(Data)); end throw(ME); end end end % ****************************************************************************** function [Method, OutFormat, isFile, isBin, Data] = ParseInput(Data, varargin) % Default options: ------------------------------------------------------------- Method = 'MD5'; OutFormat = 'hex'; isFile = false; isBin = false; % Check number and type of inputs: --------------------------------------------- nOpt = nargin - 1; Opt = varargin; if nOpt == 1 && isa(Opt{1}, 'struct') % Old style Options as struct: Opt = struct2cell(Opt{1}); nOpt = numel(Opt); end % Loop over strings in the input: ---------------------------------------------- for iOpt = 1:nOpt aOpt = Opt{iOpt}; if ~ischar(aOpt) Error_L('BadInputType', '[Opt] must be a struct or chars.'); end switch lower(aOpt) case 'file' % Data contains the file name: isFile = true; case {'bin', 'binary'} % Just the contents of the data: if (isnumeric(Data) || ischar(Data) || islogical(Data) || ... myIsString(Data)) == 0 || issparse(Data) Error_L('BadDataType', ['[Bin] input needs data type: ', ... 'numeric, CHAR, LOGICAL, STRING.']); end isBin = true; case 'array' isBin = false; % Is the default already case {'asc', 'ascii'} % 8-bit part of MATLAB CHAR or STRING: isBin = true; if ischar(Data) Data = uint8(Data); elseif myIsString(Data) && numel(Data) == 1 Data = uint8(char(Data)); else Error_L('BadDataType', ... 'ASCII method: Data must be a CHAR or scalar STRING.'); end case 'hex' if aOpt(1) == 'H' OutFormat = 'HEX'; else OutFormat = 'hex'; end case {'double', 'uint8', 'short', 'base64'} OutFormat = lower(aOpt); otherwise % Guess that this is the method: Method = upper(aOpt); end end end % ****************************************************************************** function FuncKey = ConvertFuncHandle(FuncH) % The subfunction ConvertFuncHandle converts function_handles to a struct % using the Matlab function FUNCTIONS. The output of this function changes % with the Matlab version, such that DataHash(@sin) replies different hashes % under Matlab 6.5 and 2009a. % An alternative is using the function name and name of the file for % function_handles, but this is not unique for nested or anonymous functions. % If the MATLABROOT is removed from the file's path, at least the hash of % Matlab's toolbox functions is (usually!) not influenced by the version. % Finally I'm in doubt if there is a unique method to hash function handles. % Please adjust the subfunction ConvertFuncHandles to your needs. % The Matlab version influences the conversion by FUNCTIONS: % 1. The format of the struct replied FUNCTIONS is not fixed, % 2. The full paths of toolbox function e.g. for @mean differ. FuncKey = functions(FuncH); % Include modification file time and file size. Suggested by Aslak Grinsted: if ~isempty(FuncKey.file) d = dir(FuncKey.file); if ~isempty(d) FuncKey.filebytes = d.bytes; FuncKey.filedate = d.datenum; end end % ALTERNATIVE: Use name and path. The <matlabroot> part of the toolbox functions % is replaced such that the hash for @mean does not depend on the Matlab % version. % Drawbacks: Anonymous functions, nested functions... % funcStruct = functions(FuncH); % funcfile = strrep(funcStruct.file, matlabroot, '<MATLAB>'); % FuncKey = uint8([funcStruct.function, ' ', funcfile]); % Finally I'm afraid there is no unique method to get a hash for a function % handle. Please adjust this conversion to your needs. end % ****************************************************************************** function DataBin = ConvertObject(DataObj) % Convert a user-defined object to a binary stream. There cannot be a unique % solution, so this part is left for the user... try % Perhaps a direct conversion is implemented: DataBin = uint8(DataObj); % Matt Raum had this excellent idea - unfortunately this function is % undocumented and might not be supported in te future: % DataBin = getByteStreamFromArray(DataObj); catch % Or perhaps this is better: WarnS = warning('off', 'MATLAB:structOnObject'); DataBin = struct(DataObj); warning(WarnS); end end % ****************************************************************************** function Out = fBase64_enc(In, doPad) % Encode numeric vector of UINT8 values to base64 string. B64 = org.apache.commons.codec.binary.Base64; Out = char(B64.encode(In)).'; if ~doPad Out(Out == '=') = []; end % Matlab method: % Pool = [65:90, 97:122, 48:57, 43, 47]; % [0:9, a:z, A:Z, +, /] % v8 = [128; 64; 32; 16; 8; 4; 2; 1]; % v6 = [32, 16, 8, 4, 2, 1]; % % In = reshape(In, 1, []); % X = rem(floor(bsxfun(@rdivide, In, v8)), 2); % d6 = rem(numel(X), 6); % if d6 ~= 0 % X = [X(:); zeros(6 - d6, 1)]; % end % Out = char(Pool(1 + v6 * reshape(X, 6, []))); % % p = 3 - rem(numel(Out) - 1, 4); % if doPad && p ~= 0 % Standard base64 string with trailing padding: % Out = [Out, repmat('=', 1, p)]; % end end % ****************************************************************************** function T = myIsString(S) % isstring was introduced in R2016: persistent hasString if isempty(hasString) matlabVer = [100, 1] * sscanf(version, '%d.', 2); hasString = (matlabVer >= 901); % isstring existing since R2016b end T = hasString && isstring(S); % Short-circuting end % ****************************************************************************** function R = Version_L() % The output differs between versions of this function. So give the user a % chance to recognize the version: % 1: 01-May-2011, Initial version % 2: 15-Feb-2015, The number of dimensions is considered in addition. % In version 1 these variables had the same hash: % zeros(1,1) and zeros(1,1,0), complex(0) and zeros(1,1,0,0) % 3: 29-Jun-2015, Struct arrays are processed field by field and not element % by element, because this is much faster. In consequence the hash value % differs, if the input contains a struct. % 4: 28-Feb-2016 15:20, same output as GetMD5 for MD5 sums. Therefore the % dimensions are casted to UINT64 at first. % 19-May-2018 01:13, STRING type considered. R.HashVersion = 4; R.Date = [2018, 5, 19]; R.HashMethod = {}; try Provider = java.security.Security.getProviders; for iProvider = 1:numel(Provider) S = char(Provider(iProvider).getServices); Index = strfind(S, 'MessageDigest.'); for iDigest = 1:length(Index) Digest = strtok(S(Index(iDigest):end)); Digest = strrep(Digest, 'MessageDigest.', ''); R.HashMethod = cat(2, R.HashMethod, {Digest}); end end catch ME fprintf(2, '%s\n', ME.message); R.HashMethod = 'error'; end end % ****************************************************************************** function Error_L(ID, varargin) error(['JSimon:', mfilename, ':', ID], ['*** %s: ', varargin{1}], ... mfilename, varargin{2:nargin - 1}); end
github
ojwoodford/ojwul-master
bitcount.m
.m
ojwul-master/bitwise/bitcount.m
1,281
utf_8
08975f47b04e6ab70dc6894320d1e49d
%BITCOUNT Count the number of set bits in each column of the input % % B = bitcount(A) % % Count the number of set bits in each column of the input array, % typecast as a bit vector. % %IN: % A - MxNx... input array. % %OUT: % B - 1xNx... output array of bit counts. function A = bitcount(A) persistent lufun lutable if isempty(lutable) % Generate the lookup table lutable = uint8(sum(dec2bin(0:255) - '0', 2)); % Use intlut function if possible lufun = which('intlut'); if isempty(lufun) lufun = @intlutsub; else cwd = cd(); try cd([fileparts(lufun) '/private']); intlutmex(uint8(0), uint8(0)); lufun = str2func('intlutmex'); catch lufun = @intlut; end cd(cwd); end end % Convert to an index into the lookup table sz = size(A); sz(1) = 1; [n, n] = size(A); A = reshape(typecast(A(:), 'uint8'), [], n); % Look up the number of set bits for each byte A = lufun(A, lutable); % Sum the number of set bits per column if size(A, 1) < 32 A = sum(A, 1, 'native'); else A = sum(A, 1); end A = reshape(A, sz); end function A = intlutsub(A, lutable) A = lutable(uint16(A) + uint16(1)); end
github
ojwoodford/ojwul-master
fit_gaussian.m
.m
ojwul-master/stats/fit_gaussian.m
647
utf_8
e4bfa184e5ae30b876c1a3415e6ddfbd
%FIT_GAUSSIAN Fit a multi-variate gaussian to data. % % [mu, whiten] = fit_gaussian(X) % % Fit a multi-variate gaussian to data. This function can handle % under-constrained data. % % IN: % X - MxN matrix of N vectors of dimension M. % % OUT: % mu - Mx1 distribution mean. % whiten - Mx(min(M,N)) whitening matrix. function [mu, whiten] = fit_gaussian(X) % Compute the mean and subtract mu = mean(X, 2); X = bsxfun(@minus, X, mu); % Do the economy svd, to avoid memory issues [whiten, V] = svd(X, 'econ'); % Compute the whitening matrix whiten = diag(sqrt(size(X, 2) - 1) ./ (diag(V) + 1e-300)) * whiten'; end
github
ojwoodford/ojwul-master
qpbo.m
.m
ojwul-master/optimize/qpbo.m
4,377
utf_8
5a8872c3010e87e8bc72194a2040c0d7
%QPBO Binary MRF energy minimization on non-submodular graphs % % [L stats] = qpbo(UE, PI, PE, [TI, TE], [options]) % % Uses the Quadratic Pseudo-Boolean Optimization (QPBO - an extension of % graph cuts that solves the "roof duality" problem, allowing graphs with % submodular edges to be solved) to solve binary, pairwise and triple % clique MRF energy minimization problems. % % The algorithm can be viewed as fusing two labellings in such a way as to % minimize output labellings energy: % L = FUSE(L0, L1) % In particular the solution has these properties: % P1: Not all nodes are labelled. Nodes which are labelled form part of % an optimal labelling. % P2: If all unlabelled nodes in L are fixed to L0, then E(L) <= E(L0). % % This function also implements QPBO-P and QPBO-I. See "Optimizing binary % MRFs via extended roof duality", Rother et al., CVPR 2007, for more % details. % % This function uses mexified C++ code downloaded from www page of Vladimir % Kolmogorov. To acknowledge him/reference the correct papers, see his web % page for details. % % IN: % UE - 2xM matrix of unary terms for M nodes, or M = UE(1) if numel(UE) % == 1 (assumes all unary terms are zero). UE can be any type, but % PE and TE must be of the same type; also, optimality is not % guaranteed for non-integer types. % PI - {2,3}xN uint32 matrix, each column containing the following % information on an edge: [start_node end_node % [pairwise_energy_table_index]]. If there are only 2 rows then % pairwise_energy_table_index is assumed to be the column number, % therefore you must have N == P. % PE - 4xP pairwise energy table, each column containing the energies % [E00 E01 E10 E11] for a given edge. % TI - {3,4}xQ uint32 matrix, each column containing the following % information on a triple clique: [node1 node2 node3 % [triple_clique_energy_table_index]]. If there are only 3 rows then % triple_clique_energy_table_index is assumed to be the column % number, therefore you must have Q == R. % TE - 8xR triple clique energy table, each column containing the % energies [E000 E001 E010 E011 E100 E101 E110 E111] for a given % triple clique. % options - 2x1 cell array. options{1} is a 1x4 uint32 vector of optional % parameters: % FirstNNodes - Only labels of nodes 1:FirstNNodes will be output. % Also limits nodes considered in QPBO-P and QPBO-I. % Default: M. % ImproveMethod - 0: Unlabelled nodes not improved; 1: QPBO-I % employed, assuming preferred label is L0. 2: QPBO-I % employed, using user-defined labelling returned by % callback_func. % ContractIters - Number of iterations of QPBO-P to do. Default: 0. % LargerInternal - 0: input type also used internally; 1: code uses a % larger representation (i.e. more bits) for energies % than that provided, reducing the possibility of % edges becoming saturated. Default: 0. % options{2} - callback_func, a function name or handle which, % given the labelling L (the first output of this % function), returns a logical array of the same % size defining a labelling to be transfromed by % QPBO-I. % % OUT: % L - 1xFirstNNodes int32 matrix of the energy minimizing state of each % node. Labels {0,1} are the optimal label (in a weak sense), while % labels < 0 indicate unlabelled nodes. For unlabelled nodes, if L(x) % == L(y) then x and y are in the same "strongly connected region". % stats - 3x1 int32 vector of stats: % stats(1) - number of unlabelled pixels % stats(2) - number of strongly connected regions of unlabelled pixels % stats(3) - number of unlabelled pixels after running QPBO-P % $Id: qpbo.m,v 1.1 2007/12/07 11:27:56 ojw Exp $ function varargout = qpbo(varargin) sd = 'private/qpbo/'; sourceList = {['-I' sd], 'qpbo.cpp', [sd 'QPBO_.cpp'],... [sd 'QPBO_maxflow.cpp'], [sd 'QPBO_extra.cpp'],... [sd 'QPBO_postprocessing.cpp']}; [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
cd_learn_normal.m
.m
ojwul-master/optimize/cd_learn_normal.m
6,890
utf_8
938e9df7096531476e5785896d25e2be
function estim = cd_learn_normal(varargin) %CD_LEARN_NORMAL Demos contrastive divergence learning % % params = cd_learn_normal(options) % % Uses contrastive divergence to learn the parameters of a normal % distribution that training data is generated from, and displays the % results on completion. Assumes we don't know the normalization factor of % the model we're learning. % % IN: % options - Pairs of arguments, the first being a string containing the % name of the option, the second being the value of the option. % Possible options are: % 'data' - The number of training data values to use (Default: 1000), % or a vector of training data. % 'niter' - The number of parameter updates to carry out (Default: % 3000). % 'mcmc' - The number of MCMC sampling cycles to use (Default: 1). % 'step' - The step size factor (Default: 0.01). % 'perturb' - The perturbation distribution from which to draw % updates to the data points in each MCMC cycle (Default: % @(n,sigma) randn(n,1)*sigma). % 'start' - The parameters to initialize our proposal distribution to, % (Default: [0 1]). % 'finish' - The parameters of the distribution we are aiming for % (Default: [2*rand(1) 0.5+rand(1)]). Ignored if training % data is given. % 'show_results' - Results graphically displayed if non-zero (Default: % true). % % OUT: % params - (niter+1)x2 matrix of model parameters at each iteration. % Load options opts.data = 1000; opts.niter = 3000; opts.mcmc = 1; opts.step = 0.01; opts.start = [0 1]; opts.finish = [2*rand(1) 0.5+rand(1)]; opts.perturb = @(n,sigma) randn(n, 1) * sigma; opts.show_output = true; opts = argparse(opts, varargin{:}); % Generate the data and our initial state if numel(opts.data) == 1 X = randn(opts.data, 1); X = (X * opts.finish(2)) + opts.finish(1); else X = opts.data(:); opts.data = numel(opts.data); end params = opts.start(:); % Buffers for recording display data estim = zeros(2, opts.niter+1); estim(:,1) = params; compare = estim; for iter = 1:opts.niter % Create confabulations using MCMC (Metropolis algorithm) x = X; px = calc_unnormalized_probability(x, params); for k = 1:opts.mcmc % Sample from our perturbation distribution y = x + opts.perturb(opts.data, params(2)); % Reject some of the samples py = calc_unnormalized_probability(y, params); L = py > (px .* rand(opts.data, 1)); x(L) = y(L); px(L) = py(L); end % Calculate the gradient of our energy function grad = opts.step * (calc_expectation_logfx(X, params) - calc_expectation_logfx(x, params)); % Update our parameters params = params + grad; if params(2) <= 0 params(2) = 1e-7; % Ensure sd is positive end % Record this for display later estim(:,iter+1) = params; end % Display the results estim = estim(:,1:iter+1)'; if opts.show_output mu = mean(X); sd = sqrt(var(X, 1)); clf subplot(311); plot([0 iter], [mu mu], 'r-'); hold on plot(0:iter, estim(:,1), 'b-'); data.l1 = axis; data.l1 = data.l1(3:4); data.h1 = plot([0 0], data.l1, 'k-'); title(sprintf('Mean - actual: %g, learnt: %g', mu, estim(end,1))); legend('Linear solve', 'Contrastive divergence', 'Location', 'Best'); subplot(312); plot([0 iter], [sd sd], 'r-'); hold on plot(0:iter, estim(:,2), 'b-'); data.l2 = axis; data.l2 = data.l2(3:4); data.h2 = plot([0 0], data.l2, 'k-'); title(sprintf('Standard deviation - actual: %g, learnt: %g', sd, estim(end,2))); legend('Linear solve', 'Contrastive divergence', 'Location', 'Best'); subplot(313); plot(X, abs(randn(size(X)))*0.1+0.01, 'k.'); hold on data.normal{1} = [-3:0.25:-0.75 -0.5:0.1:0.5 0.75:0.25:3]; data.normal{2} = exp(-(data.normal{1} .^ 2)); [X, Y] = calc_normal_dist(mu, sd, data.normal); plot(X, Y, 'r-'); [X, Y] = calc_normal_dist(estim(1,1), estim(1,2), data.normal); data.h3 = plot(X, Y, 'b-'); X = axis; axis([X(1)-1 X(2)+1 X(3) X(4)]); title('Estimated distributions - use mouse or arrow keys to select a column above'); legend('Data points', 'Linear solve', 'Contrastive divergence', 'Location', 'Best'); % Initialize the callbacks data.col = 0; data.niter = iter; data.step = round(iter/300); data.estim = estim; data.compare = compare; set(gcf, 'WindowButtonDownFcn', @mousedown_callback, ... 'KeyPressFcn', @keypress_callback, ... 'UserData', data); end if nargout == 0 clear estim end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Helper functions %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function grad = calc_expectation_logfx(X, params) A = X - params(1); B = (A .^ 2) / (params(2) ^ 3); A = A / (params(2) ^ 2); grad = [mean(A); mean(B)]; end function px = calc_unnormalized_probability(X, params) px = exp(-((X - params(1)) .^ 2) / (2 * (params(2) ^ 2))); end % The functions below are only used for displaying results function [X, Y] = calc_normal_dist(mu, sd, range) X = range{1} * sd + mu; Y = range{2} / (sd * sqrt(2 * pi)); end function data = plot_data(data) data.col = mod(data.col, data.niter); % Plot the new lines set(data.h1, 'XData', data.col([1 1]), 'YData', data.l1); set(data.h2, 'XData', data.col([1 1]), 'YData', data.l2); [X, Y] = calc_normal_dist(data.estim(data.col+1,1), data.estim(data.col+1,2), data.normal); set(data.h3, 'XData', X, 'YData', Y); drawnow(); end function keypress_callback(fig, event_data) data = get(fig, 'UserData'); key = lower(event_data.Character); % Which keys do what switch key case 28 % Left data.col = data.col - data.step; case 29 % Right data.col = data.col + data.step; case 31 % Down data.col = data.col - 10 * data.step; case 30 % Up data.col = data.col + 10 * data.step; end data = plot_data(data); set(fig, 'UserData', data); end function mousedown_callback(fig, event_data) % Detect which function is required button = get(fig, 'SelectionType'); data = get(fig, 'UserData'); switch button case 'extend' case 'alt' otherwise % Button 1: data.col = get(gca, 'CurrentPoint'); data.col = round(data.col(1)); data = plot_data(data); set(fig, 'UserData', data); end end function opts = argparse(opts, varargin) if isempty(varargin) inopts = struct([]); else inopts = struct(varargin{:}); end fn = fieldnames(inopts); for i = 1:length(fn) if isfield(opts, fn{i}) opts.(fn{i}) = inopts.(fn{i}); else error('Bad argument: ''%s''', fn{i}); end end end
github
ojwoodford/ojwul-master
dp_pair_chain.m
.m
ojwul-master/optimize/dp_pair_chain.m
708
utf_8
cfd16b503833f9e7ed38686b86431031
%DP_PAIR_CHAIN Dynamic programming on a chain of pairwise links % % Examples: % L = dp_pair_chain(U, E) % [L en] = dp_pair_chain(U, E) % % Minimize the cost of a set of pairwise chains. % %IN: % U - PxQxR array of unary costs (double, single or uint32) % E - PxP or PxPx(Q-1)xR array of pairwise costs (same type as U). % %OUT: % L - QxR int32 array of optimal labels (numbered between 1 and P). % en - 1xR vector of minimum costs per chain. % $Id: dp_pair_chain.m,v 1.1 2007/12/07 11:27:55 ojw Exp $ function varargout = dp_pair_chain(varargin) sourceList = {'dp_pair_chain.cpp', '-Xopenmp'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
simulated_annealing.m
.m
ojwul-master/optimize/simulated_annealing.m
4,238
utf_8
f7934e45f1d5640779962e7f527c9e5f
%SIMULATED_ANNEALING Perform simulated annealing on conditional energies % % [X en] = simulated_annealing(X0, energy, T, varargin) % % Simulated annealing for discrete energy minimization labelling problems % for which conditional energy distributions can be computed. Given an % initial labelling, a normalized cooling schedule, and a function which % returns conditional energy distributions, perform simulated annealing, % cycling over all variables in a fixed, random order, once for each input % temperature. % % The cooling schedule is normalized so that 100 means random (uniform) % sampling, while 0 (freezing) means deterministic selection of the energy % minimizing label (i.e. ICM). % %IN: % X0 - Initial labelling array, containing for each variable in the state % space a label index from 1 to n, where n is the number of possible % labels for that variable (a value which can vary from variable to % variable). % energy - A handle to a function to compute the current total or % conditional energy, with the following arguments: % E = energy(X, j, varargin{:}); % X is given labelling, j is the index of the variable in X for % which the conditional energy distribution, E, is to be % computed (E has length n, where n is the number of possible % labels for variable j). If j = 0 then the function returns the % energy of the state X (so E is scalar). varargin are the % trailing input variables passed into the function % simulated_annealing. % T - Nx1 normalized temperature cooling schedule, with a temperature % value for each cycle through all of the input variables (i.e. N % cycles total). % varargin - All trailing input variables are passed to the function % energy. Anonymous functions can be used instead, but this % method can be faster. % %OUT: % X - Lowest energy labelling found. % en - Energy of X. % $Id: simulated_annealing.m,v 1.9 2008/10/03 15:59:04 ojw Exp $ function [X, en] = simulated_annealing(X0, energy, T, varargin) % Calculate initial energy en = zeros(numel(T)+1, 1); en(1) = energy(X0, 0, varargin{:}); enMin = en(1); X = X0; % Cache values needed to evaluate start temperature nX = numel(X0); nT = numel(T); if any(T(:)) Tcurr = -1; Tot = 0; sumN = 0; for a = 1:nX % Calculate the conditional energy enCon = energy(X0, a, varargin{:}); Tot = Tot + sum(exp(min(enCon) - enCon)); sumN = sumN + numel(enCon); end % Scale temperatures T = (min(max(T, 0), 100) * (0.01 * (sumN - nX)) + nX) / sumN; T0 = nX / sumN; else % Just doing ICM T0 = 0; end I = randperm(nX); % Use a random order, but the same one every iteration for t = 1:nT % Set the temperature automatically if T(t) == T0 % Freeze Tcurr = -Inf; else %fprintf('Ratio wanted: %g. Ratio got: %g.\n', T(t), Tot/sumN); % Estimate correct temperature for next iteration Tcurr = Tcurr * (log(T(t)) / log(Tot/sumN-eps)); if Tcurr == -Inf % Stuck freezing when we shouldn't be Tcurr = -1; % Arbitrary! elseif Tcurr >= 0 % Stuck trying to overcook Tcurr = -eps; end end en(t+1) = en(t); Tot = 0; for a = I % Calculate the conditional energy enCon = energy(X0, a, varargin{:}); % Sample from the conditional distribution if Tcurr == -Inf % Freeze [s, P] = min(enCon); else % Draw from the distribution, raised by some temperature P = enCon * Tcurr; P = cumsum(exp(P - max(P))); Tot = Tot + P(end); P = 1 + sum(P(1:end-1) < (rand(1) * P(end))); end en(t+1) = en(t+1) + (enCon(P) - enCon(X0(a))); X0(a) = P; end % Keep track of the lowest energy if en(t+1) < enMin X = X0; enMin = en(t+1); end ojw_progressbar('Simulated annealing', t / nT); end return
github
ojwoodford/ojwul-master
trw_bp.m
.m
ojwul-master/optimize/trw_bp.m
2,447
utf_8
57d5a8ab7552ea350909384ce697dec5
%TRW_BP Multi-label MRF energy minimization using TRW-S & LBP % % [L energy lower_bound] = vgg_trw_bp(UE, PI, PE, [options]) % % Uses the message passing algorithms TRW-S or LBP to solve an MRF energy % minimization problem with binary or multiple labels. % % This function uses mexified C++ code written by Vladimir Kolmogorov, and % downloaded from Microsoft Research. See "Convergent Tree-Reweighted % Message Passing for Energy Minimization", Kolmogorov, PAMI 2006 for % details. % % IN: % UE - HxW cell array of unary terms for H*W nodes in the graph. Each % cell contains a KxL double matrix, with the first row being the L % energies for each of the L possible labels for that node. The % number of labels does not need to be constant across nodes. % PI - {2,3}xN uint32 matrix, each column containing the following % information on an edge: [start_node end_node % [pairwise_energy_table_index]]. If there are only 2 rows then % pairwise_energy_table_index is assumed to be the column number, % therefore you must have N == P. % PE - 1xP cell array of pairwise functions. Each cell gives the % a pairwise function of the form defined by options(1). If the form % is general (i.e. lookup table) then the cell conatins a L1xL2 % matrix, where L1 and L2 are the number of labels for the start and % end nodes respectively. % options - 1x3 int32 vector of optional parameters: % UseTRW - 0: use LBP; otherwise: use TRW-S. Default: 1. % Type - Pairwise energy functional type. 0: general. 1: truncated % quadratic - min(a*(l1-l2)^2,b). 2: truncated linear - % min(a*abs(l1-l2),b). Easy to add support for others. Default: % 0. % MaxIters - number of iterations of LBP or TRW to do. Default: 30. % % OUT: % L - HxW uint16 matrix of the energy minimizing state of each % node. % energy - scalar giving E(L). % lower_bound - scalar giving a lower bound on E(L) for any L. Only % calculated by TRW-S (i.e. 0 for LBP). % $Id: trw_bp.m,v 1.2 2008/03/10 18:45:27 ojw Exp $ function varargout = trw_bp(varargin) sd = 'private/trw-s/'; sourceList = {['-I' sd], 'trw_bp.cxx', [sd 'MRFEnergy.cpp'],... [sd 'minimize.cpp'], [sd 'ordering.cpp'],... [sd 'treeProbabilities.cpp']}; [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
global_basin.m
.m
ojwul-master/optimize/global_basin.m
718
utf_8
4ed7d9117482aaf974cadcde31d9c101
%GLOBAL_BASIN Output binary mask of watershed for the global min of array % % B = global_basin(A) % % This function computes the binary mask of all those points in an array % from which local minimization (e.g. gradient descent with small steps) % would lead to the global minimum of the array. This is the watershed of % the global minimum. This assumes that the input array is a regular % sampling of a Euclidean cost space. % %IN: % A - N-dim array of scalar values % %OUT: % B - size(A) logical array, with true indicating this point would lead % to the global minimum. function B = global_basin(A) B = watershed(A, conndef(ndims(A), 'maximal')); [b, b] = min(A(:)); B = B == B(b);
github
ojwoodford/ojwul-master
load_field.m
.m
ojwul-master/io/load_field.m
317
utf_8
0c31b7afe4727eefccf1f04a9c95a46f
%LOAD_FIELD Load only one field from a file % % x = load_field(name, field) % %IN: % name - Filename string of the file containing the field. % field - Name string of the field to be loaded. %OUT: % x - Loaded field. function x = load_field(name, field) x = load(name, field); x = x.(field); end
github
ojwoodford/ojwul-master
read_wobj.m
.m
ojwul-master/io/read_wobj.m
15,880
utf_8
6ae16c6146e94ba4869abdc7d72d8084
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) % Copyright (c) 2010, Dirk-Jan Kroon % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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. 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=struct(); 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=struct(); 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=struct(); 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=struct(); end objects(no).type=type; objects(no).data=data; end end % Initialize new object list, which will contain the "collapsed" objects objects2(no).data=struct(); 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'); if fid == -1 file_words = ''; return; end 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); if isempty(file_words) objects = struct(); if(verbose),disp('Material file not found'); end return; end % 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=struct(); end objects(no).type=type; objects(no).data=data; end end objects=objects(1:no); if(verbose),disp('Finished Reading Material file'); end
github
ojwoodford/ojwul-master
read_float32.m
.m
ojwul-master/io/read_float32.m
306
utf_8
ca7c4beb289a078ff916ee21d5220d62
%READ_FLOAT32 Read an entire file in as an array of 32-bit floats % % A = read_float32(fname) % %IN: % fname - string containing the filename of the file to be read. % %OUT: % A - Nx1 single array of the values in the file. function A = read_float32(fname) A = read_bin(fname, 'float32');
github
ojwoodford/ojwul-master
write_text.m
.m
ojwul-master/io/write_text.m
1,376
utf_8
220bb0478703b9cb82ce59c35f18ab32
%WRITE_TEXT Write out an array to a text file % % write_text(A, fname, append) % % Writes out an array to a text file using the minimum number of % significant figures required to reconstruct the exact binary number when % read in. % % The array is written out row by row, with dimensions 3 and higher % concatenated. I.e. if the input array is 20x10x3 then the text file will % have 20x3=60 rows, each containing 10 numbers. % %IN: % A - array to be saved. % fname - string containing the name of the output file. % append - boolean indicating whether the file is to be appended to or % overwritten (default). function write_text(A, fname, append) if ischar(A) || isstring(A) fmt = '%s'; else assert(isnumeric(A), 'Exporting non-numeric variables not supported'); assert(isreal(A), 'Exporting complex numbers not tested'); A = permute(A, [2 1 3]); A = A(:,:); switch class(A) case 'double' fmt = '%.16g '; case 'single' fmt = '%.8g '; otherwise fmt = '%d '; end fmt = [repmat(fmt, [1 size(A, 1)]) '\n']; end permission = 'wt'; if nargin > 2 && append(1) permission = 'at'; end fh = fopens(fname, permission); if fh == -1 error('Could not open file %s for writing.', fname); end fprintf(fh, fmt, A); fclose(fh);
github
ojwoodford/ojwul-master
read_ply.m
.m
ojwul-master/io/read_ply.m
5,687
utf_8
b34b22a96aec386a8a7c5cbf579eb898
%% read ply % Read mesh data from ply format mesh file % %% Syntax % [face,vertex]= read_ply(filename) % [face,vertex,color] = read_ply(filename) % %% Description % filename: string, file to read. % % face : double array, nf x 3 array specifying the connectivity of the mesh. % vertex: double array, nv x 3 array specifying the position of the vertices. % color : double array, nv x 3 or nf x 3 array specifying the color of the vertices or faces. % %% Example % [face,vertex] = read_ply('cube.ply'); % [face,vertex,color] = read_ply('cube.ply'); % %% Contribution % Author : Meng Bin % Created: 2014/03/05 % Revised: 2014/03/07 by Meng Bin, Block read to enhance reading speed % Revised: 2014/03/17 by Meng Bin, modify doc format % % Copyright 2014 Computational Geometry Group % Department of Mathematics, CUHK % http://www.math.cuhk.edu.hk/~lmlui % Geometry Processing Package is available under the MIT license % % Copyright (c) 2014 The Chinese University of Hong Kong % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER % LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, % OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE % SOFTWARE. function [face,vertex,color] = read_ply(filename) fid = fopen(filename,'r'); if( fid==-1 ) error('Can''t open the file.'); end % read header str = ''; while (~feof(fid) && isempty(str)) str = strtrim(fgets(fid)); end if ~strcmpi(str(1:3), 'ply') error('The file is not a valid ply one.'); end file_format = ''; nvert = 0; nface = 0; stage = ''; while (~feof(fid)) str = strtrim(fgets(fid)); if strcmpi(str, 'end_header') break; end tokens = regexp(str,'\s+','split'); if (size(tokens,2) <= 2) continue; end if strcmpi(tokens(1), 'comment') elseif strcmpi(tokens(1), 'format') file_format = lower(tokens(2)); elseif strcmpi(tokens(1), 'element') if strcmpi(tokens(2),'vertex') nvert = str2double(tokens{3}); stage = 'vertex'; elseif strcmpi(tokens(2),'face') nface = str2double(tokens{3}); stage = 'face'; end elseif strcmpi(tokens(1), 'property') end end if strcmpi(file_format, 'ascii') [face,vertex,color] = read_ascii(fid, nvert, nface); %elseif strcmp(lower(file_format), 'binary_little_endian') %elseif strcmp(lower(file_format), 'binary_big_endian') else error('The file is not a valid ply one. We only support ascii now.'); end fclose(fid); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function [face,vertex,color] = read_ascii(fid, nvert, nface) % read ASCII format ply file color = []; %read vertex info tot_cnt = 0; cols = 0; A = []; tline = ''; while (~feof(fid) && (isempty(tline) || tline(1) == '#')) pos = ftell(fid); tline = strtrim(fgets(fid)); end C = regexp(tline,'\s+','split'); % read columns of vertex line cols = size(C,2); %rewind to starting of the line fseek(fid, pos,-1); %vertex and color line format string format = strcat(repmat('%f ', [1, cols]), '\n'); %start reading while (~feof(fid) && tot_cnt < cols*nvert) [A_,cnt] = fscanf(fid,format, cols*nvert-tot_cnt); tot_cnt = tot_cnt + cnt; A = [A;A_]; skip_comment_blank_line(fid,1); end if tot_cnt~=cols*nvert warning('Problem in reading vertices. number of vertices doesnt match header.'); end A = reshape(A, cols, tot_cnt/cols); vertex = A(1:3,:)'; % extract vertex color if cols == 6 color = A(4:6,:)'; elseif cols > 6 color = A(4:7,:)'; end %read face info tot_cnt = 0; A = []; tline = ''; while (~feof(fid) && (isempty(tline) || tline(1) == '#')) pos = ftell(fid); tline = strtrim(fgets(fid)); end C = regexp(tline,'\s+','split'); % read columns of face line nvert_f = str2num(C{1}); cols = nvert_f+1; if isempty(color) cols = size(C,2); end %rewind to starting of the line fseek(fid, pos,-1); %face and color line format string format = strcat(repmat('%d ', [1, nvert_f+1]), repmat('%f ', [1, cols-nvert_f-1])); format = strcat(format, '\n'); while (~feof(fid) && tot_cnt < cols*nface) [A_,cnt] = fscanf(fid,format, cols*nface-tot_cnt); tot_cnt = tot_cnt + cnt; A = [A;A_]; skip_comment_blank_line(fid,1); end if tot_cnt~=cols*nface warning('Problem in reading faces. Number of faces doesnt match header.'); end A = reshape(A, cols, tot_cnt/cols); face = A(2:nvert_f+1,:)'+1; % extract face color if cols > nvert_f+1 color = A(nvert_f+2:cols,:)'; end color = color*1.0/255; function [tline] = skip_comment_blank_line(fid,rewind) % skip empty and comment lines % get next content line % if rewind==1, then rewind to the starting of the content line tline = ''; if rewind==1 pos = ftell(fid); end while (~feof(fid) && (isempty(tline))) if rewind==1 pos = ftell(fid); end tline = strtrim(fgets(fid)); end if rewind==1 fseek(fid, pos,-1); end
github
ojwoodford/ojwul-master
get_user_path.m
.m
ojwul-master/io/get_user_path.m
1,844
utf_8
be1d8bac23899f0064233e1635f9aee4
%GET_USER_PATH Get a user/computer-specific directory or file path % % path_str = get_user_path(name, check_path, type [append]) % % Ask a user to select a specific directory or file, and store its path. % If a valid path already exists, use this. % %IN: % name - Name of the directory to be found. % check_path - Handle to function which takes path_str as input and % returns a boolean indicating whether the path is valid. % type - Scalar. 1 for directory, 2 for file, 3 for application folder. % append - String to append to path_str before checking and storing. % Default: ''. % %OUT: % path_str - Path to user specific directory. function path_str = get_user_path(name, check_path, type, append) if nargin < 4 append = ''; end % Check if we already have a valid path tag = [strrep(lower(name), ' ', '_') '_path']; path_str = user_string(tag); if check_path(path_str) return; end % Ask the user to enter the path type_name = {'directory', 'file', 'application folder'}; help = sprintf('Please select your %s %s.', name, type_name{type}); while 1 if ismac() % Is a Mac % Give separate warning as the uigetdir dialogue box doesn't have a % title uiwait(warndlg(help)) type = min(type, 2); end if type == 2 [file, path_str] = uigetfile('*', help); if file == 0 path_str = 0; else path_str = [path_str file]; end else path_str = uigetdir('/', help); end if isequal(path_str, 0) % User hit cancel or closed window error('%s not found.', name); end path_str = [path_str filesep append]; % Check the path if ~check_path(path_str) continue; end % Store the valid path user_string(tag, path_str); return; end end
github
ojwoodford/ojwul-master
json_write.m
.m
ojwul-master/io/json_write.m
794
utf_8
88d106691d8319da9c329c12fcc0a16d
%JSON_WRITE Write a MATLAB variable to a JSON file % % json_write(var, fname) % % This function wraps the JSON for Modern C++ class in a mex wrapper, for % fast writing of MATLAB variables into JSON files. % %IN: % var - MATLAB variable to be written to a JSON file. % filename - String of filename (if in current directory) or full or % relative path to the JSON file to be written to. % Many thanks to Niels Lohmann for his JSON for Modern C++ class: % https://nlohmann.github.io/json/ % Thanks also to Sam Hare for pointing me to said class. function varargout = json_write(varargin) sourceList = {'json_write.cpp', '-largeArrayDims'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
stlwrite.m
.m
ojwul-master/io/stlwrite.m
10,820
utf_8
c0d2afd34d9e64039055c0120d2a0800
function stlwrite(filename, varargin) %STLWRITE Write STL file from patch or surface data. % % STLWRITE(FILE, FV) writes a stereolithography (STL) file to FILE for a % triangulated patch defined by FV (a structure with fields 'vertices' % and 'faces'). % % STLWRITE(FILE, FACES, VERTICES) takes faces and vertices separately, % rather than in an FV struct % % STLWRITE(FILE, X, Y, Z) creates an STL file from surface data in X, Y, % and Z. STLWRITE triangulates this gridded data into a triangulated % surface using triangulation options specified below. X, Y and Z can be % two-dimensional arrays with the same size. If X and Y are vectors with % length equal to SIZE(Z,2) and SIZE(Z,1), respectively, they are passed % through MESHGRID to create gridded data. If X or Y are scalar values, % they are used to specify the X and Y spacing between grid points. % % STLWRITE(...,'PropertyName',VALUE,'PropertyName',VALUE,...) writes an % STL file using the following property values: % % MODE - File is written using 'binary' (default) or 'ascii'. % % TITLE - Header text (max 80 chars) written to the STL file. % % TRIANGULATION - When used with gridded data, TRIANGULATION is either: % 'delaunay' - (default) Delaunay triangulation of X, Y % 'f' - Forward slash division of grid quads % 'b' - Back slash division of quadrilaterals % 'x' - Cross division of quadrilaterals % Note that 'f', 'b', or 't' triangulations now use an % inbuilt version of FEX entry 28327, "mesh2tri". % % FACECOLOR - Single colour (1-by-3) or one-colour-per-face (N-by-3) % vector of RGB colours, for face/vertex input. RGB range % is 5 bits (0:31), stored in VisCAM/SolidView format % (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL) % % Example 1: % % Write binary STL from face/vertex data % tmpvol = false(20,20,20); % Empty voxel volume % tmpvol(8:12,8:12,5:15) = 1; % Turn some voxels on % fv = isosurface(~tmpvol, 0.5); % Make patch w. faces "out" % stlwrite('test.stl',fv) % Save to binary .stl % % Example 2: % % Write ascii STL from gridded data % [X,Y] = deal(1:40); % Create grid reference % Z = peaks(40); % Create grid height % stlwrite('test.stl',X,Y,Z,'mode','ascii') % % Example 3: % % Write binary STL with coloured faces % cVals = fv.vertices(fv.faces(:,1),3); % Colour by Z height. % cLims = [min(cVals) max(cVals)]; % Transform height values % nCols = 255; cMap = jet(nCols); % onto an 8-bit colour map % fColsDbl = interp1(linspace(cLims(1),cLims(2),nCols),cMap,cVals); % fCols8bit = fColsDbl*255; % Pass cols in 8bit (0-255) RGB triplets % stlwrite('testCol.stl',fv,'FaceColor',fCols8bit) % Original idea adapted from surf2stl by Bill McDonald. Huge speed % improvements implemented by Oliver Woodford. Non-Delaunay triangulation % of quadrilateral surface courtesy of Kevin Moerman. FaceColor % implementation by Grant Lohsen. % % Author: Sven Holcombe, 11-24-11 % Check valid filename path path = fileparts(filename); if ~isempty(path) && ~exist(path,'dir') error('Directory "%s" does not exist.',path); end % Get faces, vertices, and user-defined options for writing [faces, vertices, options] = parseInputs(varargin{:}); asciiMode = strcmp( options.mode ,'ascii'); % Create the facets facets = single(vertices'); facets = reshape(facets(:,faces'), 3, 3, []); % Compute their normals V1 = squeeze(facets(:,2,:) - facets(:,1,:)); V2 = squeeze(facets(:,3,:) - facets(:,1,:)); normals = V1([2 3 1],:) .* V2([3 1 2],:) - V2([2 3 1],:) .* V1([3 1 2],:); clear V1 V2 normals = bsxfun(@times, normals, 1 ./ sqrt(sum(normals .* normals, 1))); facets = cat(2, reshape(normals, 3, 1, []), facets); clear normals % Open the file for writing permissions = {'w','wb+'}; fid = fopen(filename, permissions{asciiMode+1}); if (fid == -1) error('stlwrite:cannotWriteFile', 'Unable to write to %s', filename); end % Write the file contents if asciiMode % Write HEADER fprintf(fid,'solid %s\r\n',options.title); % Write DATA fprintf(fid,[... 'facet normal %.7E %.7E %.7E\r\n' ... 'outer loop\r\n' ... 'vertex %.7E %.7E %.7E\r\n' ... 'vertex %.7E %.7E %.7E\r\n' ... 'vertex %.7E %.7E %.7E\r\n' ... 'endloop\r\n' ... 'endfacet\r\n'], facets); % Write FOOTER fprintf(fid,'endsolid %s\r\n',options.title); else % BINARY % Write HEADER fprintf(fid, '%-80s', options.title); % Title fwrite(fid, size(facets, 3), 'uint32'); % Number of facets % Write DATA % Add one uint16(0) to the end of each facet using a typecasting trick facets = reshape(typecast(facets(:), 'uint16'), 12*2, []); % Set the last bit to 0 (default) or supplied RGB facets(end+1,:) = options.facecolor; fwrite(fid, facets, 'uint16'); end % Close the file fclose(fid); fprintf('Wrote %d faces\n',size(faces, 2)); %% Input handling subfunctions function [faces, vertices, options] = parseInputs(varargin) % Determine input type if isstruct(varargin{1}) % stlwrite('file', FVstruct, ...) if ~all(isfield(varargin{1},{'vertices','faces'})) error( 'Variable p must be a faces/vertices structure' ); end faces = varargin{1}.faces; vertices = varargin{1}.vertices; options = parseOptions(varargin{2:end}); elseif isnumeric(varargin{1}) firstNumInput = cellfun(@isnumeric,varargin); firstNumInput(find(~firstNumInput,1):end) = 0; % Only consider numerical input PRIOR to the first non-numeric numericInputCnt = nnz(firstNumInput); options = parseOptions(varargin{numericInputCnt+1:end}); switch numericInputCnt case 3 % stlwrite('file', X, Y, Z, ...) % Extract the matrix Z Z = varargin{3}; % Convert scalar XY to vectors ZsizeXY = fliplr(size(Z)); for i = 1:2 if isscalar(varargin{i}) varargin{i} = (0:ZsizeXY(i)-1) * varargin{i}; end end % Extract X and Y if isequal(size(Z), size(varargin{1}), size(varargin{2})) % X,Y,Z were all provided as matrices [X,Y] = varargin{1:2}; elseif numel(varargin{1})==ZsizeXY(1) && numel(varargin{2})==ZsizeXY(2) % Convert vector XY to meshgrid [X,Y] = meshgrid(varargin{1}, varargin{2}); else error('stlwrite:badinput', 'Unable to resolve X and Y variables'); end % Convert to faces/vertices if strcmp(options.triangulation,'delaunay') faces = delaunay(X,Y); vertices = [X(:) Y(:) Z(:)]; else if ~exist('mesh2tri','file') error('stlwrite:missing', '"mesh2tri" is required to convert X,Y,Z matrices to STL. It can be downloaded from:\n%s\n',... 'http://www.mathworks.com/matlabcentral/fileexchange/28327') end [faces, vertices] = mesh2tri(X, Y, Z, options.triangulation); end case 2 % stlwrite('file', FACES, VERTICES, ...) faces = varargin{1}; vertices = varargin{2}; otherwise error('stlwrite:badinput', 'Unable to resolve input types.'); end end if size(faces,2)~=3 errorMsg = { sprintf('The FACES input array should hold triangular faces (N x 3), but was detected as N x %d.',size(faces,2)) 'The STL format is for triangulated surfaces (i.e., surfaces made from 3-sided triangles).' 'The Geom3d package (https://www.mathworks.com/matlabcentral/fileexchange/24484-geom3d) contains' 'a "triangulateFaces" function which can be used convert your faces into triangles.' }; error('stlwrite:nonTriangles', '%s\n',errorMsg{:}) end if ~isempty(options.facecolor) % Handle colour preparation facecolor = uint16(options.facecolor); %Set the Valid Color bit (bit 15) c0 = bitshift(ones(size(faces,1),1,'uint16'),15); %Red color (10:15), Blue color (5:9), Green color (0:4) c0 = bitor(bitshift(bitand(2^6-1, facecolor(:,1)),10),c0); c0 = bitor(bitshift(bitand(2^11-1, facecolor(:,2)),5),c0); c0 = bitor(bitand(2^6-1, facecolor(:,3)),c0); options.facecolor = c0; else options.facecolor = 0; end function options = parseOptions(varargin) IP = inputParser; IP.addParamValue('mode', 'binary', @ischar) IP.addParamValue('title', sprintf('Created by stlwrite.m %s',datestr(now)), @ischar); IP.addParamValue('triangulation', 'delaunay', @ischar); IP.addParamValue('facecolor',[], @isnumeric) IP.addParamValue('facecolour',[], @isnumeric) IP.parse(varargin{:}); options = IP.Results; if ~isempty(options.facecolour) options.facecolor = options.facecolour; end function [F,V]=mesh2tri(X,Y,Z,tri_type) % function [F,V]=mesh2tri(X,Y,Z,tri_type) % % Available from http://www.mathworks.com/matlabcentral/fileexchange/28327 % Included here for convenience. Many thanks to Kevin Mattheus Moerman % [email protected] % 15/07/2010 %------------------------------------------------------------------------ [J,I]=meshgrid(1:1:size(X,2)-1,1:1:size(X,1)-1); switch tri_type case 'f'%Forward slash TRI_I=[I(:),I(:)+1,I(:)+1; I(:),I(:),I(:)+1]; TRI_J=[J(:),J(:)+1,J(:); J(:),J(:)+1,J(:)+1]; F = sub2ind(size(X),TRI_I,TRI_J); case 'b'%Back slash TRI_I=[I(:),I(:)+1,I(:); I(:)+1,I(:)+1,I(:)]; TRI_J=[J(:)+1,J(:),J(:); J(:)+1,J(:),J(:)+1]; F = sub2ind(size(X),TRI_I,TRI_J); case 'x'%Cross TRI_I=[I(:)+1,I(:); I(:)+1,I(:)+1; I(:),I(:)+1; I(:),I(:)]; TRI_J=[J(:),J(:); J(:)+1,J(:); J(:)+1,J(:)+1; J(:),J(:)+1]; IND=((numel(X)+1):numel(X)+prod(size(X)-1))'; F = sub2ind(size(X),TRI_I,TRI_J); F(:,3)=repmat(IND,[4,1]); Fe_I=[I(:),I(:)+1,I(:)+1,I(:)]; Fe_J=[J(:),J(:),J(:)+1,J(:)+1]; Fe = sub2ind(size(X),Fe_I,Fe_J); Xe=mean(X(Fe),2); Ye=mean(Y(Fe),2); Ze=mean(Z(Fe),2); X=[X(:);Xe(:)]; Y=[Y(:);Ye(:)]; Z=[Z(:);Ze(:)]; end V=[X(:),Y(:),Z(:)];
github
ojwoodford/ojwul-master
write_wobj.m
.m
ojwul-master/io/write_wobj.m
9,798
utf_8
3004ab65ebe5ca6b284c74c7b326861d
function write_wobj(OBJ,fullfilename) % Write objects to a Wavefront OBJ file % % write_wobj(OBJ,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 reading/writing, % % OBJ=read_wobj('examples\example10.obj'); % write_wobj(OBJ,'test.obj'); % % example isosurface to obj-file, % % % Load MRI scan % load('mri','D'); D=smooth3(squeeze(D)); % % Make iso-surface (Mesh) of skin % FV=isosurface(D,1); % % Calculate Iso-Normals of the surface % N=isonormals(D,FV.vertices); % L=sqrt(N(:,1).^2+N(:,2).^2+N(:,3).^2)+eps; % N(:,1)=N(:,1)./L; N(:,2)=N(:,2)./L; N(:,3)=N(:,3)./L; % % Display the iso-surface % figure, patch(FV,'facecolor',[1 0 0],'edgecolor','none'); view(3);camlight % % Invert Face rotation % FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)]; % % % Make a material structure % material(1).type='newmtl'; % material(1).data='skin'; % material(2).type='Ka'; % material(2).data=[0.8 0.4 0.4]; % material(3).type='Kd'; % material(3).data=[0.8 0.4 0.4]; % material(4).type='Ks'; % material(4).data=[1 1 1]; % material(5).type='illum'; % material(5).data=2; % material(6).type='Ns'; % material(6).data=27; % % % Make OBJ structure % clear OBJ % OBJ.vertices = FV.vertices; % OBJ.vertices_normal = N; % OBJ.material = material; % OBJ.objects(1).type='g'; % OBJ.objects(1).data='skin'; % OBJ.objects(2).type='usemtl'; % OBJ.objects(2).data='skin'; % OBJ.objects(3).type='f'; % OBJ.objects(3).data.vertices=FV.faces; % OBJ.objects(3).data.normal=FV.faces; % write_wobj(OBJ,'skinMRI.obj'); % % Function is written by D.Kroon University of Twente (June 2010) % Copyright (c) 2010, Dirk-Jan Kroon % All rights reserved. % % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT OWNER OR CONTRIBUTORS 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. if(exist('fullfilename','var')==0) [filename, filefolder] = uiputfile('*.obj', 'Write obj-file'); fullfilename = [filefolder filename]; end [filefolder,filename] = fileparts( fullfilename); if(isfield(OBJ,'faces')&&~isempty(OBJ.faces)) if isfield(OBJ, 'objects') OBJ.objects(end+1).type = 'f'; else OBJ.objects(1).type = 'f'; end OBJ.objects(end).data.vertices = OBJ.faces; end comments=cell(1,4); comments{1}=' Produced by Matlab Write Wobj exporter '; comments{2}=''; fid = fopen(fullfilename,'w'); write_comment(fid,comments); if(isfield(OBJ,'material')&&~isempty(OBJ.material)) filename_mtl=fullfile(filefolder,[filename '.mtl']); fprintf(fid,'mtllib %s\n',filename_mtl); write_MTL_file(filename_mtl,OBJ.material) end if(isfield(OBJ,'vertices')&&~isempty(OBJ.vertices)) write_vertices(fid,OBJ.vertices,'v'); end if(isfield(OBJ,'vertices_point')&&~isempty(OBJ.vertices_point)) write_vertices(fid,OBJ.vertices_point,'vp'); end if(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal)) write_vertices(fid,OBJ.vertices_normal,'vn'); end if(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture)) write_vertices(fid,OBJ.vertices_texture,'vt'); end for i=1:length(OBJ.objects) type=OBJ.objects(i).type; data=OBJ.objects(i).data; switch(type) case 'usemtl' fprintf(fid,'usemtl %s\n',data); case 'f' check1=(isfield(OBJ,'vertices_texture')&&~isempty(OBJ.vertices_texture)); check2=(isfield(OBJ,'vertices_normal')&&~isempty(OBJ.vertices_normal)); if(check1&&check2) for j=1:size(data.vertices,1) fprintf(fid,'f %d/%d/%d',data.vertices(j,1),data.texture(j,1),data.normal(j,1)); fprintf(fid,' %d/%d/%d', data.vertices(j,2),data.texture(j,2),data.normal(j,2)); fprintf(fid,' %d/%d/%d\n', data.vertices(j,3),data.texture(j,3),data.normal(j,3)); end elseif(check1) for j=1:size(data.vertices,1) fprintf(fid,'f %d/%d',data.vertices(j,1),data.texture(j,1)); fprintf(fid,' %d/%d', data.vertices(j,2),data.texture(j,2)); fprintf(fid,' %d/%d\n', data.vertices(j,3),data.texture(j,3)); end elseif(check2) for j=1:size(data.vertices,1) fprintf(fid,'f %d//%d',data.vertices(j,1),data.normal(j,1)); fprintf(fid,' %d//%d', data.vertices(j,2),data.normal(j,2)); fprintf(fid,' %d//%d\n', data.vertices(j,3),data.normal(j,3)); end else for j=1:size(data.vertices,1) fprintf(fid,'f %d %d %d\n',data.vertices(j,1),data.vertices(j,2),data.vertices(j,3)); end end otherwise fprintf(fid,'%s ',type); if(iscell(data)) for j=1:length(data) if(ischar(data{j})) fprintf(fid,'%s ',data{j}); else fprintf(fid,'%0.5g ',data{j}); end end elseif(ischar(data)) fprintf(fid,'%s ',data); else for j=1:length(data) fprintf(fid,'%0.5g ',data(j)); end end fprintf(fid,'\n'); end end fclose(fid); function write_MTL_file(filename,material) fid = fopen(filename,'w'); comments=cell(1,2); comments{1}=' Produced by Matlab Write Wobj exporter '; comments{2}=''; write_comment(fid,comments); for i=1:length(material) type=material(i).type; data=material(i).data; switch(type) case('newmtl') fprintf(fid,'%s ',type); fprintf(fid,'%s\n',data); case{'Ka','Kd','Ks'} fprintf(fid,'%s ',type); fprintf(fid,'%5.5f %5.5f %5.5f\n',data); case('illum') fprintf(fid,'%s ',type); fprintf(fid,'%d\n',data); case {'Ns','Tr','d'} fprintf(fid,'%s ',type); fprintf(fid,'%5.5f\n',data); otherwise fprintf(fid,'%s ',type); if(iscell(data)) for j=1:length(data) if(ischar(data{j})) fprintf(fid,'%s ',data{j}); else fprintf(fid,'%0.5g ',data{j}); end end elseif(ischar(data)) fprintf(fid,'%s ',data); else for j=1:length(data) fprintf(fid,'%0.5g ',data(j)); end end fprintf(fid,'\n'); end end comments=cell(1,2); comments{1}=''; comments{2}=' EOF'; write_comment(fid,comments); fclose(fid); function write_comment(fid,comments) for i=1:length(comments), fprintf(fid,'# %s\n',comments{i}); end function write_vertices(fid,V,type) switch size(V,2) case 1 for i=1:size(V,1) fprintf(fid,'%s %5.5f\n', type, V(i,1)); end case 2 for i=1:size(V,1) fprintf(fid,'%s %5.5f %5.5f\n', type, V(i,1), V(i,2)); end case 3 for i=1:size(V,1) fprintf(fid,'%s %5.5f %5.5f %5.5f\n', type, V(i,1), V(i,2), V(i,3)); end otherwise end switch(type) case 'v' fprintf(fid,'# %d vertices \n', size(V,1)); case 'vt' fprintf(fid,'# %d texture verticies \n', size(V,1)); case 'vn' fprintf(fid,'# %d normals \n', size(V,1)); otherwise fprintf(fid,'# %d\n', size(V,1)); end
github
ojwoodford/ojwul-master
write_bin.m
.m
ojwul-master/io/write_bin.m
715
utf_8
a0c3679b8d3d39851291017cce94c39d
%WRITE_BIN Write out an array to a binary file % % write_bin(A, fname) % % Writes out an array to a binary file in the format of the data in the % array. I.e. if the array is of type uint32 then the values are saved to % file as 32-bit unsigned integers. This function cannot save complex % numbers. % %IN: % A - array to be saved. % fname - string containing the name of the output file. function write_bin(A, fname) assert(isnumeric(A), 'Exporting non-numeric variables not supported'); assert(isreal(A), 'Exporting complex numbers not tested'); fh = fopens(fname, 'w', 'n'); if fh == -1 error('Could not open file %s for writing.', fname); end fwrite(fh, A, class(A)); fclose(fh);
github
ojwoodford/ojwul-master
json_read.m
.m
ojwul-master/io/json_read.m
812
utf_8
bab4c1c2c0d67a3e0d2f0d01b385fa9a
%JSON_READ Mex wrapper to C++ class for fast reading of JSON files % % var = json_read(filename) % % This function wraps the JSON for Modern C++ class in a mex wrapper, for % fast loading of JSON files into MATLAB variables. % %IN: % filename - String of filename (if in current directory) or full or % relative path to the JSON file to be read in. % %OUT: % var - MATLAB interpretation of the JSON data. % Many thanks to Niels Lohmann for his JSON for Modern C++ class: % https://nlohmann.github.io/json/ % Thanks also to Sam Hare for pointing me to said class. function varargout = json_read(varargin) sourceList = {'json_read.cpp', '-largeArrayDims'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
read_bin.m
.m
ojwul-master/io/read_bin.m
498
utf_8
9b2d92e5eda0ed038bf0e108342fbac4
%READ_BIN Read an entire file in as an array of a given type % % A = read_bin(fname, type) % %IN: % fname - string containing the filename of the file to be read. % type - string indicating the datatype of the values in the file. % %OUT: % A - Nx1 array of the values in the file, of datatype type. function A = read_bin(fname, type) fh = fopens(fname, 'r'); if fh == -1 error('Could not open file %s for reading.', fname); end A = fread(fh, ['*' type]); fclose(fh);
github
ojwoodford/ojwul-master
fopens.m
.m
ojwul-master/io/fopens.m
5,918
utf_8
b712bcfc2438ae7217099a12ba390fc6
%FOPENS Open file which is always closed when the function exits. % FID = FOPENS(FILENAME) opens the file FILENAME for read access. % FILENAME is a string containing the name of the file to be opened. % (On PC systems, FOPENS opens files for binary read access.) % % FILENAME can be a MATLABPATH relative partial pathname. If the % file is not found in the current working directory, FOPENS searches for % it on the MATLAB search path. On UNIX systems, FILENAME may also start % with a "~/" or a "~username/", which FOPENS expands to the current % user's home directory or the specified user's home directory, % respectively. % % FID is a scalar MATLAB integer valued double, called a file identifier. % You use FID as the first argument to other file input/output % routines, such as FREAD and FCLOSE. If FOPENS cannot open the file, it % throws an error. % % FID = FOPENS(FILENAME,PERMISSION) opens the file FILENAME in the % mode specified by PERMISSION: % % 'r' open file for reading % 'w' open file for writing; discard existing contents % 'a' open or create file for writing; append data to end of file % 'r+' open (do not create) file for reading and writing % 'w+' open or create file for reading and writing; discard % existing contents % 'a+' open or create file for reading and writing; append data % to end of file % 'W' open file for writing without automatic flushing % 'A' open file for appending without automatic flushing % % FILENAME can be a MATLABPATH relative partial pathname only if the file % is opened for reading. % % You can open files in binary mode (the default) or in text mode. % In binary mode, no characters get singled out for special treatment. % In text mode on the PC, the carriage return character preceding % a newline character is deleted on input and added before the newline % character on output. To open a file in text mode, append 't' to the % permission string, for example 'rt' and 'w+t'. (On Unix, text and % binary mode are the same, so this has no effect. On PC systems % this is critical.) % % If the file is opened in update mode ('+'), you must use an FSEEK or % FREWIND between an input command like FREAD, FSCANF, FGETS, or FGETL % and an output command like FWRITE or FPRINTF. You must also use an % FSEEK or FREWIND between an output command and an input command. % % Two file identifiers are automatically available and need not be % opened. They are FID=1 (standard output) and FID=2 (standard error). % % [FID, MESSAGE] = FOPENS(FILENAME,...) returns a system dependent error % message if the open is not successful. % % [FID, MESSAGE] = FOPENS(FILENAME,PERMISSION,MACHINEFORMAT) opens the % specified file with the specified PERMISSION and treats data read % using FREAD or data written using FWRITE as having a format given % by MACHINEFORMAT. MACHINEFORMAT is one of the following strings: % % 'native' or 'n' - local machine format - the default % 'ieee-le' or 'l' - IEEE floating point with little-endian % byte ordering % 'ieee-be' or 'b' - IEEE floating point with big-endian % byte ordering % 'ieee-le.l64' or 'a' - IEEE floating point with little-endian % byte ordering and 64 bit long data type % 'ieee-be.l64' or 's' - IEEE floating point with big-endian byte % ordering and 64 bit long data type. % % [FID, MESSAGE] = FOPENS(FILENAME,PERMISSION,MACHINEFORMAT,ENCODING) % opens the specified file using the specified PERMISSION and % MACHINEFORMAT. ENCODING is a string that specifies the character % encoding scheme associated with the file. It must be the empty % string ('') or a name or alias for an encoding scheme. Some examples % are 'UTF-8', 'latin1', 'US-ASCII', and 'Shift_JIS'. For common names % and aliases, see the Web site % http://www.iana.org/assignments/character-sets. If ENCODING is % unspecified or is the empty string (''), MATLAB's default encoding % scheme is used. % % [FILENAME,PERMISSION,MACHINEFORMAT,ENCODING] = FOPENS(FID) returns the % filename, permission, machine format, and character encoding values % used by MATLAB when it opened the file associated with identifier FID. % MATLAB does not determine these output values by reading information % from the opened file. For any of these parameters that were not % specified when the file was opened, MATLAB returns its default value. % The ENCODING string is a standard character encoding scheme name that % may not be the same as the ENCODING argument used in the call to FOPEN % that opened the file. An invalid FID returns empty strings for all % output arguments. % % FIDS = FOPENS('all') returns a row vector containing the file % identifiers for all the files currently opened by the user % (but not 1 or 2). % % The 'W' and 'A' permissions do not automatically perform a flush % of the current output buffer after output operations. % % Any file opened with FOPENS will automatically be closed when the % function exits, even through an error, or when the workspace is % cleared. % % See also FOPEN. function varargout = fopens(varargin) % Silly check if nargout == 0 return end % Call fopen [varargout{1:nargout}] = fopen(varargin{:}); % Check if opened if isequal(varargout{1}, -1) % Not opened. Throw an error. error('File %s could not be opened', varargin{1}); else % Set the cleanup function [name, name] = fileparts(tempname); name = ['CloseFileOnExitObj_' name]; assignin('caller', name, onCleanup(@() fclose_quiet(varargout{1}))); end end function fclose_quiet(fid) try fclose(fid); catch end end
github
ojwoodford/ojwul-master
svm_read_sparse.m
.m
ojwul-master/classify/svm_read_sparse.m
254
utf_8
2156b44a43e178996d2b95d5723a22f5
% SVM_READ_SPARSE Mex wrapper interface to the svm library function varargout = svm_read_sparse(varargin) sourceList = {'svm_read_sparse.c'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
roc_curve.m
.m
ojwul-master/classify/roc_curve.m
1,184
utf_8
ee9f65b707b7f495ee759487bafaa1d2
%ROC_CURVE Compute the x and y parameters of an ROC curve % % [X, Y, auc] = roc_curve(scores, ground_truth) % % Compute the parameters of a Receiver Operating Characteristic curve, % which plots true positive rate against false positive rate, over a range % of classification thresholds. % %IN: % scores - Mx1 vector of classification scores for M test variables. % ground_truth - Mx1 logical vector indicating the ground_truth class for % each test variable (true is positive). % %OUT: % X - (M+1)x1 vector of false positive rates with increasing % classification threshold. % Y - (M+1)x1 vector of true positive rates with increasing % classification threshold. % auc - scalar area under the curve. function [X, Y, auc] = roc_curve(scores, ground_truth) % Order the scores [~, order] = sort(scores, 'descend'); ground_truth = ground_truth(order); % Compute the true positive rate Y = [0; cumsum(ground_truth(:))]; Y = Y / Y(end); % Compute the false positive rate X = [0; cumsum(~ground_truth(:))]; X = X / X(end); if nargout < 3 return end % Compute the area under the curve auc = (diff(X)' * (Y(1:end-1) + Y(2:end))) * 0.5; end
github
ojwoodford/ojwul-master
svm_predict.m
.m
ojwul-master/classify/svm_predict.m
1,026
utf_8
688b6ffb6f6bdb0e0f1d9e065a701fd1
% SVM_PREDICT Mex wrapper interface to the svm library % % [predicted_label, accuracy, decision_values/prob_estimates] = svmpredict(testing_label_vector, testing_instance_matrix, model [,'libsvm_options']); % % -testing_label_vector: % An m by 1 vector of prediction labels. If labels of test % data are unknown, simply use any random values. % -testing_instance_matrix: % An m by n matrix of m testing instances with n features. % It can be dense or sparse. % -model: % The output of svmtrain. % -libsvm_options: % A string of testing options in the same format as that of LIBSVM. function varargout = svm_predict(varargin) sourceDir = 'private/libsvm/'; sourceList = {['-I' sourceDir], 'svm_predict.cpp', [sourceDir 'svm.cpp'], ... [sourceDir 'svm_model_matlab.cpp'], '-largeArrayDims'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
fiksvm_predict.m
.m
ojwul-master/classify/fiksvm_predict.m
971
utf_8
619c7d52f9ec6e4903b099fe3295215d
% FIKSVM_PREDICT Mex wrapper interface to the svm library % % Usage: [exact_values, pwconst_values, pwlinear_values,[times]] = ... % fiksvm_predict(testing_label_vector, testing_instance_matrix, model,'libsvm_options') % % Output: % exact_values : predictions using binary search % pwconst_values : approximation using piecewise constant function % pwlinear_values : approximation using piecewise linear function % [times] : running times % % % libsvm_options: % -b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); % -v verbose flag : 0 or 1 (default 0); % -n number of bins : [2,...] (default 100); function varargout = fiksvm_predict(varargin) sourceDir = 'private/libsvm/'; sourceList = {['-I' sourceDir], 'fiksvm_predict.cpp', [sourceDir 'fiksvm.cpp']}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
svm_demo.m
.m
ojwul-master/classify/svm_demo.m
2,009
utf_8
e635ff91ea3db75613b2d90885d71a9e
%SVM_DEMO A simple demo of SVM classification % % svm_demo(N) % % Train different binary SVM classifiers on 2D data, and visualize the % results. % %IN: % N - Integer number of 2D points to train and test on. Default: 500. function svm_demo(N) if nargin < 1 N = 500; end % Create some classification training data train_data = rand(2, N); train_class = gt_class(train_data); % Train 3 types of SVM kernels = {'linear', 'intersection', 'radial'}; for a = numel(kernels):-1:1 % Use the libsvm library obj(a) = libsvm(struct('kernel', kernels{a}, 'probabilistic', 1, 'type', 'epsilon-svr')); tic; % Train the SVM train(obj(a), train_data, train_class); t(1,a) = toc; end % Create some test data test_data = rand(2, N); test_class = gt_class(test_data); % Classify test data using the 3 learned classifiers for a = numel(obj):-1:1 tic; output{a} = test(obj(a), test_data); t(2,a) = toc; end % Render the results % Times & accuracy for a = 1:numel(kernels) fprintf('Kernel: %15s. Training: %8gs. Test: %8gs. Accuracy: %g%%.\n', kernels{a}, t(1,a), t(2,a), 100*mean((test_class' < 0.5) == (output{a} < 0.5))); end % Classifications figure; subplot(221); render(train_data, train_class); title 'Training data' subplot(222); render(test_data, output{1}); title 'Linear classification' subplot(223); render(test_data, output{2}); title 'Intersection classification' subplot(224); render(test_data, output{3}); title 'Radial basis classification' end % Use a cubic class boundary function class = gt_class(data) class = ([1, -1.5, 0.57]/0.07 * [data(1,:).^3; data(1,:).^2; data(1,:)]) < data(2,:); end % Render the points function render(data, prob) hold on patch(data(1,:), data(2,:), double(prob), 'FaceColor', 'none', 'EdgeColor', 'none', 'Marker', '+', 'MarkerEdgeColor', 'flat', 'CDataMapping', 'scaled'); hold off caxis([0 1]); colormap(squeeze(real2rgb(1:256, [1 0 0; 0 0 1]))); end
github
ojwoodford/ojwul-master
linear_predict.m
.m
ojwul-master/classify/linear_predict.m
1,333
utf_8
51ebe96e9f67b299e7822af80f846381
% LINEAR_PREDICT Mex wrapper interface to the linear svm library % % [predicted_label, accuracy, decision_values/prob_estimates] = linear_predict(testing_label_vector, testing_instance_matrix, model [, 'liblinear_options', 'col']); % % -testing_label_vector: % An m by 1 vector of prediction labels. If labels of test % data are unknown, simply use any random values. (type must be double) % -testing_instance_matrix: % An m by n matrix of m testing instances with n features. % It must be a sparse matrix. (type must be double) % -model: % The output of train. % -liblinear_options: % A string of testing options in the same format as that of LIBLINEAR. % -col: % if 'col' is set, each column of testing_instance_matrix is a data instance. Otherwise each row is a data instance. function varargout = linear_predict(varargin) sourceDir = 'private/liblinear/matlab/'; sourceList = {['-I' sourceDir], 'linear_predict.c', [sourceDir 'linear_model_matlab.c'], ... [sourceDir '../linear.cpp'], [sourceDir '../tron.cpp'], [sourceDir '../blas/*.c'], ... '-largeArrayDims'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
linear_train.m
.m
ojwul-master/classify/linear_train.m
1,135
utf_8
9d26e561f17d09f7178f3a3c68b33e85
% LINEAR_TRAIN Mex wrapper interface to the linear svm library % % model = linear_train(training_label_vector, training_instance_matrix [,'liblinear_options', 'col']); % % -training_label_vector: % An m by 1 vector of training labels. (type must be double) % -training_instance_matrix: % An m by n matrix of m training instances with n features. % It must be a sparse matrix. (type must be double) % -liblinear_options: % A string of training options in the same format as that of LIBLINEAR. % -col: % if 'col' is set, each column of training_instance_matrix is a data instance. Otherwise each row is a data instance. function varargout = linear_train(varargin) sourceDir = 'private/liblinear/matlab/'; sourceList = {['-I' sourceDir], 'linear_train.c', [sourceDir 'linear_model_matlab.c'], ... [sourceDir '../linear.cpp'], [sourceDir '../tron.cpp'], [sourceDir '../blas/*.c'], ... '-largeArrayDims'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
svm_precomp_model.m
.m
ojwul-master/classify/svm_precomp_model.m
414
utf_8
93448d99ffc7328ebb914386e77e8eb8
% SVM_PRECOMP_MODEL Mex wrapper interface to the svm library function varargout = svm_precomp_model(varargin) sourceDir = 'private/libsvm/'; sourceList = {['-I' sourceDir], 'svm_precomp_model.cpp', [sourceDir 'svm.cpp'], ... [sourceDir 'svm_model_matlab.cpp'], [sourceDir 'fiksvm.cpp']}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
svm_train.m
.m
ojwul-master/classify/svm_train.m
824
utf_8
6e6b58d056e746c8dd4e981e19013be6
% SVM_TRAIN Mex wrapper interface to the svm library % % model = svm_train(training_label_vector, training_instance_matrix, [,'libsvm_options']); % % -training_label_vector: % An m by 1 vector of training labels. % -training_instance_matrix: % An m by n matrix of m training instances with n features. % It can be dense or sparse. % -libsvm_options: % A string of training options in the same format as that of LIBSVM. function varargout = svm_train(varargin) sourceDir = 'private/libsvm/'; sourceList = {['-I' sourceDir], 'svm_train.cpp', [sourceDir 'svm.cpp'], ... [sourceDir 'svm_model_matlab.cpp'], '-largeArrayDims'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
separable_steerable_filter.m
.m
ojwul-master/filter/separable_steerable_filter.m
3,348
utf_8
e3883fff343cc4c0c1a56aa00bbac3be
%SEPARABLE_STEERABLE_FILTER Compute the basis and weights of separable steerable filters % % [basis, weight_fun] = separable_steerable_filter(r, coeff, X) % % Decompose a steerable filter formed from an odd or even parity polynomial % times a Gaussian window into a separable basis using the equations in % Appendix D of: % "The Design and Use of Steerable Filters", Freeman & Adelson, TPAMI 1991 % %IN: % r - Scalar radius (s.d.) of the Gaussian window. % coeff - 1xN vector of coefficients of the polynomial, highest order first. % X - 1xM vector of x (and y) locations to sample the filter at. % %OUT: % basis - Mx2xN array of N pairs of separable filters (y direction filter first). % weight_fun - handle to a function which takes an angle as input and % returns the N weights for the basis filter responses which % should be summed to give the output of the original filter % at that angle. function [basis, weight_fun] = separable_steerable_filter(r, coeff, X) % Default parameters for visualizing if nargin < 3 if nargin < 2 if nargin < 1 % Radius of the Gaussian mask r = 1; end % Coefficients of the polynomial, highest order first coeff = [4 0 -2]; end % Values of x (and y) to evaluate the filter basis at X = linspace(-r*4, r*4, 400); end X = reshape(X, 1, []); % Check filter is odd or even parity assert(all(coeff(1:2:end) == 0) || all(coeff(2:2:end) == 0), 'Filter not odd or even parity'); % Construct the filter function f = @(theta, x, y) filter_val(r, coeff, theta, x, y); % Compute regularly spaced angles N = find(fliplr(coeff), 1, 'last') - 1; theta = linspace(0, pi, N+2); theta = theta(1:end-1); % Compute the filters at those angles F = f(reshape(theta, 1, 1, 1, []), X, X'); % Compute the weight function of eqn. 42 K = (0:N)'; weight_fun = @(theta) bsxfun(@times, (-1 .^ K) .* (factorial(N) ./ (factorial(K) .* factorial(N - K))), bsxfun(@power, cos(theta), N-K) .* bsxfun(@power, sin(theta), K)); % Compute the K matrix of eqn. 43 K = weight_fun(theta)'; % Compute the basis filters basis = K \ reshape(permute(F, [4 1 2 3]), numel(theta), []); M = numel(X); basis = reshape(basis', M, M, N+1); % Compute the separable x and y directions of each filter [x, x] = max(abs(reshape(basis, M*M, N+1)), [], 1); [y, x] = ind2sub([M M], x); B = basis; basis = zeros(M, 2, N+1); for a = 1:N+1 v = 1 ./ sqrt(abs(B(y(a),x(a),a))); basis(:,1,a) = B(:,x(a),a) * v * sign(B(y(a),x(a),a)); basis(:,2,a) = B(y(a),:,a) * v; end % Display the filters and basis if nargout == 0 figure(1); clf reset; sc(F, 'diff'); figure(2); clf reset; sc(reshape(B, M, M, 1, N+1), 'diff'); clear basis weight_fun end end % Function to construct the Gaussian mask function g = gauss_mask(x, y, r) g = exp(-0.5 * bsxfun(@plus, x .* x, y .* y) / (r * r)) / (r * sqrt(2 * pi)); end % Function to construct the oriented filter function v = filter_val(r, coeff, theta, x, y) % Compute x' of eqn. 38 v = bsxfun(@plus, bsxfun(@times, x, cos(theta)), bsxfun(@times, y, sin(theta))); % Multiply the Gaussian mask by the polynomial (eqn. 37) v = bsxfun(@times, gauss_mask(x, y, r), polyval(coeff, v)); end
github
ojwoodford/ojwul-master
find_first.m
.m
ojwul-master/numeric/find_first.m
1,001
utf_8
f48f512bfb5b53e2022805b0c86b9125
%FIND_FIRST Fast, vectorized version of find(A, 1, 'first') % % B = find_first(A) % B = find_first(A, start) % B = find_first(A, operator, value) % B = find_first(A, operator, value, start) % % Find the first element in each column vector of an array which meets a % particular comparison criterion. % % Example: % find_first(rand(10, 10), '>', 0.8) % %IN: % A - MxN real numeric array. % operator - string of a comparison operator, e.g. '>'. Default: '~='. % value - 1xN or scalar array of values to use in the comparison. % Default: 0. % start - 1xN or scalar uint32 array of offsets from the start of each % vector at which to start searching. % %OUT: % B - 1xN uint32 array of indices of first element in each column vector % meeting the criterion, or 0 if none are found. function varargout = find_first(varargin) sourceList = {'find_first.cpp', '-Xopenmp'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
dimsel.m
.m
ojwul-master/numeric/dimsel.m
1,511
utf_8
21dccb0ea6801c98b303e4707b05f5f8
%DIMSEL Select one indexed element from each vector along a given dimension % % B = dimsel(A, I) % % Given as input a numeric array, A, and an index array, I, which contains % indices along a particular dimension of A, output the indexed elements of % A. % % For example, in the code: % A = rand(3); % [B, I] = max(A, [], 2); % C = dimsel(A, I); % the arrays B and C are identical. % %IN: % A - Multi-dimensional numeric array. % I - Multi-dimensional index array, of the same size as A but for one % dimension, which must be singleton. The array must consist of % positive intergers in the range [1,N], where N is the length of the % dimension of A that is singleton for I. % %OUT: % B - Output array. function A = dimsel(A, I) % Check inputs szA = size(A); szI = size(I); if isequal(szA, szI) || isempty(A) return; end if numel(szI) ~= numel(szA) szI = [szI 1]; end assert(all(szI == szA | szI == 1), 'Dimensions do not match'); dim = find(szI ~= szA); assert(numel(dim) == 1, 'Only one dimension of I should be different from that of A'); % Construct the index array stride = cumprod([1 szA]); if stride(dim+1) == stride(end) I = I(:) * stride(dim) + (1-stride(dim):0)'; elseif stride(dim) == 1 I = I(:) + (0:stride(dim+1):stride(end)-1)'; else I = I(:) * stride(dim) + reshape(bsxfun(@plus, (1-stride(dim):0)', 0:stride(dim+1):stride(end)-1), [], 1); end % Construct the output A = reshape(A(I), szI);
github
ojwoodford/ojwul-master
first.m
.m
ojwul-master/numeric/first.m
819
utf_8
6656ebac8a73f0f3965ebb5eb3161baa
%FIRST Returns indices of the first non-zero elements along the given dimension % % B = first(A, [dim]) % % For each vector along the given dimension, this function returns the % index of the first non-zero element along that vector, or 0 if there is % no non-zero element. % %IN: % A - MxNx... input array % dim - dimension of A along which to find the first non-zero element. % Default: first non-singleton dimension of A. % %OUT % B - 1xNx... output array (size dependent on which dimension specified). function A = first(A, dim) if nargin < 2 dim = find(size(A) ~= 1, 'first', 1); if isempty(dim) dim = 1; end end if ~islogical(A) A = A ~= 0; end n = size(A, dim); A = cumsum(A, dim); A = sum(A > 0, dim); A = (n + 1) - A; A(A==n+1) = 0; end
github
ojwoodford/ojwul-master
gauss_mask.m
.m
ojwul-master/numeric/gauss_mask.m
1,101
utf_8
fb9150428ba19cc33aa5d2f465a0a953
%GAUSS_MASK Compute 1D Nth derivative of a Gaussian % % Examples: % F = gauss_mask(sigma) % F = gauss_mask(sigma, deriv) % F = gauss_mask(sigma, deriv, X) % % This function computes the Nth derivative of a Gaussian, in 1D. % % IN: % sigma - Standard deviation of the Gaussian. % deriv - The derivative to compute. Default: 0. % X - Values of x at which to compute Gaussian. Default: % -floor(4*sigma):floor(4*sigma). % % OUT: % F - The vector of values of Nth derivative of the zero-mean Gaussian % with standard deviation sigma, evaluated at the values in X. function F = gauss_mask(sigma, deriv, X) if nargin < 3 % Determine necessary filter support (for Gaussian). X = max(floor(4 * sigma), 1); X = -X:X; end % Compute standard Gaussian s2 = -1 ./ sigma .^ 2; F = exp((0.5 * s2) * X .* X) ./ (sigma * sqrt(2 * pi)); if nargin > 1 && deriv % Compute 1st derivative F_ = F; F = s2 * X .* F; % Compute nth derivative for a = 2:deriv F__ = F_; F_ = F; F = s2 * ((a - 1) .* F__ + X .* F_); end end return
github
ojwoodford/ojwul-master
zero_mean.m
.m
ojwul-master/numeric/zero_mean.m
523
utf_8
b8edf0ff597b9b20b5cf70e48aeaee55
%ZERO_MEAN Subtract the means from a set of vectors to make them zero mean % % Y = zero_mean(X) % Y = zero_mean(X, dim) % % Subtract the mean along a specified dimension from all vectors in an % array, making them zero mean. % %IN: % X - Array containing vectors to zero mean. % dim - Dimension along which to zero-mean X. Default: first % non-singleton dimension of X. % %OUT: % Y - Zero-meaned X. function X = zero_mean(X, varargin) X = bsxfun(@minus, X, mean(X, varargin{:})); end
github
ojwoodford/ojwul-master
isapprox.m
.m
ojwul-master/numeric/isapprox.m
1,409
utf_8
5ebc8a650be39b533bbbfe311488be94
%ISAPPROX Check if A and B are approximately equal % % [tf, d] = isapprox(A, B, tol) % % Determines whether two input arrays are approximately equal. If a % tolerance is given, and no outputs are requested, the function asserts if % the inputs aren't approximately equal. % %IN: % A - Numeric array. % B - Numeric array to compare against A. % tol - Scalar tolerance (proportion of the magnitude). % %OUT: % tf - Boolean indicating if A and B are approximately equal. % d - Maximum difference between A and B (proportion of the magnitude). % D - Per element different between A and B (proportion of the magnitude). function [tf, d, D] = isapprox(A, B, tol) tf = isequal(size(A), size(B)); if ~tf if nargout == 0 error('Matrices have differing sizes: [ %s] and [ %s].', sprintf('%d ', size(A)), sprintf('%d ', size(B))); else d = -1; end return; end d = abs(A - B); d2 = abs(A + B); if issparse(d2) [i, j, d] = find(d); if isempty(d) d = 0; d2 = 0; else i = i + (j - 1) * size(d2, 1); d2 = full(d2(i)); end end D = d ./ (d2 + 1); d = 2 * max(D(:)); if nargin < 3 if nargout == 0 fprintf('Matrices differ by scale %g.\n', d); return; end tol = eps * 2; end tf = d < tol; if nargout == 0 assert(tf, 'Matrices differ outside tolerance. Largest scale difference: %g.', d); end end
github
ojwoodford/ojwul-master
extremum.m
.m
ojwul-master/numeric/extremum.m
614
utf_8
51a4fafafae5abcb7335319637a6da18
%EXTREMUM Compute the extreme value along a given dimension % % B = extremum(A, [dim]) % % Output the most extreme value (furthest from 0) along a specified % dimension of an input array. % %IN: % A - Numeric input array. % dim - Dimension along which to compute the extremum. Default: first % non-singleton dimension. % %OUT: % B - Output array. function A = extremum(A, dim) if nargin < 2 % Find the first non-singleton dimension dim = find(size(A) > 1, 1, 'first'); if isempty(dim) return; end end [I, I] = max(abs(A), [], dim); A = dimsel(A, I);
github
ojwoodford/ojwul-master
sqdist.m
.m
ojwul-master/numeric/sqdist.m
784
utf_8
56bd1dee4c97472b5aebb3d958a26641
%SQDIST Squared Euclidean distance between sets of vectors % % D = sqdist(A, [B]) % % IN: % A - MxJ matrix of columnwise vectors. % B - MxK matrix of columnwise vectors. Default: B = A. % % OUT: % D - JxK Squared distance between each vector in A and each vector in B. function D = sqdist(A, B) if nargin < 2 B = A; A2 = A .* A; B2 = A2; A = permute(-2 * A, [2 3 1]); A2 = permute(A2, [2 3 1]); else A = permute(A, [2 3 1]); A2 = A .* A; B2 = B .* B; if numel(A) <= numel(B) A = -2 * A; else B = -2 * B; end end A = reshape(cat(2, ones(size(A)), A, A2), size(A, 1), []); B = reshape(cat(1, shiftdim(B2, -1), shiftdim(B, -1), ones([1 size(B)])), [], size(B, 2)); D = A * B; end
github
ojwoodford/ojwul-master
normalize.m
.m
ojwul-master/numeric/normalize.m
582
utf_8
a11f36e044a61612a4bb2b0651a2062b
%NORMALIZE Set vectors in an array to be of unit length % % Y = normalize(X) % Y = normalize(X, dim) % % Set all the non-zero vectors in an array, along a specified dimension, to % be of unit length. % %IN: % X - Array containing vectors to normalize. % dim - Dimension along which to normalize X. Default: first % non-singleton dimension of X. % %OUT: % Y - Normalized X. function X = normalize(X, varargin) normalizer = normd(X, varargin{:}); M = normalizer ~= 0; normalizer(M) = 1 ./ normalizer(M); X = bsxfun(@times, X, normalizer); end
github
ojwoodford/ojwul-master
all_finite.m
.m
ojwul-master/numeric/all_finite.m
291
utf_8
1f4977902fa9382cafc15932c81c65f7
%ALL_FINITE Checks if all the elements in an array are finite % % tf = all_finite(x) % %IN: % x - Numeric array. % %OUT: % tf - Boolean indicating whether all elements of x are finite. function x = all_finite(x) if issparse(x) [~, ~, x] = find(x); end x = all(isfinite(x(:))); end
github
ojwoodford/ojwul-master
array_snake_indices.m
.m
ojwul-master/numeric/array_snake_indices.m
921
utf_8
1036fca344d56d2f1a94ebffb868560d
%ARRAY_SNAKE_INDICES List of indices snaking through an array % % I = array_snake_indices(sz) % % Produces a list of all the indices into an array of size sz, with each % consecutive index referencing a neighbouring element to the previous % index. % %IN: % sz - 1xN vector of the size of array to index. % %OUT: % I - (prod(sz))x1 uint32 vector of array indices. function I = array_snake_indices(sz) % Initialize the indices I = uint32(1):uint32(prod(sz)); if isempty(I) return; end % Re-order the indices so they snake through the array sz = sz(sz>1); for a = 2:numel(sz) I = reshape(I, prod(sz(1:a-1)), sz(a), []); I(:,2:2:end,:) = I(end:-1:1,2:2:end,:); end I = I(:); if nargout > 0 return; end % Test the output X = arrayfun(@(s) {1:s}, sz); [X{:}] = ndgrid(X{:}); X = cellfun(@(s) col(s(I)), X, 'UniformOutput', false); X = cat(2, X{:}); Y = sum(abs(diff(X)), 2); assert(all(Y == 1)); end
github
ojwoodford/ojwul-master
range01.m
.m
ojwul-master/numeric/range01.m
665
utf_8
e05a9fe686b93d39d6355913b9be9179
%RANGE01 Apply gain and bias so range of data is exactly [0, 1] % % Y = range01(X, [dim]) % % Set all vectors in X along the specified dimension to be in the range % [0,1]. % %IN: % X - Array containing vectors to rescale to range [0, 1]. % dim - Dimension along which to zero-mean X. Default: first % non-singleton dimension of X. % %OUT: % Y - Rescaled X. function X = range01(X, dim) if nargin < 2 % Find the first non-singleton dimension dim = find(size(X) > 1, 1, 'first'); if isempty(dim) return; end end X = bsxfun(@minus, X, min(X, [], dim)); X = bsxfun(@times, X, 1./max(X, [], dim)); end
github
ojwoodford/ojwul-master
normd.m
.m
ojwul-master/numeric/normd.m
483
utf_8
15ade47822ea81b1839ab3528ecf0fa4
%NORMD Compute the 2-norms of vectors in an array along a specific dimension % % Y = normd(X) % Y = normd(X, dim) % % Compute the 2-norms of vectors in an array, along a specific dimension. % %IN: % X - Array containing vectors to compute the norms of. % dim - Dimension along which to compute the 2-norm. Default: first % non-singleton dimension of X. % %OUT: % Y - 2-norms of X. function X = normd(X, varargin) X = sqrt(sum(X .* X, varargin{:}));
github
ojwoodford/ojwul-master
inv44n.m
.m
ojwul-master/linear/inv44n.m
2,251
utf_8
14bff2f4c1537e18cea4be0b8fc0b81c
%INV44N Compute the inverse of an array of 4x4 matrices % % [B, d] = inv44n(A) % % Vectorized computation of the inverse of multiple 4x4 matrices. % %IN: % A - 4x4xN array. % %OUT: % B - 4x4xN array, where B(:,:,a) = inv(A(:,:,a)). % d - 1xN array, where d(a) = det(A(:,:,a)). function [B, det] = inv44n(A) s0 = A(1,1,:) .* A(2,2,:) - A(2,1,:) .* A(1,2,:); s1 = A(1,1,:) .* A(2,3,:) - A(2,1,:) .* A(1,3,:); s2 = A(1,1,:) .* A(2,4,:) - A(2,1,:) .* A(1,4,:); s3 = A(1,2,:) .* A(2,3,:) - A(2,2,:) .* A(1,3,:); s4 = A(1,2,:) .* A(2,4,:) - A(2,2,:) .* A(1,4,:); s5 = A(1,3,:) .* A(2,4,:) - A(2,3,:) .* A(1,4,:); c5 = A(3,3,:) .* A(4,4,:) - A(4,3,:) .* A(3,4,:); c4 = A(3,2,:) .* A(4,4,:) - A(4,2,:) .* A(3,4,:); c3 = A(3,2,:) .* A(4,3,:) - A(4,2,:) .* A(3,3,:); c2 = A(3,1,:) .* A(4,4,:) - A(4,1,:) .* A(3,4,:); c1 = A(3,1,:) .* A(4,3,:) - A(4,1,:) .* A(3,3,:); c0 = A(3,1,:) .* A(4,2,:) - A(4,1,:) .* A(3,2,:); det = s0 .* c5 - s1 .* c4 + s2 .* c3 + s3 .* c2 - s4 .* c1 + s5 .* c0; invdet = 1 ./ det; B(1,1,:) = ( A(2,2,:) .* c5 - A(2,3,:) .* c4 + A(2,4,:) .* c3) .* invdet; B(1,2,:) = (-A(1,2,:) .* c5 + A(1,3,:) .* c4 - A(1,4,:) .* c3) .* invdet; B(1,3,:) = ( A(4,2,:) .* s5 - A(4,3,:) .* s4 + A(4,4,:) .* s3) .* invdet; B(1,4,:) = (-A(3,2,:) .* s5 + A(3,3,:) .* s4 - A(3,4,:) .* s3) .* invdet; B(2,1,:) = (-A(2,1,:) .* c5 + A(2,3,:) .* c2 - A(2,4,:) .* c1) .* invdet; B(2,2,:) = ( A(1,1,:) .* c5 - A(1,3,:) .* c2 + A(1,4,:) .* c1) .* invdet; B(2,3,:) = (-A(4,1,:) .* s5 + A(4,3,:) .* s2 - A(4,4,:) .* s1) .* invdet; B(2,4,:) = ( A(3,1,:) .* s5 - A(3,3,:) .* s2 + A(3,4,:) .* s1) .* invdet; B(3,1,:) = ( A(2,1,:) .* c4 - A(2,2,:) .* c2 + A(2,4,:) .* c0) .* invdet; B(3,2,:) = (-A(1,1,:) .* c4 + A(1,2,:) .* c2 - A(1,4,:) .* c0) .* invdet; B(3,3,:) = ( A(4,1,:) .* s4 - A(4,2,:) .* s2 + A(4,4,:) .* s0) .* invdet; B(3,4,:) = (-A(3,1,:) .* s4 + A(3,2,:) .* s2 - A(3,4,:) .* s0) .* invdet; B(4,1,:) = (-A(2,1,:) .* c3 + A(2,2,:) .* c1 - A(2,3,:) .* c0) .* invdet; B(4,2,:) = ( A(1,1,:) .* c3 - A(1,2,:) .* c1 + A(1,3,:) .* c0) .* invdet; B(4,3,:) = (-A(4,1,:) .* s3 + A(4,2,:) .* s1 - A(4,3,:) .* s0) .* invdet; B(4,4,:) = ( A(3,1,:) .* s3 - A(3,2,:) .* s1 + A(3,3,:) .* s0) .* invdet; end
github
ojwoodford/ojwul-master
cross.m
.m
ojwul-master/linear/cross.m
2,275
utf_8
730d29b6bf45181cf2d3a230017ba4af
function c = cross(a,b,dim) %CROSS Vector cross product. % C = CROSS(A,B) returns the cross product of the vectors % A and B. That is, C = A x B. A and B must be 3 element % vectors. % % C = CROSS(A,B) returns the cross product of A and B along the % first dimension of length 3. % % C = CROSS(A,B,DIM), where A and B are N-D arrays, returns the cross % product of vectors in the dimension DIM of A and B. A and B must % have the same size, and both SIZE(A,DIM) and SIZE(B,DIM) must be 3. % % Class support for inputs A,B: % float: double, single % % See also DOT. % Copyright 1984-2012 The MathWorks, Inc. % Special case: A and B are vectors if isvector(a) && isvector(b) if (nargin == 2 && (length(a) ~= 3 || length(b) ~= 3)) || ... (nargin == 3 && (size(a,dim)~=3 || size(b,dim)~=3)) error(message('MATLAB:cross:InvalidDimAorBForCrossProd')) end % Calculate cross product c = [a(2).*b(3)-a(3).*b(2); a(3).*b(1)-a(1).*b(3); a(1).*b(2)-a(2).*b(1)]; if ~iscolumn(a) || ~iscolumn(b) c = c.'; end else % general case % Check dimensions sza = size(a); szb = size(b); sza(end+1:numel(sza)) = 1; szb(end+1:numel(szb)) = 1; if any(sza ~= szb & sza ~= 1 & szb ~= 1) error(message('MATLAB:cross:InputSizeMismatch')); end if nargin == 2 dim = find(sza == 3,1); if isempty(dim) error(message('MATLAB:cross:InvalidDimAorB')); end elseif size(a, dim) ~= 3 error(message('MATLAB:cross:InvalidDimAorBForCrossProd')) end if size(b, dim) ~= 3 error(message('MATLAB:cross:InvalidDimAorBForCrossProd')) end if dim == 1 % Calculate cross product c = ro(bsxfun(@times, a, ro(b)) - bsxfun(@times, ro(a), b)); else % Permute so that DIM becomes the row dimension perm = [dim:max([ndims(a) ndims(b) dim]) 1:dim-1]; a = permute(a, perm); b = permute(b, perm); % Calculate cross product c = ro(bsxfun(@times, a, ro(b)) - bsxfun(@times, ro(a), b)); % Post-process. c = ipermute(c, perm); end end end function X = ro(X) X = reshape(X([2 3 1],:), size(X)); end
github
ojwoodford/ojwul-master
isposdef.m
.m
ojwul-master/linear/isposdef.m
266
utf_8
0c7220c903df17ddae3c6d1f2f6d7544
%ISPOSDEF Check if a square matrix is positive definite % % tf = isposdef(A) % %IN: % A - NxN matrix. % %OUT: % tf - boolean indicating whether A is positive definite. function tf = isposdef(A) [~, tf] = chol(A); tf = (tf == 0) && (rank(A) == size(A, 1)); end
github
ojwoodford/ojwul-master
inv33n.m
.m
ojwul-master/linear/inv33n.m
564
utf_8
cc713280e9ef287893c776d0bb44b625
%INV33N Compute the inverse of an array of 3x3 matrices % % [B, d] = inv33n(A) % % Vectorized computation of the inverse of multiple 3x3 matrices. % %IN: % A - 3x3xN array. % %OUT: % B - 3x3xN array, where B(:,:,a) = inv(A(:,:,a)). % d - 1xN array, where d(a) = det(A(:,:,a)). function [T, det] = inv33n(T) sz = size(T); det = det33n(T); T = reshape(T, 9, []); T = T([5 8 2 7 1 4 4 7 1],:) .* T([9 3 6 6 9 3 8 2 5],:) - T([8 2 5 4 7 1 7 1 4],:) .* T([6 9 3 9 3 6 5 8 2],:); T = reshape(bsxfun(@times, (T + 1e-322), 1 ./ det), sz); end
github
ojwoodford/ojwul-master
invSE3n.m
.m
ojwul-master/linear/invSE3n.m
435
utf_8
b18da849ddbbaed68c17c33dbcb4a630
%INVSE3N Compute the inverse of an array of 3x4 SE3 matrices % % [B, d] = invSE3n(A) % % Vectorized computation of the inverse of multiple 3x4 SE3 matrices. % %IN: % A - 3x4xN array of SE3 matrices. % %OUT: % B - 3x4xN array of inverse SE3 matrices. function T = invSE3n(T) R = permute(T(1:3,1:3,:), [2 1 3]); % Transpose the R matrix T(1:3,1:3,:) = R; T(1:3,4,:) = tmult(R, -T(1:3,4,:)); % Compute R' * -T end
github
ojwoodford/ojwul-master
det33n.m
.m
ojwul-master/linear/det33n.m
584
utf_8
3d07d701f15024db467c402a4600390a
%DET33N Compute the determinant of an array of 3x3 matrices % % d = det33n(A) % % Vectorized computation of the determinant of multiple 3x3 matrices. % %IN: % A - 3x3xN array. % %OUT: % d - 1xN array, where d(a) = det(A(:,:,a)). function T = det33n(T) T = reshape(T, 9, []); cond = zeros(size(T)); d = 1 ./ (1 + abs(T([1 5 9],:))); cond([1 5 9],:) = d; T = tmult(reshape(T, 3, 3, []), reshape(cond, 3, 3, [])); T = reshape(T, 9, []); T = T([1 2 3 1 3 2],:) .* T([5 6 4 6 5 4],:) .* T([9 7 8 8 7 9],:); T = sum(T(1:3,:) - T(4:6,:)); T = T ./ prod(d); end
github
ojwoodford/ojwul-master
pca.m
.m
ojwul-master/linear/pca.m
1,299
utf_8
41e51e264202aacba6887d551cf4746e
%PCA Principal component analysis % % [T, Y, V] = pca(X) % % IN: % X - MxN matrix of N vectors of dimension M. % % OUT: % T - Mx(M+1) Projection matrix for PCA transformation % Y - MxN matrix of transformed vectors, where Y = T * [X; ones(1, N)]. % V - Mx1 list of eigen values associated with each dimension. function [T, X, V] = pca(X) % Check for NaNs if ~any(isnan(X(:))) % Compute the mean and subtract t = mean(X, 2); X = bsxfun(@minus, X, t); % Do the economy svd, to avoid memory issues [R, V] = svd(X, 'econ'); R = R'; if nargout > 2 % Square the singular values to give eigenvalues V = diag(V); V = (V .* V) ./ size(X, 2); end else % Have NaNs! % Compute the mean and subtract t = mean(X, 2, 'omitnan'); X = bsxfun(@minus, X, t); % Compute the covariance matrix sd = sqrt(mean(X .* X, 2, 'omitnan')); C = corrcoef(X', 'rows', 'pairwise'); C = C .* (sd * sd'); % Compute the eigen values and vectors [R, V] = eig(C); % Reorder so largest first V = flipud(diag(V)); R = R(:,end:-1:1)'; end % Compose the transform T = [R -(R * t)]; if nargout > 1 % Apply the transform X = R * X; end end
github
ojwoodford/ojwul-master
tmult.m
.m
ojwul-master/linear/tmult.m
2,711
utf_8
a0e531042d0030663fd3f37c2dc1fbc2
%TMULT Tensor matrix multiply % % C = tmult(A, B, [transpose]) % % Matrix multiplication over tensor arrays (i.e. arrays of matrices), with % the ability to transpose matrices first. % % C = tmult(A, B) is equivalent to: % % sz = [size(B) 1]; % sz(1) = size(A, 1); % C = zeros(sz); % for a = 1:prod(sz(3:end)) % C(:,:,a) = A(:,:,a) * B(:,:,a); % end % % but is completely vectorized, so much faster. Tmult also supports % bsxfun-style expansion of singular dimensions where appropriate, such % that tmult(rand(4, 3, 10), rand(3, 2)) yields a 4x2x10 output. % %IN: % A - PxQx... array of input PxQ matrices, or QxP if transposed. % B - QxRx... array of input QxR matrices, or RxQ if transposed. % transpose - 2x1 logical array indicating which of the input matrices % need to be transposed before the multiply. Default: [0 0]. % %OUT: % C - PxRx... output array. function A = tmult(A, B, transpose) szB = [size(B) 1]; szA = [size(A) 1]; if nargin < 3 transpose = 0; else transpose = [transpose(:); 0]; transpose = [1 2] * (transpose(1:2) ~= 0); if transpose == 3 % Permutation required. Choose the matrix which permutes fastest. pa = any(szA(1:2) == 1); pb = any(szB(1:2) == 1); if pa || (~pb && numel(A) < numel(B)) if ~pa p = 1:numel(szA); p(1:2) = p([2 1]); A = permute(A, p); end szA(1:2) = szA([2 1]); transpose = 2; else if ~pb p = 1:numel(szB); p(1:2) = p([2 1]); B = permute(B, p); end szB(1:2) = szB([2 1]); transpose = 1; end end end switch transpose case 0 % No transposes A = reshape(A, szA([1:2 end 3:end-1])); B = reshape(B, szB([end 1:end-1])); dim = 2; szB(1) = szA(1); case 1 % First matrix transposed A = reshape(A, szA([1:2 end 3:end-1])); B = reshape(B, szB([1 end 2:end])); dim = 1; szB(1) = szA(2); case 2 % Second matrix transposed A = reshape(A, szA([1 end 2:end])); B = reshape(B, szB([end 1:end-1])); dim = 3; szB(2) = szB(1); szB(1) = szA(1); end % Compute the output A = dot(A, B, dim); % Reshape to expected size szA = [szA ones(1, numel(szB)-numel(szA))]; szB = [szB ones(1, numel(szA)-numel(szB))]; M = [szA; szB]; M = (max(M) <= 1) & (min(M) == 0); M(1:2) = false; szB(3:end) = max(szB(3:end), szA(3:end)); szB(M) = 0; A = reshape(A, szB); end
github
ojwoodford/ojwul-master
chol22n.m
.m
ojwul-master/linear/chol22n.m
525
utf_8
cac431a9a2f1d476ea0b607172597a6f
%CHOL22N Compute the Cholesky decomposition of an array of 2x2 matrices % % B = chol22n(A) % % Vectorized computation of the Cholesky decomposition of multiple 2x2 % matrices. % %IN: % A - 2x2xN array. % %OUT: % B - 2x2xN array, where B(:,:,a) = chol(A(:,:,a), 'lower'). % Formula from here: http://metamerist.blogspot.com/2008/03/googlaziness-cholesky-2x2.html function T = chol22n(T) a = sqrt(T(1,1,:)); b = T(2,1,:) ./ a; c = sqrt(T(2,2,:) - b .* b); T = [a zeros(1, 1, size(T, 3)); b c]; end
github
ojwoodford/ojwul-master
whiten_srt.m
.m
ojwul-master/linear/whiten_srt.m
693
utf_8
81a53816a156dc60778e232690a33aa9
%WHITEN_SRT Transform data to be zero mean and close to identity covariance % % [Y, T] = whiten_srt(X) % % Apply a similarity transform to the data such that the mean is zero and % the covariance is as close to the identity as possible. % %IN: % X - MxN array of N vectors of dimension M to be whitened % % Y - (M+1)xN array of whitened data. % T - (M+1)x(M+1) matrix for the transformation proj(T \ homg(Y)) = X. function [X, T] = whiten_srt(X) % Subtract the mean mu = mean(X, 2); X = bsxfun(@minus, X, mu); % Whitening the covariance [T, s] = svd(X * X'); T = T * sqrt((size(X, 2) - 1) ./ max(diag(s))); X = T * X; % Construct the transform T(:,end+1) = T * -mu; T(3,3) = 1; end
github
ojwoodford/ojwul-master
whiten.m
.m
ojwul-master/linear/whiten.m
762
utf_8
74a208f31dba9cc99791735e5ef5310d
%WHITEN Transform data to be zero mean and identity covariance % % [Y, T] = whiten(X, [epsilon]) % %IN: % X - MxN array of N vectors od dimension M to be whitened % epsilon - scalar value to add to eigen values to avoid amplifying % noise. Default: 1e-4. % % Y - MxN array of whitened data. % T - (M+1)x(M+1) matrix for the transformation [Y; 1] = T * [X; 1]. function [X, T] = whiten(X, epsilon) % Set the default epsilon if nargin < 2 epsilon = 1e-4; end % Subtract the mean mu = mean(X, 2); X = bsxfun(@minus, X, mu); % Whitening the covariance [V, D] = svd(X * X'); T = V' * diag(sqrt((size(X, 2) - 1) ./ (diag(D) + epsilon))) * V; X = T * X; % Construct the transform mu = T * -mu; T(end+1,end+1) = 1; T(1:end-1,end) = mu; end
github
ojwoodford/ojwul-master
linear_regressor.m
.m
ojwul-master/linear/linear_regressor.m
2,399
utf_8
2b1edd7949fb50b4886bc0009e8a8527
classdef linear_regressor < handle properties (SetAccess = private, Hidden = true) parameters; regularization_lambda = 0; isquadratic = false; end methods function this = linear_regressor(quad, reg) if nargin > 0 this.isquadratic = quad; if nargin > 1 this.regularization_lambda = reg; end end end function train(this, X, y) % Preprocess the data X = quadraticize(this, X'); norm_mat = compute_normalization(X); X(:,end+1) = 1; X = X * norm_mat; % Train if this.regularization_lambda % Minimize the regularized cost using a local optimizer this.parameters = fmincg(@(theta) linear_regression_cost(X, y, theta, this.regularization_lambda), zeros(size(X, 2), 1), optimset('MaxIter', 200, 'GradObj', 'on')); else % Solve the normal equation linear system this.parameters = (X' * X) \ (X' * y(:)); end % Apply the normalization this.parameters = norm_mat * this.parameters; end function y = test(this, X) % Preprocess the data X = quadraticize(this, X'); X(:,end+1) = 1; % Compute the output y = X * this.parameters; end function X = quadraticize(this, X) if this.isquadratic [m, n] = size(X); X = [X reshape(bsxfun(@times, X, reshape(X, m, 1, n)), m, n*n)]; end end end end function norm_mat = compute_normalization(X) m = mean(X, 1); X = bsxfun(@minus, X, m); s = 1 ./ (sqrt(mean(X .* X, 1)) + 1e-38); norm_mat = diag(s); norm_mat(end+1,:) = -(m .* s); norm_mat(end,end+1) = 1; end function [J, grad] = linear_regression_cost(X, y, theta, lambda) if nargin < 4 lambda = 0; end m = numel(y); % number of training examples hx = X * theta; grad = hx - y(:); J = grad' * grad; if lambda J = J + (theta(2:end)' * theta(2:end)) * lambda; end J = J / (2 * m); if nargout > 1 grad = sum(bsxfun(@times, grad, X), 1)' / m; if lambda grad(2:end) = grad(2:end) + theta(2:end) * (lambda / m); end end end
github
ojwoodford/ojwul-master
eig22n.m
.m
ojwul-master/linear/eig22n.m
710
utf_8
d4eb84365738b510a317624640f6432c
%EIG22N Compute the eigenvalues and eigenvectors of 2x2 matrices % % [e, V] = eig22n(A) % % Vectorized computation of the eigenvalues and eigenvectors of multiple % 2x2 matrices. % %IN: % A - 2x2xN array. % %OUT: % e - 2x1xN array, where e(:,a) = eig(A(:,:,a)). % V - 2x2xN array, where [V(:,:,a), ~] = eig(A(:,:,a)). function [e, V] = eig22n(A) % First compute the eigenvalues using the quadratic equation b = A(1,1,:) + A(2,2,:); e = A(2,1,:) .* A(1,2,:) - A(1,1,:) .* A(2,2,:); e = sqrt(b .* b + 4 * e); e = [b + e; b - e] * 0.5; if nargout < 2 return; end % Now solve for the eigenvectors V = normalize(reshape(sum(A, 1), 2, 1, []) - reshape(e, 1, 2, []), 1); V = [-V(2,:,:); V(1,:,:)]; end
github
ojwoodford/ojwul-master
inv22n.m
.m
ojwul-master/linear/inv22n.m
509
utf_8
d3988bcba15c758442d58d984be90c23
%INV22N Compute the inverse of an array of 2x2 matrices % % [B, d] = inv22n(A) % % Vectorized computation of the inverse of multiple 2x2 matrices. % %IN: % A - 2x2xN array. % %OUT: % B - 2x2xN array, where B(:,:,a) = inv(A(:,:,a)). % d - 1xN array, where d(a) = det(A(:,:,a)). function [T, det] = inv22n(T) sz = size(T); T = reshape(T, 4, []); T = T([4 2 3 1],:); T(2:3,:) = -T(2:3,:); det = T(1,:) .* T(4,:) - T(2,:) .* T(3,:); T = reshape(bsxfun(@times, T, 1 ./ det), sz); end
github
ojwoodford/ojwul-master
edge_demo.m
.m
ojwul-master/edges/edge_demo.m
1,554
utf_8
9a4ed09075dbf09302013c950184e2b6
%EDGE_DEMO Compute and visualize the gradient and edgels of an image % % edge_demo % edge_demo(A, scale, thresh) % %IN: % A - HxWxC image. Default: Use peppers.png % scale - sigma of Gaussian blur to apply during edge detection. % Default: 0.7. % thresh - Threshold on edgel suppression. If negative, magnitude is % interpreted as the proportion of pixels to return as edgels. % Default: -0.05, i.e. keep top 5% of pixels, by edge strength. function edge_demo(A, scale, thresh) % Set default arguments if nargin < 3 thresh = -0.05; % Negative numbers indicate ratio of edges to keep if nargin < 2 scale = 0.7; if nargin < 1 A = imread('peppers.png'); end end end % Compute the gradient image tic; G = imgrad(A, scale, 'dizenzo'); t1 = toc; % Compute a reasonable edgel threshold if thresh < 0 s = sort(reshape(sum(G .* G, 3), [], 1), 'descend'); thresh = sqrt(s(ceil(end*-thresh))); fprintf('Edgel threshold: %g\n', thresh); end % Compute the edgels tic; X = compute_edgels(G, thresh); t2 = toc; % Visualization fprintf('Computing gradients: %gs\nExtracting edgels: %gs\n', t1, t2); clf; % Render the gradient image sc(G, 'flow', [0 thresh*2]); % Render the edgels hold on c = 0.5 * cos(reshape(X(3,:), 1, 1, [])); s = 0.5 * sin(reshape(X(3,:), 1, 1, [])); X = bsxfun(@plus, reshape(X(1:2,:), 2, 1, []), [-s s; c -c]); plot(squeeze(X(1,:,:)), squeeze(X(2,:,:)), 'r-', 'LineWidth', 2); hold off
github
ojwoodford/ojwul-master
edge_orient.m
.m
ojwul-master/edges/edge_orient.m
1,697
utf_8
15cb5f6b3da227debeff758ef7043493
%EDGE_ORIENT Calculate edge filter responses at any orientation % % [R, O, G] = edge_orient(I, sigma, [mcm]) % % Returns a handle to a function that generates an edge filter response % image using angularly adaptive filtering, and also outputs the angle that % gives maximal edge response. The implementation uses separable, steerable % filters, hence is fast. % % For multi-channel images, the gradient is computed in the colour % direction of greatest change. % % IN: % I - HxWxC input image. % sigma - Scalar value determing the scale of the edge filter % (essentially the amount of pre-smoothing to apply). % mcm - multi-channel method: 'dizenzo' (default), 'norm', 'pca', % 'rgb2gray'. % % OUT: % R - @(theta) anonymous function, which, when given a scalar angle (in % radians), or HxW angle array, returns an HxW edge filter response % image for the angle(s) given. R(O) is the maximal edge filter % response for each pixel. % O - HxW edge orientation image, returning the angle, in radians, of the % maximal filter response at each pixel. % G - HxWx2 array of gradient images in x and y directions, along third % dimension. function [R, O, G] = edge_orient(I, sigma, mcm) % Set the default method if nargin < 3 mcm = 'dizenzo'; end % Compute the image gradients [Ix, Iy] = imgrad(I, sigma, mcm); % Output function that generates response at any angle R = @(theta) cos(theta) .* Ix + sin(theta) .* Iy; if nargout > 1 % Evaluate the orientation, in radians O = atan2(Iy, Ix); if nargout > 2 G = cat(3, Ix, Iy); end end return
github
ojwoodford/ojwul-master
edge_grad_max.m
.m
ojwul-master/edges/edge_grad_max.m
2,128
utf_8
59bbc912b76006eae4bc3b0b297e10d2
%EDGE_GRAD_MAX Mask of gradient maxima % % M = edge_grad_max(G, [thresh, [M]]) % % Given a gradient image, computes the magnitude of locally maximal (in the % direction of maximum gradient) gradients. % % IN: % G - HxWx2 array of gradient images in x and y directions, along third % dimension. % thresh - Scalar value determining the threshold of the second % derivative of gradient above which to ignore edges. Default: % 0. % M - HxW logical image of pixels to look for maxima at. % % OUT: % Mo - HxWx3 masked gradient (0 if not locally maximal), gradient and % gradient derivative magnitudes image. % X - 2x(sum(M(:))) array of subpixel edgelet dimensions. function [M, X] = edge_grad_max(G, thresh, M) % Default values if nargin < 3 M = true(size(G, 1), size(G, 2)); if nargin < 2 thresh = 0; end end % Sample in direction of maximum gradient GM = reshape(G, [], 2); GM = GM(M,:); off = bsxfun(@times, GM, 1./(max(abs(GM), [], 2) + 1e-100)); [Y, X] = find(M); a = reshape(ojw_interp2(G, bsxfun(@plus, X, [-off(:,1) off(:,1)]), bsxfun(@plus, Y, [-off(:,2) off(:,2)]), 'l', cast(0, class(G))), [], 2, 2); % Compute normalized edge direction mag = normd(GM, 2); nm = bsxfun(@times, GM, 1 ./ (mag + 1e-100)); % Compute derivatives of gradient magnitude in direction of maximum % gradient a = abs(sum(bsxfun(@times, a, reshape(nm, [], 1, 2)), 3)); deriv_2nd = 2 * mag - sum(a, 2); % Output the edge gradient magnitude M_ = M; M = zeros(numel(M), 2); M(M_,1) = mag; M(M_,2) = mag; M(M_,3) = deriv_2nd; % Find gradient maxima above the threshold M_(M_) = all(bsxfun(@gt, mag, a), 2) & mag > thresh & deriv_2nd > thresh; % Mask boundary pixels M_([1 end],:) = false; M_(:,[1 end]) = false; % Mask output magnitudes M(~M_,1) = 0; M = reshape(M, [size(G, 1), size(G, 2) 3]); if nargout > 1 % Sub-pixel refine the edgelets in the direction of maximum gradient off = 0.5 * normd(off, 2) .* diff(a, 1, 2) ./ deriv_2nd; X = [(X + nm(:,1) .* off)'; (Y + nm(:,2) .* off)']; end end
github
ojwoodford/ojwul-master
edge_scale.m
.m
ojwul-master/edges/edge_scale.m
3,642
utf_8
2f8b378bdf47530ade9e24ab3a115f5a
%EDGE_SCALE Compute an edge scale image % % [S, G, E] = edge_scale(I, [max_octaves, [levels_per_octave, [thresh]]]) % % Output the edge scale of each pixel, and a list of edgels, if requested. % The scale of an edge is determined by the amount of image smoothing % required before it stops being a locally maximal gradient. % % IN: % I - HxWxC input image. % max_octaves - integer indicating the number of scale octaves to search % over, from 0 (original image only) to Inf (coarsest scale % possible). Default: Inf. % levels_per_octave - positive integer indicating the number scale levels % to have per octave (halving of image size). % Default: 1. % % OUT: % S - HxW edge scale image, indicating for each pixel the coarsest octave % at which that pixel is an edge (starting from 0), or -1 if not an % edge. % G - HxWx2 gradient image at the finest scale. % E - 5xN list of edgels, each column giving [x y angle mag scale] of the % edgel centre. function [S, G, E] = edge_scale(I, max_octaves, levels_per_octave, thresh) % Default values if nargin < 4 thresh = 0; if nargin < 3 levels_per_octave = 1; if nargin < 2 max_octaves = Inf; end end end [h, w, c] = size(I); max_octaves = min(max_octaves, floor(log2(min(h, w))) - 3); max_octaves = max_octaves * levels_per_octave - 1; % Prefilter the image sigma = 1.0; if sigma > 0.5 I = filter(I, sqrt(sigma * sigma - 0.25)); end % Compute the gradient image at the coarsest scale grad = @(I) imgrad(I, 0, 'norm'); [Ix, Iy] = grad(I); G = cat(3, Ix, Iy); if nargout < 3 % Compute the gradient maxima and subpixel locations M = edge_grad_max(G, thresh); M = M(:,:,1) ~= 0; else % Compute the gradient maxima and subpixel locations [M, X] = edge_grad_max(G, thresh); mag = M(:,:,1); M = mag ~= 0; mag = mag(M); % Compute the edge angles, in radians angle = atan2(Iy(M), Ix(M)); % Output only those edgelets which meet the criteria E = [X(:,M); angle'; mag']; Morig = M; end clear Ix Iy % Initialize the scale image S = (M - 1) * levels_per_octave; % Now go over each further octave scale = 0; octave = 0; Mlow = M; while any(Mlow(:)) % Increase the scale scale = scale + 1; if scale > max_octaves break; end % Compute the filter sigma_new = sigma * (2 ^ (1 / levels_per_octave)); g = gauss_mask(sqrt(sigma_new * sigma_new - sigma * sigma)); sigma = sigma_new; % Filter the image I = filter(I, g); % Subsample if necessary if mod(scale, levels_per_octave) == 0 I = I(1:2:end,1:2:end,:); Mlow = conv2([1 1 1], [1; 1; 1], single(Mlow), 'same') > 0; Mlow = Mlow(1:2:end,1:2:end); sigma = sigma / 2; octave = octave + 1; end % Find the gradient maxima M_ = edge_grad_max(grad(I), 0, Mlow); M_ = M_(:,:,1) ~= 0; Mlow = Mlow & M_; % Upscale to original size M_(end+1,end+1) = false; M_ = single(M_); for a = 1:octave; M_ = interp2(M_); end % Update the mask M_ = M_(1:h,1:w) ~= 0; M = M & M_; % Update the scales S(M) = scale; end % Rescale the scale S = S / levels_per_octave; % Add scale onto the edgelet descriptions if nargout > 1 E = [E; S(Morig)']; end end function I = filter(I, g) g = g / sum(g); I = imfiltsep(I, g, g); end
github
ojwoodford/ojwul-master
compute_edgels.m
.m
ojwul-master/edges/compute_edgels.m
3,118
utf_8
f0cfd6d776fe3d002ffd49a5f7164962
%COMPUTE_EDGELS Extract edgels from a gradient image % % E = compute_edgels(G, thresh) % % Returns a list of edgel positions and normal angles, each edgel being a % pixel long, given a gradient image and threshold parameter. % % IN: % G - HxWx2 array of gradient images in x and y directions, along third % dimension. % thresh - Scalar value determining the threshold of the second % derivative of gradient at which to ignore edges. % % OUT: % E - 3xN list of edgels, each column giving [x y angle] of the edgel % centre. % I - Mx1 list of chain start indices (if min_length > 0) function [E, I] = compute_edgels(G, thresh, min_length, join_thresh) if nargin < 4 join_thresh = 0; if nargin < 3 min_length = 0; if nargin < 2 thresh = 0; end end end % Compute the gradient maxima and subpixel locations [M, E] = edge_grad_max(G, thresh); % Compute the edgeness map M_ = M(:,:,1) ~= 0; M = (M(:,:,3) .* M_) ./ (M(:,:,2) + 20); % Output only those edgelets which meet the criteria G = reshape(G, [], 2); E = [E(:,M_); normalize([-G(M_,2)'; G(M_,1)']); M(M_)']; % Compute the edgelets or edge chains I = []; if min_length % Create an index matrix I = M; M_ = find(M_); n = numel(M_); I(M_) = 1:n; I(I==0) = n + 1; % Extract the neighbours to the right and below Y = [E zeros(5, 1)]; off = size(M, 1); off = [-off-1, -off, -off+1, -1, 1, off-1, off, off+1]'; I = I(bsxfun(@plus, M_', off)); Y = reshape(Y(:,I), 5, 8, n); % Compute the edge score for the neighbours Z = normalize(bsxfun(@minus, reshape(E(1:2,:), 2, 1, []), Y(1:2,:,:))); Z = reshape(bsxfun(@times, abs(sum(bsxfun(@times, reshape(E(3:4,:), 2, 1, []), Z), 1) .* sum(Y(3:4,:,:) .* Z, 1)) .* Y(5,:,:), reshape(E(5,:), 1, 1, [])), 8, n); % Compute the chains [J, I] = compute_chains(Z, I, min_length, join_thresh); E = E(:,J); end % Compute the edge angles, in radians E = [E(1:2,:); atan2(-E(3,:), E(4,:)); E(5,:)]; end function [I, J] = compute_chains(Z, L, min_length, thresh) I = zeros(size(Z, 2), 1); ic = 0; ic_last = 0; J = I; jc = 1; K = uint8(sum(Z > thresh, 1)'); M = [K < 0; true]; i_ = uint32(0); opts = {'==', uint8(1)}; while 1 % Select the start point i = find_first(K, opts{:}, i_); if ~i if isempty(opts) break; end opts = {}; continue; end i_ = i; J(jc) = ic + 1; % Build the chain l = 0; m = thresh * (i ~= uint32(0)) + 1; while m > thresh % Add to the chain ic = ic + 1; I(ic) = i; M(i) = true; K(i) = 0; l = l + 1; % Find the next edge k = Z(:,i); k(M(L(:,i))) = 0; [m, j] = max(k); i = L(j,i); end % Check it's long enough if l < min_length; ic = ic_last; else jc = jc + 1; ic_last = ic; end end I = I(1:ic); J = J(1:jc-1); end
github
ojwoodford/ojwul-master
tensor_voted_edges.m
.m
ojwul-master/edges/tensor_voted_edges.m
2,114
utf_8
0f69548b15f818bc7e694233d37f96d7
% Author: Emmanuel Maggiori. March 2014. % % Complimentary material for the literature review: % "Perceptual grouping by tensor voting: a comparative survey of recent approaches". E Maggiori, HL Manterola, M del fresno. To be published in IET Computer Vision. % % Implementation of Steerable Tensor Voting as published in: % "An efficient method for tensor voting using steerable filters", Franken et. al. ECCV 2006. function grad_im = tensor_voted_edges(grad_im, sigma) s = normd(grad_im, 3); be = pi/2 + mod(atan2(grad_im(:,:,2), grad_im(:,:,1)), pi); [height, width] = size(s); c0=c(0,s,be); c2=c(2,s,be); c4=c(4,s,be); c6=c(6,s,be); c2bar=conj(c2); w0=w(0,height,width,sigma); w2=w(2,height,width,sigma); w4=w(4,height,width,sigma); w6=w(6,height,width,sigma); w8=w(8,height,width,sigma); c0_f=fft2(c0); c2_f=fft2(c2); c4_f=fft2(c4); c6_f=fft2(c6); c2bar_f=fft2(c2bar); w0_f=fft2(w0); w2_f=fft2(w2); w4_f=fft2(w4); w6_f=fft2(w6); w8_f=fft2(w8); w0_c2bar=w0_f.*c2bar_f; %eight convolutions required w2_c0=w2_f.*c0_f; w4_c2=w4_f.*c2_f; w6_c4=w6_f.*c4_f; w8_c6=w8_f.*c6_f; w0_c0=w0_f.*c0_f; w2_c2=w2_f.*c2_f; w4_c4=w4_f.*c4_f; U_minus2= ifftshift( ifft2( (w0_c2bar) + 4*(w2_c0) + 6*(w4_c2) + 4*(w6_c4) + (w8_c6) ) ); U_2=conj(U_minus2); U_0= real( ifftshift( ifft2( 6*(w0_c0) + 8*(w2_c2) + 2*(w4_c4) ))); saliency = abs(U_minus2); orientation = 0.5 * angle(U_minus2); grad_im = cat(3, saliency .* sin(orientation), saliency .* cos(orientation)); end function im = c(m,s,be) %s: stickness field, be:orientation field im=s.*exp(-1i*m*be); end function kernel = w(m,h,w,sigma) w2=ceil(w/2.0); h2=ceil(h/2.0); [x, y] = meshgrid(1:w,1:h); kernel = exp(-(((x-w2).^2+(y-h2).^2)/(2*sigma^2))).*(((x-w2)+1i*(y-h2))./(sqrt((x-w2).^2+(y-h2).^2))).^m; kernel(h2,w2)=1; end
github
ojwoodford/ojwul-master
fast_kmeans.m
.m
ojwul-master/cluster/fast_kmeans.m
1,324
utf_8
6cf23c5f257a6576ed755100821fcb1f
%FAST_KMEANS Compute k-means cluster centres % % [CX sse I] = fast_kmeans(X, params[, CX]) % % This function computes k-means cluster centres. It will work faster if % data is projected onto principle components first. % % IN: % X - MxN matrix of N input vectors of dimension M. % params - [nclusters max_iters min_sse_delta robust_thresh]. % nclusters: number of required clusters. % max_iters: maximum number of iterations. % min_sse_delta: convergence threshold for change in error score. % robust_thresh: reject outliers more than robust_thresh % squared distance away from all cluster % centers. If 0, no outlier rejection. % CX - Mx(nclusters) matrix of initial cluster centres of X. Default: % randomly initialized to nclusters different vectors from X. % % OUT: % CX - Mx(nclusters) matrix of updated cluster centres of X. % sse - Sum of squared errors of distances to cluster centres. % I - Nx1 uint32 vector of cluster indices each input vector is assigned % to. function varargout = fast_kmeans(varargin) sourceList = {'fast_kmeans.cpp', '-Xopenmp'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
isautodiff.m
.m
ojwul-master/autodiff/isautodiff.m
104
utf_8
114480bc63ab1389236fc7fac0cbbea5
%ISAUTODIFF Helper for autodiff function tf = isautodiff(varargin) tf = false(1, max(nargin, 1)); end
github
ojwoodford/ojwul-master
var_indices.m
.m
ojwul-master/autodiff/var_indices.m
90
utf_8
343c2c6be93b20eb08c12d5780c90d43
%VAR_INDICES Dummy helper function for autodiff function c = var_indices(a) c = []; end
github
ojwoodford/ojwul-master
autodiff.m
.m
ojwul-master/autodiff/autodiff.m
25,193
utf_8
27a380b7799c8c8099d41e76ab04c2e2
% A class for doing autodifferentiation classdef autodiff properties (SetAccess = private, Hidden = true) value; % Function values Mx...xN deriv; % Jacobian values VxMx...xN varind; % Variable indices 1xV end methods function obj = autodiff(a, v, b) obj.value = a; if nargin > 1 obj.varind = v(:)'; %assert(isequal(obj.varind, unique(obj.varind))); if nargin > 2 obj.deriv = b; %assert(isequal(size(b), [numel(obj.varind) size(a)])); else % We assume that there is 1 varind per element in a obj.deriv = reshape(eye(numel(v)), [numel(a) size(a)]); end else obj.varind = 1:numel(a); obj.deriv = reshape(eye(numel(a)), [numel(a) size(a)]); end end % Get the values function c = double(obj) c = obj.value; end function c = grad(obj, vars) if nargin < 2 vars = obj.varind; elseif isscalar(vars) && vars < 0 % Return sparse output n = numel(obj.value); c = sparse(repmat(obj.varind(:), [n 1]), ... reshape(repmat(1:n, [numel(obj.varind(:)) 1]), [], 1), ... obj.deriv(:), ... -vars, n); return; end n = numel(vars); if n == numel(obj.varind) && n == vars(end) && n == obj.varind(end) c = obj.deriv; else c = zeros([n size(obj.value)]); [Lia, Locb] = ismember(vars, obj.varind); c(Lia,:) = obj.deriv(Locb(Lia),:); end end function c = var_indices(obj) c = obj.varind; end function disp(obj, varargin) fprintf('Value:\n'); disp(obj.value, varargin{:}); fprintf('Gradient:\n'); disp(obj.deriv, varargin{:}); fprintf('Gradient indices:\n'); disp(obj.varind, varargin{:}); end % Elementwise operators function c = plus(a, b) c = double(a) + double(b); [d, v] = add_grads(grad(a), grad(b), var_indices(a), var_indices(b), size(c)); c = autodiff(c, v, d); end function c = uminus(a) c = autodiff(-a.value, a.varind, -a.deriv); end function c = minus(a, b) c = a + (-b); end function c = times(a, b) da = double(a); db = double(b); d = []; v = []; if isautodiff(a) d = a.deriv .* shiftdim(db, -1); end if isautodiff(b) v = b.deriv .* shiftdim(da, -1); end c = da .* db; [d, v] = add_grads(d, v, var_indices(a), var_indices(b), size(c)); c = autodiff(c, v, d); end function c = dot(a, b, dim) if nargin < 3 dim = first_nonsingleton_dim(a, b); end da = double(a); db = double(b); d = []; v = []; if isautodiff(a) d = sum(a.deriv .* shiftdim(db, -1), dim+1); end if isautodiff(b) v = sum(b.deriv .* shiftdim(da, -1), dim+1); end c = dot(da, db, dim); [d, v] = add_grads(d, v, var_indices(a), var_indices(b), size(c)); c = autodiff(c, v, d); end function c = rdivide(a, b) da = double(a); db = double(b); d = []; v = []; if isautodiff(a) d = a.deriv .* shiftdim(db, -1); end if isautodiff(b) v = b.deriv .* -shiftdim(da, -1); end c = da ./ db; [d, v] = add_grads(d, v, var_indices(a), var_indices(b), size(c)); c = autodiff(c, v, d .* shiftdim(1 ./ (db .* db), -1)); end function c = ldivide(a, b) c = rdivide(b, a); end function c = power(a, b) da = double(a); db = double(b); d = []; v = []; c = da .^ db; if isautodiff(a) d = a.deriv .* shiftdim((da .^ (db-1)) .* db, -1); end if isautodiff(b) v = b.deriv .* shiftdim(c .* log(da), -1); end [d, v] = add_grads(d, v, var_indices(a), var_indices(b), size(c)); c = autodiff(c, v, d); end function c = bsxfun(func, a, b) c = func(a, b); end function c = conj(a) c = autodiff(conj(a.value), a.varind, conj(a.deriv)); end function c = abs(a) M = a.value < 0; c = reshape(a.deriv, [], numel(a.value)); c(:,M) = -c(:,M); c = autodiff(abs(a.value), a.varind, reshape(c, size(a.deriv))); end function c = exp(a) c = exp(a.value); c = autodiff(c, a.varind, shiftdim(c, -1) .* a.deriv); end function c = log(a) c = autodiff(log(a.value), a.varind, a.deriv .* (1 ./ shiftdim(a.value, -1))); end function c = sqrt(a) c = sqrt(a.value); c = autodiff(c, a.varind, a.deriv .* shiftdim(min(0.5 ./ c, 1e300), -1)); end function c = sin(a) c = autodiff(sin(a.value), a.varind, a.deriv .* shiftdim(cos(a.value), -1)); end function c = cos(a) c = autodiff(cos(a.value), a.varind, a.deriv .* shiftdim(-sin(a.value), -1)); end function c = tan(a) c = sec(a.value); c = autodiff(tan(a.value), a.varind, a.deriv .* shiftdim(c .* c, -1)); end function c = asin(a) c = autodiff(asin(a.value), a.varind, a.deriv .* shiftdim(1 ./ sqrt(1 - a.value .* a.value), -1)); end function c = acos(a) c = autodiff(acos(a.value), a.varind, a.deriv .* shiftdim(-1 ./ sqrt(1 - a.value .* a.value), -1)); end function c = atan(a) c = autodiff(atan(a.value), a.varind, a.deriv .* shiftdim(1 ./ (1 + a.value .* a.value), -1)); end % Matrix operators function c = mtimes(a, b) if isscalar(a) || isscalar(b) c = times(a, b); return; end da = double(a); db = double(b); c = da * db; v = combine_varind(a, b); sz = [numel(v) size(c)]; if isautodiff(a) g = reshape(reshape(grad(a, v), [], size(da, 2)) * db, sz); else g = 0; end if isautodiff(b) g = g + reshape(sum(shiftdim(da, -1) .* permute(grad(b, v), [1 4 2 3]), 3), sz); end c = autodiff(c, v, g); end function c = mrdivide(a, b) if isscalar(a) || isscalar(b) c = rdivide(a, b); return; end error('Matrix divides not yet supported in autodiff. Use inv if possible.'); end function c = mldivide(a, b) if isscalar(a) || isscalar(b) c = ldivide(a, b); return; end error('Matrix divides not yet supported in autodiff. Use inv if possible.'); end function c = inv(a) c = inv(a.value); sz = [size(a.deriv) 1]; d = -shiftdim(c, -1) .* reshape(a.deriv, sz([1 end 2:end-1])); d = reshape(sum(d, 3), sz); d = d .* shiftdim(c, -2); d = reshape(sum(d, 3), sz); c = autodiff(c, a.varind, d); end function c = pinv(a) c = pinv(a.value); ct = c'; d = permute(a.deriv, [1 3 2]); sz = [size(a.deriv) 1]; if sz(2) >= sz(3) d_ = reshape(sum(d .* shiftdim(ct, -2), 3), sz(1), sz(3), sz(3)); d_ = d_ - reshape(sum(shiftdim(c * a.value, -1) .* reshape(d_, sz(1), 1, sz(3), sz(3)), 3), sz(1), sz(3), sz(3)); d_ = d_ - reshape(sum(shiftdim(c, -1) .* reshape(a.deriv, sz(1), 1, sz(2), sz(3)), 3), sz(1), sz(3), sz(3)); d = reshape(d - reshape(sum(sum(d .* shiftdim(a.value, -2), 3) .* shiftdim(c, -3), 4), sz(1), sz(3), sz(2)), sz(1), 1, sz(3), sz(2)); d = reshape(sum(d_ .* shiftdim(c, -2), 3), sz(1), sz(3), sz(2)) + reshape(sum(shiftdim(c * ct, -1) .* d, 3), sz(1), sz(3), sz(2)); else d_ = reshape(sum(shiftdim(ct, -1) .* reshape(d, sz(1), 1, sz(3), sz(2)), 3), sz(1), sz(2), sz(2)); d_ = d_ - reshape(sum(d_ .* shiftdim(a.value * c, -2), 3), sz(1), sz(2), sz(2)); d_ = d_ - reshape(sum(a.deriv .* shiftdim(c, -2), 3), sz(1), sz(2), sz(2)); d = d - reshape(sum(shiftdim(c, -1) .* reshape(sum(shiftdim(a.value, -1) .* reshape(d, sz(1), 1, sz(3), sz(2)), 3), sz(1), 1, sz(2), sz(2)), 3), sz(1), sz(3), sz(2)); d = reshape(sum(shiftdim(c, -1) .* reshape(d_, sz(1), 1, sz(2), sz(2)), 3), sz(1), sz(3), sz(2)) + reshape(sum(d .* shiftdim(ct * c, -2), 3), sz(1), sz(3), sz(2)); end c = autodiff(c, a.varind, d); end function c = expm(a) c = expm(a.value); sz = [size(a.deriv) 1]; d = shiftdim(c, -1) .* reshape(a.deriv, sz([1 end 2:end-1])); d = reshape(sum(d, 3), sz); c = autodiff(c, a.varind, d); end function c = logm(a) sz = [size(a.deriv) 1]; d = shiftdim(inv(a.value), -1) .* reshape(a.deriv, sz([1 end 2:end-1])); d = reshape(sum(d, 3), sz); c = autodiff(logm(a.value), a.varind, d); end % Reduction methods: Sum, prod, min, max function c = sum(a, dim, flag) assert(nargin < 3 || strcmp(flag, 'default'), 'Only default option supported'); if nargin < 2 dim = first_nonsingleton_dim(a); end c = autodiff(sum(a.value, dim), a.varind, sum(a.deriv, dim+1)); end function c = prod(a, dim) if nargin < 2 dim = first_nonsingleton_dim(a); end c = a.value; c(c==0) = 1e-154; c = autodiff(prod(a.value, dim), a.varind, sum(a.deriv .* shiftdim(prod(c, dim) .* (1 ./ c), -1), dim+1)); end function c = select(a, b, M) da = double(a); db = double(b); v = combine_varind(a, b); ga = grad(a, v); gb = grad(b, v); if isscalar(a) M = ~M; db(M) = da; gb(:,M) = repmat(ga, [1 sum(M(:))]); c = autodiff(db, v, gb); elseif isscalar(b) da(M) = db; ga(:,M) = repmat(gb, [1 sum(M(:))]); c = autodiff(da, v, ga); else da(M) = db(M); ga(:,M) = gb(:,M); c = autodiff(da, v, ga); end end function [c, d] = min(a, b, dim) if nargin > 1 && ~isempty(b) d = double(a) > double(b); c = select(a, b, d); else if nargin < 3 dim = first_nonsingleton_dim(a); end [c, d] = min(a.value, [], dim); c = autodiff(c, var_indices(a), dimsel(a.deriv, d, dim)); end end function [c, d] = max(a, b, dim) if nargin > 1 && ~isempty(b) d = double(a) < double(b); c = select(a, b, d); else if nargin < 3 dim = first_nonsingleton_dim(a); end [c, d] = max(a.value, [], dim); c = autodiff(c, var_indices(a), dimsel(a.deriv, d, dim)); end end % Logical operators function c = lt(a, b) c = lt(double(a), double(b)); end function c = le(a, b) c = le(double(a), double(b)); end function c = gt(a, b) c = gt(double(a), double(b)); end function c = ge(a, b) c = ge(double(a), double(b)); end function c = eq(a, b) c = eq(double(a), double(b)); end function c = ne(a, b) c = ne(double(a), double(b)); end % Access functions function c = end(a, k, n) if k < n c = size(a.value, k); else sz = size(a.value); if numel(sz) < k c = 1; else c = prod(sz(k:end)); end end end function c = subsref(a, s) assert(strcmp(s.type, '()')); c = a.value(s.subs{:}); c = autodiff(c, a.varind, reshape(a.deriv(:,s.subs{:}), [size(a.deriv, 1) size(c)])); end function c = subsasgn(a, s, b) assert(strcmp(s.type, '()')); c = double(a); c(s.subs{:}) = double(b); v = combine_varind(a, b); d = grad(a, v); s_ = [{':'} s.subs]; d_ = grad(b, v); if isscalar(b) d_ = repmat(d_, [1 size(c(s.subs{:}))]); end d(s_{:}) = d_; c = autodiff(c, v, d); end % Array concatenation function c = cat(dim, varargin) c = cellfun(@double, varargin, 'Uniform', false); v = combine_varind(varargin{:}); d = cellfun(@(x) grad(x, v), varargin, 'Uniform', false); c = autodiff(cat(dim, c{:}), v, cat(dim+1, d{:})); end function c = horzcat(varargin) c = cat(2, varargin{:}); end function c = vertcat(varargin) c = cat(1, varargin{:}); end function c = repmat(a, varargin) c = autodiff(repmat(a.value, varargin{:}), a.varind, repmat(a.deriv, cat(2, 1, varargin{:}))); end % Transpose, permute, reshape, shiftdim etc. function c = ctranspose(a) c = permute(conj(a), [2 1]); end function c = transpose(a) c = permute(a, [2 1]); end function c = permute(a, order) c = autodiff(permute(a.value, order), a.varind, permute(a.deriv, [1 order+1])); end function c = ipermute(a, order) order(order) = 1:numel(order); c = permute(a, order); end function c = reshape(a, varargin) if nargin == 2 && isnumeric(varargin{1}) c = autodiff(reshape(a.value, varargin{1}), a.varind, reshape(a.deriv, [size(a.deriv, 1) varargin{1}])); else c = autodiff(reshape(a.value, varargin{:}), a.varind, reshape(a.deriv, size(a.deriv, 1), varargin{:})); end end function c = shiftdim(a, n) if (n > 0) m = ndims(a.value); n = rem(n, m); c = permute(a, [n+1:m, 1:n]); else c = reshape(a, [ones(1, -n), size(a.value)]); end end % Size and is* function varargout = size(a, varargin) [varargout{1:nargout}] = size(a.value, varargin{:}); end function c = length(a) if isempty(a) c = 0; else c = max(size(a)); end end function c = ndims(a) c = ndims(a.value); end function c = numel(a) c = numel(a.value); end function c = isautodiff(a) c = true; end function c = isfloat(a) c = isfloat(a.value); end function c = isempty(a) c = isempty(a.value); end function c = isscalar(a) c = isscalar(a.value); end function c = isreal(a) c = isreal(a.value) & isreal(a.deriv); end function c = isnan(a) c = isnan(a.value) | shiftdim(any(isnan(a.deriv)), 1); end function c = isfinite(a) c = isfinite(a.value) & shiftdim(all(isfinite(a.deriv)), 1); end % Other functions function c = ojw_interp2(I, x, y, varargin) if isautodiff(x) && isautodiff(y) && ~isautodiff(I) [c, d] = ojw_interp2(I, x.value, y.value, varargin{:}); c = autodiff(c, x.varind, x.deriv .* d(1,:,:,:) + y.deriv .* d(2,:,:,:)); elseif isautodiff(I) && ~isautodiff(x) && ~isautodiff(y) [h, w, n] = size(I.value); sz = size(I.value); [sz(1), sz(2)] = size(x); c = [shiftdim(I.value, -1); I.grad]; c = reshape(reshape(c, size(c, 1), numel(I.value))', h, w, []); c = ojw_interp2(c, x, y, varargin{:}); c = reshape(c, size(c, 1), size(c, 2), n, numel(I.varind)+1); c = autodiff(reshape(c(:,:,:,1), sz), I.varind, reshape(permute(c(:,:,:,2:end), [4 1 2 3]), [numel(I.varind) sz])); else error('Unexpected variables'); end end % Alternative method avoids a subsref of autodiff variables (for % speed) function c = ojw_interp2_alt(I, x, varargin) if isautodiff(x) && ~isautodiff(I) [c, d] = ojw_interp2(I, x.value(:,:,1), x.value(:,:,2), varargin{:}); c = autodiff(c, x.varind, x.deriv(:,:,:,1) .* d(1,:,:,:) + x.deriv(:,:,:,2) .* d(2,:,:,:)); else error('Unexpected variables'); end end function c = expm_srt_3d(dP) dP.value(1:3,:) = dP.value(1:3,:) * sqrt(2); dP.deriv(:,1:3,:) = dP.deriv(:,1:3,:) * sqrt(2); switch size(dP, 1) case 3 type = 'so3'; case 6 type = 'se3'; dP = autodiff(dP.value([4:6 1:3],:), dP.varind, dP.deriv(:,[4:6 1:3],:)); case 7 type = 'sim3'; dP.value(7,:) = dP.value(7,:) * sqrt(3); dP.deriv(:,7,:) = dP.deriv(:,7,:) * sqrt(3); dP = autodiff(dP.value([4:6 1:3 7],:), dP.varind, dP.deriv(:,[4:6 1:3 7],:)); otherwise error('Size of dP not recognized'); end c = exp(lie(type), dP); c = autodiff(c.value(1:3,:,:), c.varind, c.deriv(:,1:3,:,:)); end function c = conv2(varargin) % Get the shape if ischar(varargin{end}) shape = varargin{end}; varargin = varargin(1:end-1); else shape = 'full'; end v = combine_varind(varargin{:}); n = numel(v); c = double(varargin{end}); if isautodiff(varargin{end}) d = permute(grad(varargin{end}, v), [2 3 1]); else d = []; end if numel(varargin) == 3 varargin{1} = reshape(varargin{1}, [], 1); varargin{2} = reshape(varargin{2}, 1, []); conv2_ = @(A, B) conv2(B, A, shape); else conv2_ = @(A, B) conv2(A, B, shape); end for a = 1:numel(varargin)-1 ca = double(varargin{a}); if ~isempty(d) for b = n:-1:1 d_(:,:,b) = conv2_(ca, d(:,:,b)); end d = d_; clear d_ end if isautodiff(varargin{a}) da = permute(grad(varargin{a}, v), [2 3 1]); for b = n:-1:1 d_(:,:,b) = conv2_(da(:,:,b), c); end if isempty(d) d = d_; else d = d + d_; end clear d_ end c = conv2_(ca, c); end d = permute(d, [3 1 2]); c = autodiff(c, v, d); end function a = homg(a) a.value(end+1,:) = 1; a.deriv(:,end+1,:) = 0; end function [c, z] = proj(a) sz = size(a.value); sz(1) = sz(1) - 1; c = a.value(1:end-1,:); z = 1 ./ a.value(end,:); c = c .* z; z = shiftdim(z, -1); dz = -z .* a.deriv(:,end,:); d = a.deriv(:,1:end-1,:) .* z + shiftdim(c, -1) .* dz; c = autodiff(reshape(c, sz), a.varind, reshape(d, [size(d, 1) sz])); if nargout > 1 sz(1) = 1; dz = dz .* z; z = autodiff(reshape(z, sz), a.varind, reshape(dz, [size(dz, 1) sz])); end end % Debug function check_size(a) sz1 = size(a.value); sz2 = size(a.deriv); if numel(sz2) == 2 sz2(3) = 1; end assert(isequal(sz1, sz2(2:end)), 'Unexpected array sizes. Value: [%s]. Derivative: [%s].\n', sprintf('%d ', sz1), sprintf('%d ', sz2)); end end end % Helpers function dim = first_nonsingleton_dim(a, b) sza = size(a); if nargin > 1 szb = size(b); sza(end+1:numel(szb)) = 1; szb(end+1:numel(sza)) = 1; sza = min(sza, szb); end dim = find(sza > 1, 1, 'first'); if isempty(dim) dim = 1; end end function g = expand_array(ga, va, v, fill) [l, l] = ismember(va, v); sz = size(ga); sz(1) = numel(v); g = repmat(fill, sz); g(l,:) = ga(:,:); end function [c, v] = add_grads(ga, gb, va, vb, sz) if isempty(va) sz2 = size(gb); sz = [sz2(1) sz]; sz2(end+1:numel(sz)) = 1; sz2 = max(sz2, 1); c = repmat(gb, sz ./ sz2); v = vb; return; end if isempty(vb) sz2 = size(ga); sz = [sz2(1) sz]; sz2(end+1:numel(sz)) = 1; sz2 = max(sz2, 1); c = repmat(ga, sz ./ sz2); v = va; return; end n = numel(va); if (n == vb(end) && n == numel(vb) && n == va(end)) || isequal(va, vb) c = ga + gb; v = va; return; end v = combine_varind_({va, vb}); c = expand_array(ga, va, v, 0) + expand_array(gb, vb, v, 0); end function A = dimsel(A, I, dim) % Construct the index array szA = size(A); szI = size(I); stride = cumprod([1 szA(2:end)]); if stride(dim+1) == stride(end) I = I(:) * stride(dim) + (1-stride(dim):0)'; elseif stride(dim) == 1 I = I(:) + (0:stride(dim+1):stride(end)-1)'; else I = I(:) * stride(dim) + reshape((1-stride(dim):0)' + (0:stride(dim+1):stride(end)-1), [], 1); end % Construct the output A = reshape(A(:,I), [szA(1) szI]); end function v = combine_varind(varargin) v = combine_varind_(cellfun(@var_indices, varargin, 'UniformOutput', false)); end function v = combine_varind_(varinds) varinds = varinds(~cellfun(@isempty, varinds)); [n, m] = max(cellfun(@(c) c(end), varinds)); if numel(varinds) == 1 || numel(varinds{m}) == n v = varinds{m}; return; end v = false(1, n); v([varinds{:}]) = true; v = find(v); end
github
ojwoodford/ojwul-master
ojw_interp2_alt.m
.m
ojwul-master/autodiff/ojw_interp2_alt.m
850
utf_8
d8690ddac7c190d31d55d7348871f54d
%OJW_INTERP2_ALT Fast 2d interpolation for images % % V = ojw_interp2_alt(A, X) % V = ojw_interp2_alt(A, X, interp_mode) % V = ojw_interp2_alt(A, X, interp_mode, oobv) % % Wrapper to ojw_interp2 which has horizontal and vertical coordinates % concatenated along the third dimension into one array. % %IN: % A - HxWxC double, single, uint16, int16, uint8, int8 or Logical array. % X - MxNx2 sample coordinates (1,1 being the centre of the top left % pixel). % interp_mode - string, either 'nearest', 'linear', 'cubic', 'magic', % '3lanczos', or '5lanczos'. Default: 'linear'. % oobv - 1x1 Out of bounds value. Default: NaN. % %OUT: % V - MxNxC interpolated values. Class is the same as that of oobv. function varargout = ojw_interp2_alt(A, X, varargin) [varargout{1:nargout}] = ojw_interp2(A, X(:,:,1), X(:,:,2), varargin{:}); end
github
ojwoodford/ojwul-master
grad.m
.m
ojwul-master/autodiff/grad.m
221
utf_8
401e020bd53921b653fe42f0dc0629b9
%GRAD Dummy helper function for autodiff function c = grad(a, vars) if nargin < 2 c = 0; elseif isscalar(vars) && vars < 0 c = sparse(-vars, numel(a)); else c = zeros([numel(vars) size(a)]); end end
github
ojwoodford/ojwul-master
refine_subpixel.m
.m
ojwul-master/features/refine_subpixel.m
1,323
utf_8
2fb324b22128ffd02507ef1746c82bb5
%REFINE_SUBPIXEL N-dimensional sub-pixel refinement % % [offset, val] = refine_subpixel(A, M) % % Computes the offsets and values of the refined positions of maxima/minima % in an N-dimensional array, by fitting a quadratic around the points. % %IN: % A - An N-dimensional array of size sz. % M - A binary mask of size sz indicating which points in the array are % to be refined, or a 1xL list of the indices of such points. % %OUT: % offset - NxL array of offset positions of the estimated true % maximum/minimum from the integer position. % val - 1xL estimated values at the subpixel maxima/minima. function [offset, val] = refine_subpixel(V, c) % Compute the indices if islogical(c) c = find(c); end c = reshape(c, 1, []); % Compute some dimension values sz = cumprod(size(V)); sz = [1 sz(1:end-1)]'; % Compute the Jacobian (central differences along each dimension) Vp = V(bsxfun(@plus, c, sz)); Vn = V(bsxfun(@minus, c, sz)); J = 0.5 * (Vp - Vn); % Compute the Hessian (no skew though, to ensure positive semi-definite) Vc = V(c); H = Vp + Vn - 2 * Vc; % Compute the offsets and values offset = -J ./ H; if nargout > 1 val = col(Vc, 2) + dot(J, offset); end offset(:,any(abs(offset) >= 1)) = 0; %assert(all(abs(offset(:)) < 1)); end
github
ojwoodford/ojwul-master
fast_corners.m
.m
ojwul-master/features/fast_corners.m
892
utf_8
51b22d38c75dfc9d3eeca1cd61e2fae2
%FAST_CORNERS Call mexed FAST corner detector % % [XY, scores] = fast_corners(I, thresh, type) % % FAST corner detection using Ed Rosten's C implementation. Method % published in: % "Machine learning for high-speed corner detection", % E. Rosten & T. Drummond, ECCV 2006. % %IN: % I - HxW uint8 grayscale image. % thresh - scalar integer threshold for nonmax-suppression. % type - {9,10,11,12} type of corner detector to use. % %OUT: % XY - 2xN uint16 array of x,y coordinates of corners. % score - 1xN uint16 array corner scores. function varargout = fast_corners(varargin) sd = 'private/fast/'; sourceList = {[sd 'fast_mex.c'], [sd 'fast_9.c'], [sd 'fast_10.c'], [sd 'fast_11.c'], ... [sd 'fast_12.c'], [sd 'nonmax.c'], [sd 'fast.c']}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here end
github
ojwoodford/ojwul-master
extract_features.m
.m
ojwul-master/features/extract_features.m
1,610
utf_8
5e25a2a041b3867b15db27af4864c6bb
%EXTRACT_FEATURES Extract interest points from a detector score image % % [X, s] = extract_features(score, [radius, [thresh, [subpixel]]]) % % Finds the local maxima in the input detector score image. % %IN: % score - HxW interest point detector score. % radius - Scalar indicating the radius of non-maxima suppression to % apply. Default: 1.5. % thresh - Threshold on corner suppression. If negative, magnitude is % interpreted as the proportion of strongest corners to keep. % Default: -0.5, i.e. keep top 50% of corners. % subpixel - Boolean indicating whether subpixel refinement is wanted. % Default: true. % %OUT: % X - 2xN matrix of interest point locations. % s - 1xN vector of interest point scores. function [X, score] = extract_features(score, radius, thresh, subpixel) % Set the default values if nargin < 4 subpixel = true; if nargin < 3 thresh = -0.5; if nargin < 2 radius = 1.5; end end end % Find the local maxima M = imnonmaxsup(score, radius); % Reject boundary maxima M([1 end],:) = false; M(:,[1 end]) = false; % Keep only those above the threshold if thresh < 0 s = sort(score(M), 'descend'); thresh = s(ceil(end*-thresh)); end M = M & score >= thresh; % Compute the indices [y, x] = find(M); X = [y(:)'; x(:)']; if subpixel % Sub-pixel refinement X = X + refine_subpixel(score, M); end % Put x coordinate first X = X([2 1],:); % Output the scores if nargout > 1 score = score(M); end end
github
ojwoodford/ojwul-master
corners.m
.m
ojwul-master/features/corners.m
1,326
utf_8
cb352371b69acdedf06ea6f61d8d00b4
%CORNERS Compute corner detector score % % score = corners(I, [sigma], method) % %IN: % I - HxWxC image % sigma - Scalar value determing the scale of the gradient filter. % Default: 1. % method - String determing the method to use: 'harris', 'noble' % or 'shi-tomasi'. Default: 'shi-tomasi'. % %OUT: % score - HxW corner detector score. function score = corners(I, varargin) % Set the default values method = 'shi-tomasi'; sigma = 1; for v = varargin(:)' if ischar(v{1}) method = v{1}; elseif isscalar(v{1}) sigma = v{1}; else error('Input argument not recognized'); end end % Compute the image gradient [Ix, Iy] = imgrad(I, 'Sobel'); % Compute 1D Gaussian filter from sigma g = max(floor((5 / 2) * sigma), 1); g = -g:g; g = gauss_mask(sigma, 0, g); % Region integration Ix2 = imfiltsep(Ix .* Ix, g', g); Iy2 = imfiltsep(Iy .* Iy, g', g); Ixy = imfiltsep(Ix .* Iy, g', g); % Compute trace and determinant of structure tensor T = Ix2 + Iy2; D = Ix2 .* Iy2 - Ixy .* Ixy; % Compute the corner score switch lower(method) case 'harris' score = D - 0.04 * T .* T; case 'noble' score = D ./ (T + 1e-300); case 'shi-tomasi' score = T - sqrt(T .* T - 2 * D); end end
github
ojwoodford/ojwul-master
dog.m
.m
ojwul-master/features/dog.m
279
utf_8
a1b8d4163884aa428f3e0c43500dd4a6
%DOG Difference of Gaussians blob detector % % features = dog(I) % %IN: % I - HxWxC image % %OUT: % features - 4xN frames of N features: [X; Y; scale; orientation]. function features = dog(I) if size(I, 3) == 3 I = rgb2gray(I); end features = vl_sift(single(I)); end
github
ojwoodford/ojwul-master
interest_point_demo.m
.m
ojwul-master/features/interest_point_demo.m
3,385
utf_8
8516f6ee54d76a2f85743454d8f59737
%INTEREST_POINT_DEMO Compute and visualize the interest points of an image % % interest_point_demo % interest_point_demo(A, [scale, [thresh, [detector]]]) % %IN: % A - HxWxC image. Default: Use peppers.png % scale - scale of the interest points to be detected (if applicable). % Default: 2. % thresh - threshold on point suppression. If negative, magnitude is % interpreted as the proportion of strongest points to keep. % Default: -0.5, i.e. keep top 50% of points. % detector - string of the detector name. Default: 'noble'. function interest_point_demo(A, detector, scale, thresh) % Set default arguments if nargin < 4 thresh = -0.5; % Negative numbers indicate ratio of edges to keep if nargin < 3 scale = 2; if nargin < 2 detector = 'noble'; if nargin < 1 A = imread('peppers.png'); end end end end switch lower(detector) case {'harris', 'noble', 'shi-tomasi'} % Compute the detector score image tic(); score = corners(A, scale, detector); t1 = toc(); % Compute the interest points tic(); X = extract_features(score, 1.5, thresh, true); t2 = toc(); % Visualization fprintf('Computing corner detector score: %gs\nExtracting interest points: %gs\n', t1, t2); clf; % Render the score over the image sc(cat(3, score, A), 'prob'); % Render the interest points hold on plot(X(1,:), X(2,:), 'y.', 'MarkerSize', 10); hold off case 'fast' % Compute the detector score image if size(A, 3) == 3 A = rgb2gray(A); end scale = max(min(round(scale), 12), 9); tic(); [X, score] = fast_corners(A, max(thresh, 1), scale); t1 = toc(); fprintf('Extracting interest points: %gs\n', t1); % Keep only those above the threshold if thresh < 0 tic(); s = sort(score, 'descend'); thresh = s(ceil(end*-thresh)); M = score >= thresh; score = score(M); X = X(:,M); t1 = toc(); fprintf('Selecting interest points: %gs\n', t1); end % Visualization clf; % Render the image sc(A); % Render the interest points m = max(score); C = parula(m); hold on I = accumarray(score', (1:numel(score))', [m 1], @(I) {I}); hold on for a = 1:m if isempty(I{a}) continue; end plot(col(X(1,I{a})), col(X(2,I{a})), 'b.', 'Color', C(a,:), 'MarkerSize', 10); end hold off case 'dog' % Compute the detector score image tic(); features = dog(A); t1 = toc(); % Visualization fprintf('Detecting DoG features: %gs\n', t1); clf; % Show the image imdisp(A); % Render the interest points hold on render_circles(features(1:3,:), 64, [1 0 0]); hold off otherwise error('Detector method %s not recognized', detector); end end
github
ojwoodford/ojwul-master
vl_dsift.m
.m
ojwul-master/features/vlfeat/vl_dsift.m
5,724
utf_8
a5e67611f562f0b69ababcc52b234260
% VL_DSIFT Dense SIFT % [FRAMES,DESCRS] = VL_DSIFT(I) extracts a dense set of SIFT % keypoints from image I. I must be of class SINGLE and grayscale. % FRAMES is a 2 x NUMKEYPOINTS, each colum storing the center (X,Y) % of a keypoint frame (all frames have the same scale and % orientation). DESCRS is a 128 x NUMKEYPOINTS matrix with one % descriptor per column, in the same format of VL_SIFT(). % % VL_DSIFT() does NOT compute a Gaussian scale space of the image % I. Instead, the image should be pre-smoothed at the desired scale % level, e.b. by using the VL_IMSMOOTH() function. % % The scale of the extracted descriptors is controlled by the option % SIZE, i.e. the width in pixels of a spatial bin (recall that a % SIFT descriptor is a spatial histogram with 4 x 4 bins). % % The sampling density is controlled by the option STEP, which is % the horizontal and vertical displacement of each feature cetner to % the next. % % The sampled image area is controlled by the option BOUNDS, % defining a rectangle in which features are comptued. A descriptor % is included in the rectangle if all the centers of the spatial % bins are included. The upper-left descriptor is placed so that the % uppler-left spatial bin center is algined with the upper-left % corner of the rectangle. % % By default, VL_DSIFT() computes features equivalent to % VL_SIFT(). However, the FAST option can be used to turn on an % variant of the descriptor (see VLFeat C API documentation for % further details) which, while not strictly equivalent, it is much % faster. % % VL_DSIFT() accepts the following options: % % Step:: 1 % Extracts a SIFT descriptor each STEP pixels. % % Size:: 3 % A spatial bin covers SIZE pixels. % % Bounds:: [whole image] % Specifies a rectangular area where descriptors should be % extracted. The format is [XMIN, YMIN, XMAX, YMAX]. If this % option is not specified, the entiere image is used. The % bounding box is clipped to the image boundaries. % % Norm:: % If specified, adds to the FRAMES ouptut argument a third % row containint the descriptor norm, or engergy, before % contrast normalization. This information can be used to % suppress low contrast descriptors. % % Fast:: % If specified, use a piecewise-flat, rather than Gaussian, % windowing function. While this breaks exact SIFT equivalence, % in practice is much faster to compute. % % FloatDescriptors:: % If specified, the descriptor are returned in floating point % rather than integer format. % % Verbose:: % If specified, be verbose. % % RELATION TO THE SIFT DETECTOR % % In the standard SIFT detector/descriptor, implemented by % VL_SIFT(), the size of a spatial bin is related to the keypoint % scale by a multiplier, called magnification factor, and denoted % MAGNIF. Therefore, the keypoint scale corresponding to the % descriptors extracted by VL_DSIFT() is equal to SIZE / % MAGNIF. VL_DSIFT() does not use MAGNIF because, by using dense % sampling, it avoids detecting keypoints in the first plance. % % VL_DSIFT() does not smooth the image as SIFT does. Therefore, in % order to obtain equivalent results, the image should be % pre-smoothed approriately. Recall that in SIFT, for a keypoint of % scale S, the image is pre-smoothed by a Gaussian of variance S.^2 % - 1/4 (see VL_SIFT() and VLFeat C API documentation). % % Example:: % This example produces equivalent SIFT descriptors using % VL_DSIFT() and VL_SIFT(): % % binSize = 8 ; % magnif = 3 ; % Is = vl_imsmooth(I, sqrt((binSize/magnif)^2 - .25)) ; % % [f, d] = vl_dsift(Is, 'size', binSize) ; % f(3,:) = binSize/magnif ; % f(4,:) = 0 ; % [f_, d_] = vl_sift(I, 'frames', f) ; % % Remark:: % The equivalence is never exact due to (i) boundary effects % and (ii) the fact that VL_SIFT() downsamples the image to save % computation. It is, however, usually very good. % % Remark:: % In categorization it is often useful to under-smooth the image, % comared to standard SIFT, in order to keep the gradients % sharp. % % FURTHER DETAILS ON THE GEOMETRY % % As mentioned, the VL_DSIFT() descriptors cover the bounding box % specified by BOUNDS = [XMIN YMIN XMAX YMAX]. Thus the top-left bin % of the top-left descriptor is placed at (XMIN, YMIN). The next % three bins to the right are at XMIN + SIZE, XMIN + 2*SIZE, XMIN + % 3*SIZE. The X coordiante of the center of the first descriptor is % therefore at (XMIN + XMIN + 3*SIZE) / 2 = XMIN + 3/2 * SIZE. For % instance, if XMIN = 1 and SIZE = 3 (default values), the X % coordinate of the center of the first descriptor is at 1 + 3/2 * 3 % = 5.5. For the second descriptor immediately to its right this is % 5.5 + STEP, and so on. % % See also:: VL_HELP(), VL_SIFT(). % AUTORIGHTS % Copyright (C) 2007-10 Andrea Vedaldi and Brian Fulkerson % % This file is part of VLFeat, available under the terms of the % GNU GPLv2, or (at your option) any later version. function varargout = vl_dsift(varargin) base = '../private/vlfeat'; if ismember(computer('arch'), {'maca64'}) sourceList = {['-I' base], 'vl_dsift.c', [base '/vl/dsift.c'], [base '/vl/generic.c'], [base '/vl/host.c'], [base '/vl/imopv.c'], [base '/vl/random.c']}; % Cell array of source files else sourceList = {['-I' base], '-D__SSE2__', 'vl_dsift.c', [base '/vl/dsift.c'], [base '/vl/generic.c'], [base '/vl/host.c'], [base '/vl/imopv.c'], [base '/vl/imopv_sse2.c'], [base '/vl/random.c']}; % Cell array of source files end [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return
github
ojwoodford/ojwul-master
vl_ubcmatch.m
.m
ojwul-master/features/vlfeat/vl_ubcmatch.m
1,416
utf_8
9fa45a4773984b53f3103700b3b9b2e0
% VL_UBCMATCH Match SIFT features % MATCHES = VL_UBCMATCH(DESCR1, DESCR2) matches the two sets of SIFT % descriptors DESCR1 and DESCR2. % % [MATCHES,SCORES] = VL_UBCMATCH(DESCR1, DESCR2) retuns the matches and % also the squared Euclidean distance between the matches. % % The function uses the algorithm suggested by D. Lowe [1] to reject % matches that are too ambiguous. % % VL_UBCMATCH(DESCR1, DESCR2, THRESH) uses the specified threshold % THRESH. A descriptor D1 is matched to a descriptor D2 only if the % distance d(D1,D2) multiplied by THRESH is not greater than the % distance of D1 to all other descriptors. The default value of % THRESH is 1.5. % % The storage class of the descriptors can be either DOUBLE, FLOAT, % INT8 or UINT8. Usually integer classes are faster. % % REFERENCES % % [1] D. G. Lowe, Distinctive image features from scale-invariant % keypoints. IJCV, vol. 2, no. 60, pp. 91-110, 2004. % % See also VL_HELP(), VL_SIFT(). % AUTORIGHTS % Copyright (C) 2007-10 Andrea Vedaldi and Brian Fulkerson % % This file is part of VLFeat, available under the terms of the % GNU GPLv2, or (at your option) any later version. function varargout = vl_ubcmatch(varargin) base = '../private/vlfeat'; sourceList = {['-I' base], 'vl_ubcmatch.c'}; % Cell array of source files [varargout{1:nargout}] = compile(varargin{:}); % Compilation happens here return