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
jacksky64/imageProcessing-master
filter_gauss_1D.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/filter_gauss_1D.m
1,137
utf_8
94a453b82dcdeba67bd886e042d552d9
% 1D Gaussian filter. % % Equivalent to (but faster then): % f = fspecial('Gaussian',[2*r+1,1],sigma); % f = filter_gauss_nD( 2*r+1, r+1, sigma^2 ); % % USAGE % f = filter_gauss_1D( r, sigma, [show] ) % % INPUTS % r - filter size=2r+1, if r=[] -> r=ceil(2.25*sigma) % sigma - standard deviation of filter % show - [0] figure to use for optional display % % OUTPUTS % f - 1D Gaussian filter % % EXAMPLE % f1 = filter_gauss_1D( 10, 2, 1 ); % f2 = filter_gauss_nD( 21, [], 2^2, 2); % % See also FILTER_BINOMIAL_1D, FILTER_GAUSS_ND, FSPECIAL % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function f = filter_gauss_1D( r, sigma, show ) if( nargin<3 || isempty(show) ); show=0; end if( isempty(r) ); r = ceil(sigma*2.25); end if( mod(r,1)~=0 ); error( 'r must be an integer'); end % compute filter x = -r:r; f = exp(-(x.*x)/(2*sigma*sigma))'; f(f<eps*max(f(:))*10) = 0; sumf = sum(f(:)); if(sumf~=0); f = f/sumf; end % display if(show); filter_visualize_1D( f, show ); end
github
jacksky64/imageProcessing-master
clfEcoc.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/clfEcoc.m
1,493
utf_8
e77e1b4fd5469ed39f47dd6ed15f130f
function clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets) % Wrapper for ecoc that makes ecoc compatible with nfoldxval. % % Requires the SVM toolbox by Anton Schwaighofer. % % USAGE % clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets) % % INPUTS % p - data dimension % clfInit - binary classifier init (see nfoldxval) % clfparams - binary classifier parameters (see nfoldxval) % nclasses - num of classes (currently 3<=nclasses<=7 suppored) % use01targets - see ecoc % % OUTPUTS % clf - see ecoc % % EXAMPLE % % See also ECOC, NFOLDXVAL, CLFECOCCODE % % Piotr's Image&Video Toolbox Version 2.0 % Copyright 2008 Piotr Dollar. [pdollar-at-caltech.edu] % Please email me if you find bugs, or have suggestions or questions! % Licensed under the Lesser GPL [see external/lgpl.txt] if( nclasses<3 || nclasses>7 ) error( 'currently only works if 3<=nclasses<=7'); end; if( nargin<5 || isempty(use01targets)); use01targets=0; end; % create code (limited for now) [C,nbits] = clfEcocCode( nclasses ); clf = ecoc(nclasses, nbits, C, use01targets ); % didn't use to pass use01? clf.verbosity = 0; % don't diplay output % initialize and temporarily store binary learner clf.templearner = feval( clfInit, p, clfparams{:} ); % ecoctrain2 is custom version of ecoctrain clf.funTrain = @clfEcocTrain; clf.funFwd = @ecocfwd; function clf = clfEcocTrain( clf, varargin ) clf = ecoctrain( clf, clf.templearner, varargin{:} );
github
jacksky64/imageProcessing-master
getargs.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/getargs.m
3,455
utf_8
de2bab917fa6b9ba3099f1c6b6d68cf0
% Utility to process parameter name/value pairs. % % DEPRECATED -- ONLY USED BY KMEANS2? SHOULD BE REMOVED. % USE GETPARAMDEFAULTS INSTEAD. % % Based on code fromt Matlab Statistics Toolobox's "private/statgetargs.m" % % [EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...) % accepts a cell array PNAMES of valid parameter names, a cell array DFLTS % of default values for the parameters named in PNAMES, and additional % parameter name/value pairs. Returns parameter values A,B,... in the same % order as the names in PNAMES. Outputs corresponding to entries in PNAMES % that are not specified in the name/value pairs are set to the % corresponding value from DFLTS. If nargout is equal to length(PNAMES)+1, % then unrecognized name/value pairs are an error. If nargout is equal to % length(PNAMES)+2, then all unrecognized name/value pairs are returned in % a single cell array following any other outputs. % % EMSG is empty if the arguments are valid, or the text of an error message % if an error occurs. GETARGS does not actually throw any errors, but % rather returns an error message so that the caller may throw the error. % Outputs will be partially processed after an error occurs. % % USAGE % [emsg,varargout]=getargs(pnames,dflts,varargin) % % INPUTS % pnames - cell of valid parameter names % dflts - cell of default parameter values % varargin - list of proposed name / value pairs % % OUTPUTS % emsg - error msg - '' if no error % varargout - list of assigned name / value pairs % % EXAMPLE % pnames = {'color' 'linestyle', 'linewidth'}; dflts = { 'r','_','1'}; % v = {'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'}; % [emsg,color,linestyle,linewidth,unrec] = getargs(pnames,dflts,v{:}) % ok % [emsg,color,linestyle,linewidth] = getargs(pnames,dflts,v{:}) % err % % See also GETPARAMDEFAULTS % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function [emsg,varargout]=getargs(pnames,dflts,varargin) wid = sprintf('Images:%s:obsoleteFunction',mfilename); warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n It will be ' ... 'removed in the next version of the toolbox.'],upper(mfilename)); % We always create (nparams+1) outputs: % one for emsg % nparams varargs for values corresponding to names in pnames % If they ask for one more (nargout == nparams+2), it's for unrecognized % names/values emsg = ''; nparams = length(pnames); varargout = dflts; unrecog = {}; nargs = length(varargin); % Must have name/value pairs if mod(nargs,2)~=0 emsg = sprintf('Wrong number of arguments.'); else % Process name/value pairs for j=1:2:nargs pname = varargin{j}; if ~ischar(pname) emsg = sprintf('Parameter name must be text.'); break; end i = strmatch(lower(pname),lower(pnames)); if isempty(i) % if they've asked to get back unrecognized names/values, add this % one to the list if nargout > nparams+1 unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}}; % otherwise, it's an error else emsg = sprintf('Invalid parameter name: %s.',pname); break; end elseif length(i)>1 emsg = sprintf('Ambiguous parameter name: %s.',pname); break; else varargout{i} = varargin{j+1}; end end end varargout{nparams+1} = unrecog;
github
jacksky64/imageProcessing-master
normxcorrn_fg.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/normxcorrn_fg.m
2,699
utf_8
e65c38d97efb3a624e0fa94a97f75eb6
% Normalized n-dimensional cross-correlation with a mask. % % Similar to normxcorrn, except takes an additional argument that specifies % a figure ground mask for the T. That is T_fg must be of the same % dimensions as T, with each entry being 0 or 1, where zero specifies % regions to ignore (the ground) and 1 specifies interesting regions (the % figure). Essentially T_fg specifies regions in T that are interesting % and should be taken into account when doing normalized cross correlation. % This allows for templates of arbitrary shape, and not just squares. % % Note: this function is approximately 3 times slower then normxcorr2 % because it cannot use the trick of precomputing sums. % % USAGE % C = normxcorrn_fg( T, T_fg, A, [shape] ) % % INPUTS % T - template to correlate to each window in A % T_fg - figure/ground mask for the template % A - matrix to correlate T to % shape - ['full'] 'valid', 'full', or 'same', see convn_fast help % % OUTPUTS % C - correlation matrix % % EXAMPLE % A=rand(50); B=rand(11); Bfg=ones(11); % C1=normxcorrn_fg(B,Bfg,A); C2=normxcorr2(B,A); % figure(1); im(C1); figure(2); im(C2); % figure(3); im(abs(C1-C2)); % % See also NORMXCORRN % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function C = normxcorrn_fg( T, T_fg, A, shape ) if( nargin <4 || isempty(shape)); shape='full'; end; if( ndims(T)~=ndims(A) || ndims(T)~=ndims(T_fg) ) error('TEMPALTE, T_fg, and A must have same number of dimensions'); end; if( any(size(T)~=size(T_fg))) error('TEMPALTE and T_fg must have same dimensions'); end; if( ~all(T_fg==0 | T_fg==1)) error('T_fg may have only entries either 0 or 1'); end; nkeep = sum(T_fg(:)); if( nkeep==0); error('T_fg must have some nonzero values'); end; % center T on 0 and normalize magnitued to 1, excluding ground % T= (T-T_av) / ||(T-T_av)|| T(T_fg==0)=0; T = T - sum(T(:)) / nkeep; T(T_fg==0)=0; T = T / norm( T(:) ); % flip for convn_fast purposes for d=1:ndims(T); T = flipdim(T,d); end; for d=1:ndims(T_fg); T_fg = flipdim(T_fg,d); end; % get average over each window over A A_av = convn_fast( A, T_fg/nkeep, shape ); % get magnitude over each window over A "mag(WA-WAav)" % We can rewrite the above as "sqrt(SUM(WAi^2)-n*WAav^2)". so: A_mag = convn_fast( A.*A, T_fg, shape ) - nkeep * A_av .* A_av; A_mag = sqrt(A_mag); A_mag(A_mag<.000001)=1; %removes divide by 0 error % finally get C. in each image window, we will now do: % "dot(T,(WA-WAav)) / mag(WA-WAav)" C = convn_fast(A,T,shape) - A_av*sum(T(:)); C = C ./ A_mag;
github
jacksky64/imageProcessing-master
makemovie.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/makemovie.m
1,266
utf_8
9a03d9a5227c4eaa86520f206ce283e7
% [3D] Used to convert a stack of T images into a movie. % % To display same data statically use montage. % % USAGE % M = makemovies( IS ) % % INPUTS % IS - MxNxT or MxNx1xT or MxNx3xT array of movies. % % OUTPUTS % M - resulting movie % % EXAMPLE % load( 'images.mat' ); % M = makemovie( videos(:,:,:,1) ); % movie( M ); % % See also MONTAGE2, MAKEMOVIES, PLAYMOVIE, CELL2ARRAY, FEVALARRAYS, % IMMOVIE, MOVIE2AVI % Piotr's Image&Video Toolbox Version NEW % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function M = makemovie( IS ) % get images format (if image stack is MxNxT convert to MxNx1xT) if (ndims(IS)==3); IS = permute(IS, [1,2,4,3] ); end siz = size(IS); nch = siz(3); nd = ndims(IS); if ( nd~=4 ); error('unsupported dimension of IS'); end if( nch~=1 && nch~=3 ); error('illegal image stack format'); end; % normalize for maximum contrast if( isa(IS,'double') ); IS = IS - min(IS(:)); IS = IS / max(IS(:)); end % make movie for i=1:siz(4) Ii=IS(:,:,:,i); if( nch==1 ); [Ii,Mi] = gray2ind( Ii ); else Mi=[]; end if i==1 M=repmat(im2frame( Ii, Mi ),[1,siz(4)]); else M(i) = im2frame( Ii, Mi ); end end
github
jacksky64/imageProcessing-master
localsum_block.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/localsum_block.m
815
utf_8
1216b03a3bd44ff1fc3256de16a2f1c6
% Calculates the sum in non-overlapping blocks of I of size dims. % % Similar to localsum except gets sum in non-overlapping windows. % Equivalent to doing localsum, and then subsampling (except more % efficient). % % USAGE % I = localsum_block( I, dims ) % % INPUTS % I - matrix to compute sum over % dims - size of volume to compute sum over % % OUTPUTS % I - resulting array % % EXAMPLE % load trees; I=ind2gray(X,map); % I2 = localsum_block( I, 11 ); % figure(1); im(I); figure(2); im(I2); % % See also LOCALSUM % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function I = localsum_block( I, dims ) I = nlfiltblock_sep( I, dims, @rnlfiltblock_sum );
github
jacksky64/imageProcessing-master
imrotate2.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/imrotate2.m
1,326
utf_8
bb2ff6c3138ce5f53154d58d7ebc4f31
% Custom version of imrotate that demonstrates use of apply_homography. % % Works exactly the same as imrotate. For usage see imrotate. % % USAGE % IR = imrotate2( I, angle, [method], [bbox] ) % % INPUTS % I - 2D image [converted to double] % angle - angle to rotate in degrees % method - ['linear'] 'nearest', 'linear', 'spline', 'cubic' % bbox - ['loose'] 'loose' or 'crop' % % OUTPUTS % IR - rotated image % % EXAMPLE % load trees; % tic; X1 = imrotate( X, 55, 'bicubic' ); toc, % tic; X2 = imrotate2( X, 55, 'bicubic' ); toc % clf; subplot(2,2,1); im(X); subplot(2,2,2); im(X1-X2); % subplot(2,2,3); im(X1); subplot(2,2,4); im(X2); % % See also IMROTATE % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function IR = imrotate2( I, angle, method, bbox ) if( ~isa( I, 'double' ) ); I = double(I); end if( nargin<3 || isempty(method)); method='linear'; end if( nargin<4 || isempty(bbox) ); bbox='loose'; end if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end % convert arguments for apply_homography angle_rads = angle /180 * pi; R = rotationMatrix( angle_rads ); H = [R [0;0]; 0 0 1]; IR = apply_homography( I, H, method, bbox );
github
jacksky64/imageProcessing-master
imSubsResize.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/imSubsResize.m
1,338
utf_8
cd7dedf790c015adfb1f2d620e9ed82f
% Resizes subs by resizVals. % % Resizes subs in subs/vals image representation by resizVals. % % This essentially replaces each sub by sub.*resizVals. The only subtlety % is that in images the leftmost sub value is .5, so for example when % resizing by a factor of 2, the first pixel is replaced by 2 pixels and so % location 1 in the original image goes to location 1.5 in the second % image, NOT 2. It may be necessary to round the values afterward. % % USAGE % subs = imSubsResize( subs, resizVals, [zeroPnt] ) % % INPUTS % subs - subscripts of point locations (n x d) % resizVals - k element vector of shrinking factors % zeroPnt - [.5] See comment above. % % OUTPUTS % subs - transformed subscripts of point locations (n x d) % % EXAMPLE % subs = imSubsResize( [1 1; 2 2], [2 2] ) % % % See also IMSUBSTOARRAY % Piotr's Image&Video Toolbox Version NEW % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function subs = imSubsResize( subs, resizVals, zeroPnt ) if( nargin<3 || isempty(zeroPnt) ); zeroPnt=.5; end [n d] = size(subs); [resizVals,er] = checkNumArgs( resizVals, [1 d], -1, 2 ); error(er); % transform subs resizVals = repmat( resizVals, [n, 1] ); subs = (subs - zeroPnt) .* resizVals + zeroPnt;
github
jacksky64/imageProcessing-master
imtranslate.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/imtranslate.m
1,183
utf_8
054727fb31c105414b655c0f938b6ced
% Translate an image to subpixel accuracy. % % Note that for subplixel accuracy cannot use nearest neighbor interp. % % USAGE % IR = imtranslate( I, dx, dy, [method], [bbox] ) % % INPUTS % I - 2D image [converted to double] % dx - x translation (right) % dy - y translation (up) % method - ['linear'] 'nearest', 'linear', 'spline', 'cubic' % bbox - ['loose'] 'loose' or 'crop' % % OUTPUTS % IR - translated image % % EXAMPLE % load trees; % XT = imtranslate(X,0,1.5,'bicubic','crop'); % figure(1); im(X,[0 255]); figure(2); im(XT,[0 255]); % % See also IMROTATE2 % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function IR = imtranslate( I, dx, dy, method, bbox ) if( ~isa( I, 'double' ) ); I = double(I); end if( nargin<4 || isempty(method)); method='linear'; end if( nargin<5 || isempty(bbox) ); bbox='loose'; end if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end % convert arguments for apply_homography H = [eye(2) [dy; dx]; 0 0 1]; IR = apply_homography( I, H, method, bbox );
github
jacksky64/imageProcessing-master
randperm2.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/randperm2.m
1,398
utf_8
5007722f3d5f5ba7c0f83f32ef8a3a2c
% Returns a random permutation of integers. % % randperm2(n) is a random permutation of the integers from 1 to n. For % example, randperm2(6) might be [2 4 5 6 1 3]. randperm2(n,k) is only % returns the first k elements of the permuation, so for example % randperm2(6) might be [2 4]. This is a faster version of randperm.m if % only need first k<<n elements of the random permutation. Also uses less % random bits (only k). Note that this is an implementation O(k), versus % the matlab implementation which is O(nlogn), however, in practice it is % often slower for k=n because it uses a loop. % % USAGE % p = randperm2( n, k ) % % INPUTS % n - permute 1:n % k - keep only first k outputs % % OUTPUTS % p - k length vector of permutations % % EXAMPLE % randperm2(10,5) % % See also RANDPERM % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function p = randperm2( n, k ) wid = sprintf('Images:%s:obsoleteFunction',mfilename); warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n RANDSAMPLE is its '... 'recommended replacement.'],upper(mfilename)); p = randsample( n, k ); %if (nargin<2); k=n; else k = min(k,n); end % p = 1:n; % for i=1:k % r = i + floor( (n-i+1)*rand ); % t = p(r); p(r) = p(i); p(i) = t; % end % p = p(1:k);
github
jacksky64/imageProcessing-master
apply_homography.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/apply_homography.m
3,582
utf_8
9c3ed72d35b1145f41114e6e6135b44f
% Applies the homography defined by H on the image I. % % Takes the center of the image as the origin, not the top left corner. % Also, the coordinate system is row/ column format, so H must be also. % % The bounding box of the image is set by the BBOX argument, a string that % can be 'loose' (default) or 'crop'. When BBOX is 'loose', IR includes the % whole transformed image, which generally is larger than I. When BBOX is % 'crop' IR is cropped to include only the central portion of the % transformed image and is the same size as I. Preserves I's type. % % USAGE % IR = apply_homography( I, H, [method], [bbox], [show] ) % % INPUTS % I - input black and white image (2D double or unint8 array) % H - 3x3 nonsingular homography matrix % method - ['linear'] for interp2 'nearest','linear','spline','cubic' % bbox - ['loose'] see above for meaning of bbox 'loose','crop') % show - [0] figure to use for optional display % % OUTPUTS % IR - result of applying H to I. % % EXAMPLE % load trees; I=X; % R = rotationMatrix( pi/4 ); T = [1; 3]; H = [R T; 0 0 1]; % IR = apply_homography( I, H, [], 'crop', 1 ); % % See also TEXTURE_MAP, IMROTATE2 % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function IR = apply_homography( I, H, method, bbox, show ) if( ndims(I)~=2 ); error('I must a MxN array'); end; if(any(size(H)~=[3 3])); error('H must be 3 by 3'); end; if(rank(H)~=3); error('H must be full rank.'); end; if( nargin<3 || isempty(method)); method='linear'; end; if( nargin<4 || isempty(bbox)); bbox='loose'; end; if( nargin<5 || isempty(show)); show=0; end; classname = class( I ); if(~strcmp(classname,'double')); I = double(I); end I = padarray(I,[3,3],eps,'both'); siz = size(I); % set origin to be center of image rstart = (-siz(1)+1)/2; rend = (siz(1)-1)/2; cstart = (-siz(2)+1)/2; cend = (siz(2)-1)/2; % If 'bbox' then get bounds of resulting image. To do this project the % original points accoring to the homography and see the bounds. Note % that since a homography maps a quadrilateral to a quadrilateral only % need to look at where the bounds of the quadrilateral are mapped to. % If 'same' then simply use the original image bounds. if (strcmp(bbox,'loose')) pr = H * [rstart rend rstart rend; cstart cstart cend cend; 1 1 1 1]; row_dest = pr(1,:) ./ pr(3,:); col_dest = pr(2,:) ./ pr(3,:); minr = floor(min(row_dest(:))); maxr = ceil(max(row_dest(:))); minc = floor(min(col_dest(:))); maxc = ceil(max(col_dest(:))); elseif (strcmp(bbox,'crop')) minr = rstart; maxr = rend; minc = cstart; maxc = cend; else error('illegal value for bbox'); end; mrows = maxr-minr+1; ncols = maxc-minc+1; % apply inverse homography on meshgrid in destination image [col_dest_grid,row_dest_grid] = meshgrid( minc:maxc, minr:maxr ); pr = inv(H) * [row_dest_grid(:)'; col_dest_grid(:)'; ones(1,mrows*ncols)]; row_sample_locs = pr(1,:) ./ pr(3,:) + (siz(1)+1)/2; row_sample_locs = reshape(row_sample_locs,mrows,ncols); col_sample_locs = pr(2,:) ./ pr(3,:) + (siz(2)+1)/2; col_sample_locs = reshape(col_sample_locs,mrows,ncols); % now texture map results IR = interp2( I, col_sample_locs, row_sample_locs, method ); IR(isnan(IR)) = 0; IR = arraycrop2dims( IR, size(IR)-6 ); %undo extra padding if(~strcmp(classname,'double')); IR=feval(classname,IR ); end % optionally show if ( show) I = arraycrop2dims( I, size(IR)-2 ); figure(show); clf; im(I); figure(show+1); clf; im(IR); end
github
jacksky64/imageProcessing-master
pca_apply.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/pca_apply.m
2,427
utf_8
0831befb6057f8502bc492227455019a
% Companion function to pca. % % Use pca to retrieve the principal components U and the mean mu from a % set fo vectors X1 via [U,mu,vars] = pca(X1). Then given a new % vector x, use y = pca_apply( x, U, mu, vars, k ) to get the first k % coefficients of x in the space spanned by the columns of U. See pca for % general information. % % This may prove useful: % siz = size(X); k = 100; % Uim = reshape( U(:,1:k), [ siz(1:end-1) k ] ); % % USAGE % [ Yk, Xhat, avsq, avsqOrig ] = pca_apply( X, U, mu, vars, k ) % % INPUTS % X - array for which to get PCA coefficients % U - [returned by pca] -- see pca % mu - [returned by pca] -- see pca % vars - [returned by pca] -- see pca % k - number of principal coordinates to approximate X with % % OUTPUTS % Yk - first k coordinates of X in column space of U % Xhat - approximation of X corresponding to Yk % avsq - measure of squared error normalized to fall between [0,1] % % EXAMPLE % % See also PCA, PCA_VISUALIZE % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function [Yk,Xhat,avsq,avsqOrig] = pca_apply(X,U,mu,vars,k) %#ok<INUSL> siz = size(X); nd = ndims(X); [N,r] = size(U); if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end inds = {':'}; inds = inds(:,ones(1,nd-1)); d= prod(siz(1:end-1)); % some error checking if(d~=N); error('incorrect size for X or U'); end if(isa(X,'uint8')); X = double(X); end if( k>r ) warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG> k=r; end % subtract mean, then flatten X Xorig = X; murep = mu( inds{:}, ones(1,siz(end))); X = X - murep; X = reshape(X, d, [] ); % Find Yk, the first k coefficients of X in the new basis k = min( r, k ); Uk = U(:,1:k); Yk = Uk' * X; % calculate Xhat - the approx of X using the first k princ components if( nargout>1 ) Xhat = Uk * Yk; Xhat = reshape( Xhat, siz ); Xhat = Xhat + murep; end % caclulate average value of (Xhat-Xorig).^2 compared to average value % of X.^2, where X is Xorig without the mean. This is equivalent to % what fraction of the variance is captured by Xhat. if( nargout>2 ) avsq = Xhat - Xorig; avsq = dot(avsq(:),avsq(:)); avsqOrig = dot(X(:),X(:)); if (nargout==3) avsq = avsq / avsqOrig; end end
github
jacksky64/imageProcessing-master
mode2.m
.m
imageProcessing-master/piotr/toolbox/external/deprecated/mode2.m
731
utf_8
5c9321ef4b610b4f4a2d43902a68838e
% Returns the mode of a vector. % % Was mode not part of Matlab before? % % USAGE % y = mode2( x ) % % INPUTS % x - vector of integers % % OUTPUTS % y - mode % % EXAMPLE % x = randint2( 1, 10, [1 3] ) % mode(x), mode2( x ) % % See also MODE % Piotr's Image&Video Toolbox Version 1.5 % Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu % Please email me if you find bugs, or have suggestions or questions! function y = mode2( x ) wid = sprintf('Images:%s:obsoleteFunction',mfilename); warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n MODE is its '... 'recommended replacement.'],upper(mfilename)); y = mode( x ); % [b,i,j] = unique(x); % [ mval, ind ] = max(hist(j,length(b))); % y = b(ind);
github
jacksky64/imageProcessing-master
savefig.m
.m
imageProcessing-master/piotr/toolbox/external/other/savefig.m
13,459
utf_8
2b8463f9b01ceb743e440d8fb5755829
function savefig(fname, varargin) % Usage: savefig(filename, fighdl, options) % % Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure. % It saves an eps of the figure and the uses Ghostscript to convert to the other formats. % The result is a cropped, clean picture. There are options for using rgb or cmyk colours, % or grayscale. You can also choose the resolution. % % The advantage of savefig is that there is very little empty space around the figure in the % resulting files, you can export to more than one format at once, and Ghostscript generates % trouble-free files. % % If you find any errors, please let me know! (peder at axensten dot se) % % filename: File name without suffix. % % fighdl: (default: gcf) Integer handle to figure. % % options: (default: '-r300', '-lossless', '-rgb') You can define your own % defaults in a global variable savefig_defaults, if you want to, i.e. % savefig_defaults= {'-r200','-gray'};. % 'eps': Output in Encapsulated Post Script (no preview yet). % 'pdf': Output in (Adobe) Portable Document Format. % 'png': Output in Portable Network Graphics. % 'jpeg': Output in Joint Photographic Experts Group format. % 'tiff': Output in Tagged Image File Format (no compression: huge files!). % '-rgb': Output in rgb colours. % '-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used). % '-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used). % '-fonts': Include fonts in eps or pdf. Includes only the subset needed. % '-lossless': Use lossless compression, works on most formats. same as '-c0', below. % '-c<float>': Set compression for non-indexed bitmaps in PDFs - % 0: lossless; 0.1: high quality; 0.5: medium; 1: high compression. % '-r<integer>': Set resolution. % '-crop': Removes points and line segments outside the viewing area -- permanently. % Only use this on figures where many points and/or line segments are outside % the area zoomed in to. This option will result in smaller vector files (has no % effect on pixel files). % '-dbg': Displays gs command line(s). % % EXAMPLE: % savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250'); % Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi, % with high quality lossy compression. % % REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop' % must be supported. I think version 7.32 or newer is ok. % % HISTORY: % Version 1.0, 2006-04-20. % Version 1.1, 2006-04-27: % - No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead! % Version 1.2, 2006-05-02: % - Added a '-dbg' option (see options, above). % - Now looks for a global variable 'savefig_defaults' (see options, above). % - More detailed Ghostscript options (user will not really notice). % - Warns when there is no device for a file-type/color-model combination. % Version 1.3, 2006-06-06: % - Added a check to see if there actually is a figure handle. % - Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too). % - Now compatible with Ghostscript 8.54, released 2006-06-01. % Version 1.4, 2006-07-20: % - Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default). % - Added an option '-hard' that don't do anti-aliasing on pixel graphics. % Version 1.5, 2006-07-27: % - Fixed a bug when calling with a figure handle argument. % Version 1.6, 2006-07-28: % - Added a crop option, see above. % Version 1.7, 2007-03-31: % - Fixed bug: calling print with invalid renderer value '-none'. % - Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things. % Version 1.8, 2008-01-03: % - Added MacIntel: 'MACI'. % - Added 64bit PC (I think, can't test it myself). % - Added option '-nointerpolate' (use it to prevent blurring of pixelated). % - Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'. % - Fixed the gs 8.57 warning on UseCIEColor (it's now set). % - Added '-gray' for pdf, but gs 8.56 or newer is needed. % - Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed. % Version 1.9, 2008-07-27: % - Added lossless compression, see option '-lossless', above. Works on most formats. % - Added lossy compression, see options '-c<float>...', above. Works on 'pdf'. % Thanks to Olly Woodford for idea and implementation! % - Removed option '-nointerpolate' -- now savefig never interpolates. % - Fixed a few small bugs and removed some mlint comments. % Version 2.0, 2008-11-07: % - Added the possibility to include fonts into eps or pdf. % % TO DO: (Need Ghostscript support for these, so don't expect anything soon...) % - svg output. % - '-cmyk' for 'jpeg' and 'png'. % - Preview in 'eps'. % - Embedded vector fonts, not bitmap, in 'eps'. % % Copyright (C) Peder Axensten (peder at axensten dot se), 2006. % KEYWORDS: eps, pdf, jpg, jpeg, png, tiff, eps2pdf, epstopdf, ghostscript % % INSPIRATION: eps2pdf (5782), eps2xxx (6858) % % REQUIREMENTS: Works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too). %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% op_dbg= false; % Default value. % Compression compr= [' -dUseFlateCompression=true -dLZWEncodePages=true -dCompatibilityLevel=1.6' ... ' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false ' ... ' -dColorImageFilter=%s -dGrayImageFilter=%s']; % Compression. lossless= sprintf (compr, '/FlateEncode', '/FlateEncode'); lossy= sprintf (compr, '/DCTEncode', '/DCTEncode' ); lossy= [lossy ' -c ".setpdfwrite << /ColorImageDict << /QFactor %g ' ... '/Blend 1 /HSample [%s] /VSample [%s] >> >> setdistillerparams"']; % Create gs command. cmdEnd= ' -sDEVICE=%s -sOutputFile="%s"'; % Essential. epsCmd= ''; epsCmd= [epsCmd ' -dSubsetFonts=true -dNOPLATFONTS']; % Future support? epsCmd= [epsCmd ' -dUseCIEColor=true -dColorConversionStrategy=/UseDeviceIndependentColor']; epsCmd= [epsCmd ' -dProcessColorModel=/%s']; % Color conversion. pdfCmd= [epsCmd ' -dAntiAliasColorImages=false' cmdEnd]; epsCmd= [epsCmd cmdEnd]; % Get file name. if((nargin < 1) || isempty(fname) || ~ischar(fname)) % Check file name. error('No file name specified.'); end [pathstr, namestr] = fileparts(fname); if(isempty(pathstr)), fname= fullfile(cd, namestr); end % Get handle. fighdl= get(0, 'CurrentFigure'); % See gcf. % Get figure handle. if((nargin >= 2) && (numel(varargin{1}) == 1) && isnumeric(varargin{1})) fighdl= varargin{1}; varargin= {varargin{2:end}}; end if(isempty(fighdl)), error('There is no figure to save!?'); end set(fighdl, 'Units', 'centimeters') % Set paper stuff. sz= get(fighdl, 'Position'); sz(1:2)= 0; set(fighdl, 'PaperUnits', 'centimeters', 'PaperSize', sz(3:4), 'PaperPosition', sz); % Set up the various devices. % Those commented out are not yet supported by gs (nor by savefig). % pdf-cmyk works due to the Matlab '-cmyk' export being carried over from eps to pdf. device.eps.rgb= sprintf(epsCmd, 'DeviceRGB', 'epswrite', [fname '.eps']); device.jpeg.rgb= sprintf(cmdEnd, 'jpeg', [fname '.jpeg']); % device.jpeg.cmyk= sprintf(cmdEnd, 'jpegcmyk', [fname '.jpeg']); device.jpeg.gray= sprintf(cmdEnd, 'jpeggray', [fname '.jpeg']); device.pdf.rgb= sprintf(pdfCmd, 'DeviceRGB', 'pdfwrite', [fname '.pdf']); device.pdf.cmyk= sprintf(pdfCmd, 'DeviceCMYK', 'pdfwrite', [fname '.pdf']); device.pdf.gray= sprintf(pdfCmd, 'DeviceGray', 'pdfwrite', [fname '.pdf']); device.png.rgb= sprintf(cmdEnd, 'png16m', [fname '.png']); % device.png.cmyk= sprintf(cmdEnd, 'png???', [fname '.png']); device.png.gray= sprintf(cmdEnd, 'pnggray', [fname '.png']); device.tiff.rgb= sprintf(cmdEnd, 'tiff24nc', [fname '.tiff']); device.tiff.cmyk= sprintf(cmdEnd, 'tiff32nc', [fname '.tiff']); device.tiff.gray= sprintf(cmdEnd, 'tiffgray', [fname '.tiff']); % Get options. global savefig_defaults; % Add global defaults. if( iscellstr(savefig_defaults)), varargin= {savefig_defaults{:}, varargin{:}}; elseif(ischar(savefig_defaults)), varargin= {savefig_defaults, varargin{:}}; end varargin= {'-r300', '-lossless', '-rgb', varargin{:}}; % Add defaults. res= ''; types= {}; fonts= 'false'; crop= false; for n= 1:length(varargin) % Read options. if(ischar(varargin{n})) switch(lower(varargin{n})) case {'eps','jpeg','pdf','png','tiff'}, types{end+1}= lower(varargin{n}); case '-rgb', color= 'rgb'; deps= {'-depsc2'}; case '-cmyk', color= 'cmyk'; deps= {'-depsc2', '-cmyk'}; case '-gray', color= 'gray'; deps= {'-deps2'}; case '-fonts', fonts= 'true'; case '-lossless', comp= 0; case '-crop', crop= true; case '-dbg', op_dbg= true; otherwise if(regexp(varargin{n}, '^\-r[0-9]+$')), res= varargin{n}; elseif(regexp(varargin{n}, '^\-c[0-9.]+$')), comp= str2double(varargin{n}(3:end)); else warning('pax:savefig:inputError', 'Unknown option in argument: ''%s''.', varargin{n}); end end else warning('pax:savefig:inputError', 'Wrong type of argument: ''%s''.', class(varargin{n})); end end types= unique(types); if(isempty(types)), error('No output format given.'); end if (comp == 0) % Lossless compression gsCompr= lossless; elseif (comp <= 0.1) % High quality lossy gsCompr= sprintf(lossy, comp, '1 1 1 1', '1 1 1 1'); else % Normal lossy gsCompr= sprintf(lossy, comp, '2 1 1 2', '2 1 1 2'); end % Generate the gs command. switch(computer) % Get gs command. case {'MAC','MACI'}, gs= '/usr/local/bin/gs'; case {'PCWIN'}, gs= 'gswin32c.exe'; case {'PCWIN64'}, gs= 'gswin64c.exe'; otherwise, gs= 'gs'; end gs= [gs ' -q -dNOPAUSE -dBATCH -dEPSCrop']; % Essential. gs= [gs ' -dPDFSETTINGS=/prepress -dEmbedAllFonts=' fonts]; % Must be first? gs= [gs ' -dUseFlateCompression=true']; % Useful stuff. gs= [gs ' -dAutoRotatePages=/None']; % Probably good. gs= [gs ' -dHaveTrueTypes']; % Probably good. gs= [gs ' ' res]; % Add resolution to cmd. if(crop && ismember(types, {'eps', 'pdf'})) % Crop the figure. fighdl= do_crop(fighdl); end % Output eps from Matlab. renderer= ['-' lower(get(fighdl, 'Renderer'))]; % Use same as in figure. if(strcmpi(renderer, '-none')), renderer= '-painters'; end % We need a valid renderer. deps = [deps '-loose']; % added by PPD seems to help w cropping in matlab 2014b :( print(fighdl, deps{:}, '-noui', renderer, res, [fname '-temp']); % Output the eps. % Convert to other formats. for n= 1:length(types) % Output them. if(isfield(device.(types{n}), color)) cmd= device.(types{n}).(color); % Colour model exists. else cmd= device.(types{n}).rgb; % Use alternative. if(~strcmp(types{n}, 'eps')) % It works anyways for eps (VERY SHAKY!). warning('pax:savefig:deviceError', ... 'No device for %s using %s. Using rgb instead.', types{n}, color); end end cmp= lossless; if (strcmp(types{n}, 'pdf')), cmp= gsCompr; end % Lossy compr only for pdf. if (strcmp(types{n}, 'eps')), cmp= ''; end % eps can't use lossless. cmd= sprintf('%s %s %s -f "%s-temp.eps"', gs, cmd, cmp, fname);% Add up. status= system(cmd); % Run Ghostscript. if (op_dbg || status), display (cmd), end end delete([fname '-temp.eps']); % Clean up. end function fig= do_crop(fig) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Remove line segments that are outside the view. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% haxes= findobj(fig, 'Type', 'axes', '-and', 'Tag', ''); for n=1:length(haxes) xl= get(haxes(n), 'XLim'); yl= get(haxes(n), 'YLim'); lines= findobj(haxes(n), 'Type', 'line'); for m=1:length(lines) x= get(lines(m), 'XData'); y= get(lines(m), 'YData'); inx= (xl(1) <= x) & (x <= xl(2)); % Within the x borders. iny= (yl(1) <= y) & (y <= yl(2)); % Within the y borders. keep= inx & iny; % Within the box. if(~strcmp(get(lines(m), 'LineStyle'), 'none')) crossx= ((x(1:end-1) < xl(1)) & (xl(1) < x(2:end))) ... % Crossing border x1. | ((x(1:end-1) < xl(2)) & (xl(2) < x(2:end))) ... % Crossing border x2. | ((x(1:end-1) > xl(1)) & (xl(1) > x(2:end))) ... % Crossing border x1. | ((x(1:end-1) > xl(2)) & (xl(2) > x(2:end))); % Crossing border x2. crossy= ((y(1:end-1) < yl(1)) & (yl(1) < y(2:end))) ... % Crossing border y1. | ((y(1:end-1) < yl(2)) & (yl(2) < y(2:end))) ... % Crossing border y2. | ((y(1:end-1) > yl(1)) & (yl(1) > y(2:end))) ... % Crossing border y1. | ((y(1:end-1) > yl(2)) & (yl(2) > y(2:end))); % Crossing border y2. crossp= [( (crossx & iny(1:end-1) & iny(2:end)) ... % Crossing a x border within y limits. | (crossy & inx(1:end-1) & inx(2:end)) ... % Crossing a y border within x limits. | crossx & crossy ... % Crossing a x and a y border (corner). ), false ... ]; crossp(2:end)= crossp(2:end) | crossp(1:end-1); % Add line segment's secont end point. keep= keep | crossp; end set(lines(m), 'XData', x(keep)) set(lines(m), 'YData', y(keep)) end end end
github
jacksky64/imageProcessing-master
dirSynch.m
.m
imageProcessing-master/piotr/toolbox/matlab/dirSynch.m
4,570
utf_8
d288299d31d15f1804183206d0aa0227
function dirSynch( root1, root2, showOnly, flag, ignDate ) % Synchronize two directory trees (or show differences between them). % % If a file or directory 'name' is found in both tree1 and tree2: % 1) if 'name' is a file in both the pair is considered the same if they % have identical size and identical datestamp (or if ignDate=1). % 2) if 'name' is a directory in both the dirs are searched recursively. % 3) if 'name' is a dir in root1 and a file in root2 (or vice-versa) % synchronization cannot proceed (an error is thrown). % If 'name' is found only in root1 or root2 it's a difference between them. % % The parameter flag controls how synchronization occurs: % flag==0: neither tree1 nor tree2 has preference (newer file is kept) % flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged) % flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged) % Run with showOnly=1 and different values of flag to see its effect. % % By default showOnly==1. If showOnly, displays a list of actions that need % to be performed in order to synchronize the two directory trees, but does % not actually perform the actions. It is highly recommended to run % dirSynch first with showOnly=1 before running it with showOnly=0. % % USAGE % dirSynch( root1, root2, [showOnly], [flag], [ignDate] ) % % INPUTS % root1 - root directory of tree1 % root2 - root directory of tree2 % showOnly - [1] show but do NOT perform actions % flag - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2 % ignDate - [0] if true considers two files same even if have diff dates % % OUTPUTS % dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 ) % % EXAMPLE % % See also % % Piotr's Computer Vision Matlab Toolbox Version 2.10 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] if(nargin<3 || isempty(showOnly)), showOnly=1; end; if(nargin<4 || isempty(flag)), flag=0; end; if(nargin<5 || isempty(ignDate)), ignDate=0; end; % get differences between root1/root2 and loop over them D = dirDiff( root1, root2, ignDate ); roots={root1,root2}; ticId = ticStatus; for i=1:length(D) % get action if( flag==1 ) if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end elseif( flag==2 ) if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end else act=1; if(D(i).in1 && D(i).in2) if( D(i).new1 ), src1=1; else src1=2; end else if( D(i).in1 ), src1=1; else src1=2; end end end src2=mod(src1,2)+1; % perform action if( act==1 ) if( showOnly ) disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]); else copyfile( [roots{src1} D(i).name], [roots{src2} D(i).name], 'f' ); end; else if( showOnly ) disp(['DEL in ' int2str(src1) ': ' D(i).name]); else fName = [roots{src1} D(i).name]; if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end end end if(~showOnly), tocStatus( ticId, i/length(D) ); end; end end function D = dirDiff( root1, root2, ignDate ) % get differences from root1 to root2 D1 = dirDiff1( root1, root2, ignDate, '/' ); % get differences from root2 to root1 D2 = dirDiff1( root2, root1, ignDate, '/' ); % remove duplicates (arbitrarily from D2) D2=D2(~([D2.in1] & [D2.in2])); % swap 1 and 2 in D2 for i=1:length(D2), D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1; end % merge D = [D1 D2]; end function D = dirDiff1( root1, root2, ignDate, subdir ) if(root1(end)~='/'), root1(end+1)='/'; end if(root2(end)~='/'), root2(end+1)='/'; end if(subdir(end)~='/'), subdir(end+1)='/'; end fs1=dir([root1 subdir]); fs2=dir([root2 subdir]); D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0); D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[]; for i1=1:length( fs1 ) name=fs1(i1).name; isdir=fs1(i1).isdir; if( any(strcmp(name,{'.','..'})) ), continue; end; i2 = find(strcmp(name,names2)); if(~isempty(i2) && isdir) % cannot handle this condition if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end; % recurse and record possible differences Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW> elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ... (ignDate || fs1(i1).datenum==fs2(i2).datenum)) % nothing to do - files are same continue; else % record differences n=n+1; D(n).name=[subdir name]; D(n).isdir=isdir; D(n).in1=1; D(n).in2=~isempty(i2); D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum); end end D = [D(1:n) Dsub]; end
github
jacksky64/imageProcessing-master
plotRoc.m
.m
imageProcessing-master/piotr/toolbox/matlab/plotRoc.m
5,212
utf_8
008f9c63073c6400c4960e9e213c47e5
function [h,miss,stds] = plotRoc( D, varargin ) % Function for display of rocs (receiver operator characteristic curves). % % Display roc curves. Consistent usage ensures uniform look for rocs. The % input D should have n rows, each of which is of the form: % D = [falsePosRate truePosRate] % D is generated, for example, by scanning a detection threshold over n % values from 0 (so first entry is [1 1]) to 1 (so last entry is [0 0]). % Alternatively D can be a cell vector of rocs, in which case an average % ROC will be shown with error bars. Plots missRate (which is just 1 minus % the truePosRate) on the y-axis versus the falsePosRate on the x-axis. % % USAGE % [h,miss,stds] = plotRoc( D, prm ) % % INPUTS % D - [nx2] n data points along roc [falsePosRate truePosRate] % typically ranges from [1 1] to [0 0] (or may be reversed) % prm - [] param struct % .color - ['g'] color for curve % .lineSt - ['-'] linestyle (see LineSpec) % .lineWd - [4] curve width % .logx - [0] use logarithmic scale for x-axis % .logy - [0] use logarithmic scale for y-axis % .marker - [''] marker type (see LineSpec) % .mrkrSiz - [12] marker size % .nMarker - [5] number of markers (regularly spaced) to display % .lims - [0 1 0 1] axes limits % .smooth - [0] if T compute lower envelop of roc to smooth staircase % .fpTarget - [] return miss rates at given fp values (and draw lines) % .xLbl - ['false positive rate'] label for x-axis % .yLbl - ['miss rate'] label for y-axis % % OUTPUTS % h - plot handle for use in legend only % miss - average miss rates at fpTarget reference values % stds - standard deviation of miss rates at fpTarget reference values % % EXAMPLE % k=2; x=0:.0001:1; data1 = [1-x; (1-x.^k).^(1/k)]'; % k=3; x=0:.0001:1; data2 = [1-x; (1-x.^k).^(1/k)]'; % hs(1)=plotRoc(data1,struct('color','g','marker','s')); % hs(2)=plotRoc(data2,struct('color','b','lineSt','--')); % legend( hs, {'roc1','roc2'} ); xlabel('fp'); ylabel('fn'); % % See also % % Piotr's Computer Vision Matlab Toolbox Version 3.02 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] % get params [color,lineSt,lineWd,logx,logy,marker,mrkrSiz,nMarker,lims,smooth, ... fpTarget,xLbl,yLbl] = getPrmDflt( varargin, {'color' 'g' 'lineSt' '-' ... 'lineWd' 4 'logx' 0 'logy' 0 'marker' '' 'mrkrSiz' 12 'nMarker' 5 ... 'lims' [] 'smooth' 0 'fpTarget' [] 'xLbl' 'false positive rate' ... 'yLbl' 'miss rate' } ); if( isempty(lims) ); lims=[logx*1e-5 1 logy*1e-5 1]; end % ensure descending fp rate, change to miss rate, optionally 'nicefy' roc if(~iscell(D)), D={D}; end; nD=length(D); for j=1:nD, assert(size(D{j},2)==2); end for j=1:nD, if(D{j}(1,2)<D{j}(end,2)), D{j}=flipud(D{j}); end; end for j=1:nD, D{j}(:,2)=1-D{j}(:,2); assert(all(D{j}(:,2)>=0)); end if(smooth), for j=1:nD, D{j}=smoothRoc(D{j}); end; end % plot: (1) h for legend only, (2) markers, (3) error bars, (4) roc curves hold on; axis(lims); xlabel(xLbl); ylabel(yLbl); prmMrkr = {'MarkerSize',mrkrSiz,'MarkerFaceColor',color}; prmClr={'Color',color}; prmPlot = [prmClr,{'LineWidth',lineWd}]; h = plot( 2, 0, [lineSt marker], prmMrkr{:}, prmPlot{:} ); %(1) DQ = quantizeRocs( D, nMarker, logx, lims ); DQm=mean(DQ,3); if(~isempty(marker)) plot(DQm(:,1),DQm(:,2),marker,prmClr{:},prmMrkr{:} ); end %(2) if(nD>1), DQs=std(DQ,0,3); errorbar(DQm(:,1),DQm(:,2),DQs(:,2),'.',prmClr{:}); end %(3) if(nD==1), DQ=D{1}; else DQ=quantizeRocs(D,100,logx,lims); end DQm = mean(DQ,3); plot( DQm(:,1), DQm(:,2), lineSt, prmPlot{:} ); %(4) % plot line at given fp rate m=length(fpTarget); miss=zeros(1,m); stds=miss; if( m>0 ) assert( min(DQm(:,1))<=min(fpTarget) ); DQs=std(DQ,0,3); for i=1:m, j=find(DQm(:,1)<=fpTarget(i)); j=j(1); miss(i)=DQm(j,2); stds(i)=DQs(j,2); end fp=min(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]); fp=max(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]); end % set log axes if( logx==1 ) ticks=10.^(-8:8); set(gca,'XScale','log','XTick',ticks); end if( logy==1 ) ticks=[.001 .002 .005 .01 .02 .05 .1 .2 .5 1]; set(gca,'YScale','log','YTick',ticks); end if( logx==1 || logy==1 ), grid on; set(gca,'XMinorGrid','off','XMinorTic','off'); set(gca,'YMinorGrid','off','YMinorTic','off'); end end function DQ = quantizeRocs( Ds, nPnts, logx, lims ) % estimate miss rate at each target fp rate nD=length(Ds); DQ=zeros(nPnts,2,nD); if(logx==1), fps=logspace(log10(lims(1)),log10(lims(2)),nPnts); else fps=linspace(lims(1),lims(2),nPnts); end; fps=flipud(fps'); for j=1:nD, D=[Ds{j}; 0 1]; k=1; fp=D(k,1); for i=1:nPnts while( k<size(D,1) && fp>=fps(i) ), k=k+1; fp=D(k,1); end k0=max(k-1,1); fp0=D(k0,1); assert(fp0>=fp); if(fp0==fp), r=.5; else r=(fps(i)-fp)/(fp0-fp); end DQ(i,1,j)=fps(i); DQ(i,2,j)=r*D(k0,2)+(1-r)*D(k,2); end end end function D1 = smoothRoc( D ) D1 = zeros(size(D)); n = size(D,1); cnt=0; for i=1:n isAnkle = (i==1) || (i==n); if( ~isAnkle ) dP=D1(cnt,:); dC=D(i,:); dN=D(i+1,:); isAnkle = (dC(1)~=dP(1)) && (dC(2)~=dN(2)); end if(isAnkle); cnt=cnt+1; D1(cnt,:)=D(i,:); end end D1=D1(1:cnt,:); end
github
jacksky64/imageProcessing-master
simpleCache.m
.m
imageProcessing-master/piotr/toolbox/matlab/simpleCache.m
4,098
utf_8
92df86b0b7e919c9a26388e598e4d370
function varargout = simpleCache( op, cache, varargin ) % A simple cache that can be used to store results of computations. % % Can save and retrieve arbitrary values using a vector (includnig char % vectors) as a key. Especially useful if a function must perform heavy % computation but is often called with the same inputs (for which it will % give the same outputs). Note that the current implementation does a % linear search for the key (a more refined implementation would use a hash % table), so it is not meant for large scale usage. % % To use inside a function, make the cache persistent: % persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end; % The following line, when placed inside a function, means the cache will % stay in memory until the matlab environment changes. For an example % usage see maskGaussians. % % USAGE - 'init': initialize a cache object % cache = simpleCache('init'); % % USAGE - 'put': put something in cache. key must be a numeric vector % cache = simpleCache( 'put', cache, key, val ); % % USAGE - 'get': retrieve from cache. found==1 if obj was found % [found,val] = simpleCache( 'get', cache, key ); % % USAGE - 'remove': free key % [cache,found] = simpleCache( 'remove', cache, key ); % % INPUTS % op - 'init', 'put', 'get', 'remove' % cache - the cache object being operated on % varargin - see USAGE above % % OUTPUTS % varargout - see USAGE above % % EXAMPLE % cache = simpleCache('init'); % hellokey=rand(1,3); worldkey=rand(1,11); % cache = simpleCache( 'put', cache, hellokey, 'hello' ); % cache = simpleCache( 'put', cache, worldkey, 'world' ); % [f,v]=simpleCache( 'get', cache, hellokey ); disp(v); % [f,v]=simpleCache( 'get', cache, worldkey ); disp(v); % % See also PERSISTENT, MASKGAUSSIANS % % Piotr's Computer Vision Matlab Toolbox Version 2.61 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] switch op case 'init' % init a cache cacheSiz = 8; cache.freeinds = 1:cacheSiz; cache.keyns = -ones(1,cacheSiz); cache.keys = cell(1,cacheSiz); cache.vals = cell(1,cacheSiz); varargout = {cache}; case 'put' % a put operation key=varargin{1}; val=varargin{2}; cache = cacheput( cache, key, val ); varargout = {cache}; case 'get' % a get operation key=varargin{1}; [ind,val] = cacheget( cache, key ); found = ind>0; varargout = {found,val}; case 'remove' % a remove operation key=varargin{1}; [cache,found] = cacheremove( cache, key ); varargout = {cache,found}; otherwise error('Unknown cache operation: %s',op); end end function cache = cachegrow( cache ) % double cache size cacheSiz = length( cache.keyns ); if( cacheSiz>64 ) % warn if getting big warning(['doubling cache size to: ' int2str2(cacheSiz*2)]);%#ok<WNTAG> end cache.freeinds = [cache.freeinds (cacheSiz+1):(2*cacheSiz)]; cache.keyns = [cache.keyns -ones(1,cacheSiz)]; cache.keys = [cache.keys cell(1,cacheSiz)]; cache.vals = [cache.vals cell(1,cacheSiz)]; end function cache = cacheput( cache, key, val ) % put something into the cache % get location to place ind = cacheget( cache, key ); % see if already in cache if( ind==-1 ) if( isempty( cache.freeinds ) ) cache = cachegrow( cache ); %grow cache end ind = cache.freeinds(1); % get new cache loc cache.freeinds = cache.freeinds(2:end); end % now simply place in ind cache.keyns(ind) = length(key); cache.keys{ind} = key; cache.vals{ind} = val; end function [ind,val] = cacheget( cache, key ) % get cache element, or fail cacheSiz = length( cache.keyns ); keyn = length( key ); for i=1:cacheSiz if(keyn==cache.keyns(i) && all(key==cache.keys{i})) val = cache.vals{i}; ind = i; return; end end ind=-1; val=-1; end function [cache,found] = cacheremove( cache, key ) % get cache element, or fail ind = cacheget( cache, key ); found = ind>0; if( found ) cache.freeinds = [ind cache.freeinds]; cache.keyns(ind) = -1; cache.keys{ind} = []; cache.vals{ind} = []; end end
github
jacksky64/imageProcessing-master
tpsInterpolate.m
.m
imageProcessing-master/piotr/toolbox/matlab/tpsInterpolate.m
1,646
utf_8
d3bd3a26d048f32cfdc17884ccae6d8c
function [xsR,ysR] = tpsInterpolate( warp, xs, ys, show ) % Apply warp (obtained by tpsGetWarp) to a set of new points. % % USAGE % [xsR,ysR] = tpsInterpolate( warp, xs, ys, [show] ) % % INPUTS % warp - [see tpsGetWarp] bookstein warping parameters % xs, ys - points to apply warp to % show - [1] will display results in figure(show) % % OUTPUTS % xsR, ysR - result of warp applied to xs, ys % % EXAMPLE % % See also TPSGETWARP % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] if( nargin<4 || isempty(show)); show = 1; end wx = warp.wx; affinex = warp.affinex; wy = warp.wy; affiney = warp.affiney; xsS = warp.xsS; ysS = warp.ysS; xsD = warp.xsD; ysD = warp.ysD; % interpolate points (xs,ys) xsR = f( wx, affinex, xsS, ysS, xs(:)', ys(:)' ); ysR = f( wy, affiney, xsS, ysS, xs(:)', ys(:)' ); % optionally show points (xsR, ysR) if( show ) figure(show); subplot(2,1,1); plot( xs, ys, '.', 'color', [0 0 1] ); hold('on'); plot( xsS, ysS, '+' ); hold('off'); subplot(2,1,2); plot( xsR, ysR, '.' ); hold('on'); plot( xsD, ysD, '+' ); hold('off'); end function zs = f( w, aff, xsS, ysS, xs, ys ) % find f(x,y) for xs and ys given W and original points n = size(w,1); ns = size(xs,2); delXs = xs'*ones(1,n) - ones(ns,1)*xsS; delYs = ys'*ones(1,n) - ones(ns,1)*ysS; distSq = (delXs .* delXs + delYs .* delYs); distSq = distSq + eye(size(distSq)) + eps; U = distSq .* log( distSq ); U( isnan(U) )=0; zs = aff(1)*ones(ns,1)+aff(2)*xs'+aff(3)*ys'; zs = zs + sum((U.*(ones(ns,1)*w')),2);
github
jacksky64/imageProcessing-master
checkNumArgs.m
.m
imageProcessing-master/piotr/toolbox/matlab/checkNumArgs.m
3,796
utf_8
726c125c7dc994c4989c0e53ad4be747
function [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag ) % Helper utility for checking numeric vector arguments. % % Runs a number of tests on the numeric array x. Tests to see if x has all % integer values, all positive values, and so on, depending on the values % for intFlag and signFlag. Also tests to see if the size of x matches siz % (unless siz==[]). If x is a scalar, x is converted to a array simply by % creating a matrix of size siz with x in each entry. This is why the % function returns x. siz=M is equivalent to siz=[M M]. If x does not % satisfy some criteria, an error message is returned in er. If x satisfied % all the criteria er=''. Note that error('') has no effect, so can use: % [ x, er ] = checkNumArgs( x, ... ); error(er); % which will throw an error only if something was wrong with x. % % USAGE % [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag ) % % INPUTS % x - numeric array % siz - []: does not test size of x % - [if not []]: intended size for x % intFlag - -1: no need for integer x % 0: error if non integer x % 1: error if non odd integers % 2: error if non even integers % signFlag - -2: entires of x must be strictly negative % -1: entires of x must be negative % 0: no contstraints on sign of entries in x % 1: entires of x must be positive % 2: entires of x must be strictly positive % % OUTPUTS % x - if x was a scalar it may have been replicated into a matrix % er - contains error msg if anything was wrong with x % % EXAMPLE % a=1; [a, er]=checkNumArgs( a, [1 3], 2, 0 ); a, error(er) % % See also NARGCHK % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] xname = inputname(1); er=''; if( isempty(siz) ); siz = size(x); end; if( length(siz)==1 ); siz=[siz siz]; end; % first check that x is numeric if( ~isnumeric(x) ); er = [xname ' not numeric']; return; end; % if x is a scalar, simply replicate it. xorig = x; if( length(x)==1); x = x(ones(siz)); end; % regardless, must have same number of x as n if( length(siz)~=ndims(x) || ~all(size(x)==siz) ) er = ['has size = [' num2str(size(x)) '], ']; er = [er 'which is not the required size of [' num2str(siz) ']']; er = createErrMsg( xname, xorig, er ); return; end % check that x are the right type of integers (unless intFlag==-1) switch intFlag case 0 if( ~all(mod(x,1)==0)) er = 'must have integer entries'; er = createErrMsg( xname, xorig, er); return; end; case 1 if( ~all(mod(x,2)==1)) er = 'must have odd integer entries'; er = createErrMsg( xname, xorig, er); return; end; case 2 if( ~all(mod(x,2)==0)) er = 'must have even integer entries'; er = createErrMsg( xname, xorig, er ); return; end; end; % check sign of entries in x (unless signFlag==0) switch signFlag case -2 if( ~all(x<0)) er = 'must have strictly negative entries'; er = createErrMsg( xname, xorig, er ); return; end; case -1 if( ~all(x<=0)) er = 'must have negative entries'; er = createErrMsg( xname, xorig, er ); return; end; case 1 if( ~all(x>=0)) er = 'must have positive entries'; er = createErrMsg( xname, xorig, er ); return; end; case 2 if( ~all(x>0)) er = 'must have strictly positive entries'; er = createErrMsg( xname, xorig, er ); return; end end function er = createErrMsg( xname, x, er ) if(numel(x)<10) er = ['Numeric input argument ' xname '=[' num2str(x) '] ' er '.']; else er = ['Numeric input argument ' xname ' ' er '.']; end
github
jacksky64/imageProcessing-master
fevalDistr.m
.m
imageProcessing-master/piotr/toolbox/matlab/fevalDistr.m
11,227
utf_8
7e4d5077ef3d7a891b2847cb858a2c6c
function [out,res] = fevalDistr( funNm, jobs, varargin ) % Wrapper for embarrassingly parallel function evaluation. % % Runs "r=feval(funNm,jobs{i}{:})" for each job in a parallel manner. jobs % should be a cell array of length nJob and each job should be a cell array % of parameters to pass to funNm. funNm must be a function in the path and % must return a single value (which may be a dummy value if funNm writes % results to disk). Different forms of parallelization are supported % depending on the hardware and Matlab toolboxes available. The type of % parallelization is determined by the parameter 'type' described below. % % type='LOCAL': jobs are executed using a simple "for" loop. This implies % no parallelization and is the default fallback option. % % type='PARFOR': jobs are executed using a "parfor" loop. This option is % only available if the Matlab *Parallel Computing Toolbox* is installed. % Make sure to setup Matlab workers first using "matlabpool open". % % type='DISTR': jobs are executed on the Caltech cluster. Distributed % queuing system must be installed separately. Currently this option is % only supported on the Caltech cluster but could easily be installed on % any Linux cluster as it requires only SSH and a shared filesystem. % Parameter pLaunch is used for controller('launchQueue',pLaunch{:}) and % determines cluster machines used (e.g. pLaunch={48,401:408}). % % type='COMPILED': jobs are executed locally in parallel by first compiling % an executable and then running it in background. This option requires the % *Matlab Compiler* to be installed (but does NOT require the Parallel % Computing Toolbox). Compiling can take 1-10 minutes, so use this option % only for large jobs. (On Linux alter startup.m by calling addpath() only % if ~isdeployed, otherwise will get error about "CTF" after compiling). % Note that relative paths will not work after compiling so all paths used % by funNm must be absolute paths. % % type='WINHPC': jobs are executed on a Windows HPC Server 2008 cluster. % Similar to type='COMPILED', except after compiling, the executable is % queued to the HPC cluster where all computation occurs. This option % likewise requires the *Matlab Compiler*. Paths to data, etc., must be % absolute paths and available from HPC cluster. Parameter pLaunch must % have two fields 'scheduler' and 'shareDir' that define the HPC Server. % Extra parameters in pLaunch add finer control, see fedWinhpc for details. % For example, at MSR one possible cluster is defined by scheduler = % 'MSR-L25-DEV21' and shareDir = '\\msr-arrays\scratch\msr-pool\L25-dev21'. % Note call to 'job submit' from Matlab will hang unless pwd is saved % (simply call 'job submit' from cmd prompt and enter pwd). % % USAGE % [out,res] = fevalDistr( funNm, jobs, [varargin] ) % % INPUTS % funNm - name of function that will process jobs % jobs - [1xnJob] cell array of parameters for each job % varargin - additional params (struct or name/value pairs) % .type - ['local'], 'parfor', 'distr', 'compiled', 'winhpc' % .pLaunch - [] extra params for type='distr' or type='winhpc' % .group - [1] send jobs in batches (only relevant if type='distr') % % OUTPUTS % out - 1 if jobs completed successfully % res - [1xnJob] cell array containing results of each job % % EXAMPLE % % Note: in this case parallel versions are slower since conv2 is so fast % n=16; jobs=cell(1,n); for i=1:n, jobs{i}={rand(500),ones(25)}; end % tic, [out,J1] = fevalDistr('conv2',jobs,'type','local'); toc, % tic, [out,J2] = fevalDistr('conv2',jobs,'type','parfor'); toc, % tic, [out,J3] = fevalDistr('conv2',jobs,'type','compiled'); toc % [isequal(J1,J2), isequal(J1,J3)], figure(1); montage2(cell2array(J1)) % % See also matlabpool mcc % % Piotr's Computer Vision Matlab Toolbox Version 3.26 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] dfs={'type','local','pLaunch',[],'group',1}; [type,pLaunch,group]=getPrmDflt(varargin,dfs,1); store=(nargout==2); if(isempty(jobs)), res=cell(1,0); out=1; return; end switch lower(type) case 'local', [out,res]=fedLocal(funNm,jobs,store); case 'parfor', [out,res]=fedParfor(funNm,jobs,store); case 'distr', [out,res]=fedDistr(funNm,jobs,pLaunch,group,store); case 'compiled', [out,res]=fedCompiled(funNm,jobs,store); case 'winhpc', [out,res]=fedWinhpc(funNm,jobs,pLaunch,store); otherwise, error('unkown type: ''%s''',type); end end function [out,res] = fedLocal( funNm, jobs, store ) % Run jobs locally using for loop. nJob=length(jobs); res=cell(1,nJob); out=1; tid=ticStatus('collecting jobs'); for i=1:nJob, r=feval(funNm,jobs{i}{:}); if(store), res{i}=r; end; tocStatus(tid,i/nJob); end end function [out,res] = fedParfor( funNm, jobs, store ) % Run jobs locally using parfor loop. nJob=length(jobs); res=cell(1,nJob); out=1; parfor i=1:nJob, r=feval(funNm,jobs{i}{:}); if(store), res{i}=r; end; end end function [out,res] = fedDistr( funNm, jobs, pLaunch, group, store ) % Run jobs using Linux queuing system. if(~exist('controller.m','file')) msg='distributed queuing not installed, switching to type=''local''.'; warning(msg); [out,res]=fedLocal(funNm,jobs,store); return; %#ok<WNTAG> end nJob=length(jobs); res=cell(1,nJob); controller('launchQueue',pLaunch{:}); if( group>1 ) nJobGrp=ceil(nJob/group); jobsGrp=cell(1,nJobGrp); k=0; for i=1:nJobGrp, k1=min(nJob,k+group); jobsGrp{i}={funNm,jobs(k+1:k1),'type','local'}; k=k1; end nJob=nJobGrp; jobs=jobsGrp; funNm='fevalDistr'; end jids=controller('jobsAdd',nJob,funNm,jobs); k=0; fprintf('Sent %i jobs...\n',nJob); tid=ticStatus('collecting jobs'); while( 1 ) jids1=controller('jobProbe',jids); if(isempty(jids1)), pause(.1); continue; end jid=jids1(1); [r,err]=controller('jobRecv',jid); if(~isempty(err)), disp('ABORTING'); out=0; break; end k=k+1; if(store), res{jid==jids}=r; end tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end end; controller('closeQueue'); end function [out,res] = fedCompiled( funNm, jobs, store ) % Run jobs locally in background in parallel using compiled code. nJob=length(jobs); res=cell(1,nJob); tDir=jobSetup('.',funNm,'',{}); cmd=[tDir 'fevalDistrDisk ' funNm ' ' tDir ' ']; i=0; k=0; Q=feature('numCores'); q=0; tid=ticStatus('collecting jobs'); while( 1 ) % launch jobs until queue is full (q==Q) or all jobs launched (i==nJob) while(q<Q && i<nJob), q=q+1; i=i+1; jobSave(tDir,jobs{i},i); if(ispc), system2(['start /B /min ' cmd int2str2(i,10)],0); else system2([cmd int2str2(i,10) ' &'],0); end end % collect completed jobs (k1 of them), release queue slots done=jobFileIds(tDir,'done'); k1=length(done); k=k+k1; q=q-k1; for i1=done, res{i1}=jobLoad(tDir,i1,store); end pause(1); tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end end for i=1:10, try rmdir(tDir,'s'); break; catch,pause(1),end; end %#ok<CTCH> end function [out,res] = fedWinhpc( funNm, jobs, pLaunch, store ) % Run jobs using Windows HPC Server. nJob=length(jobs); res=cell(1,nJob); dfs={'shareDir','REQ','scheduler','REQ','executable','fevalDistrDisk',... 'mccOptions',{},'coresPerTask',1,'minCores',1024,'priority',2000}; p = getPrmDflt(pLaunch,dfs,1); tDir = jobSetup(p.shareDir,funNm,p.executable,p.mccOptions); for i=1:nJob, jobSave(tDir,jobs{i},i); end hpcSubmit(funNm,1:nJob,tDir,p); k=0; ticId=ticStatus('collecting jobs'); while( 1 ) done=jobFileIds(tDir,'done'); k=k+length(done); for i1=done, res{i1}=jobLoad(tDir,i1,store); end pause(5); tocStatus(ticId,k/nJob); if(k==nJob), out=1; break; end end for i=1:10, try rmdir(tDir,'s'); break; catch,pause(5),end; end %#ok<CTCH> end function tids = hpcSubmit( funNm, ids, tDir, pLaunch ) % Helper: send jobs w given ids to HPC cluster. n=length(ids); tids=cell(1,n); if(n==0), return; end; scheduler=[' /scheduler:' pLaunch.scheduler ' ']; m=system2(['cluscfg view' scheduler],0); minCores=(hpcParse(m,'total number of nodes',1) - ... hpcParse(m,'Unreachable nodes',1) - 1)*8; minCores=min([minCores pLaunch.minCores n*pLaunch.coresPerTask]); m=system2(['job new /numcores:' int2str(minCores) '-*' scheduler ... '/priority:' int2str(pLaunch.priority)],1); jid=hpcParse(m,'created job, id',0); s=min(ids); e=max(ids); p=n>1 && isequal(ids,s:e); if(p), jid1=[jid '.1']; else jid1=jid; end for i=1:n, tids{i}=[jid1 '.' int2str(i)]; end cmd0=''; if(p), cmd0=['/parametric:' int2str(s) '-' int2str(e)]; end cmd=@(id) ['job add ' jid scheduler '/workdir:' tDir ' /numcores:' ... int2str(pLaunch.coresPerTask) ' ' cmd0 ' /stdout:stdout' id ... '.txt ' pLaunch.executable ' ' funNm ' ' tDir ' ' id]; if(p), ids1='*'; n=1; else ids1=int2str2(ids); end if(n==1), ids1={ids1}; end; for i=1:n, system2(cmd(ids1{i}),1); end system2(['job submit /id:' jid scheduler],1); disp(repmat(' ',1,80)); end function v = hpcParse( msg, key, tonum ) % Helper: extract val corresponding to key in hpc msg. t=regexp(msg,': |\n','split'); t=strtrim(t(1:floor(length(t)/2)*2)); keys=t(1:2:end); vals=t(2:2:end); j=find(strcmpi(key,keys)); if(isempty(j)), error('key ''%s'' not found in:\n %s',key,msg); end v=vals{j}; if(tonum==0), return; elseif(isempty(v)), v=0; return; end if(tonum==1), v=str2double(v); return; end v=regexp(v,' ','split'); v=str2double(regexp(v{1},':','split')); if(numel(v)==4), v(5)=0; end; v=((v(1)*24+v(2))*60+v(3))*60+v(4)+v(5)/1000; end function tDir = jobSetup( rtDir, funNm, executable, mccOptions ) % Helper: prepare by setting up temporary dir and compiling funNm t=clock; t=mod(t(end),1); t=round((t+rand)/2*1e15); tDir=[rtDir filesep sprintf('fevalDistr-%015i',t) filesep]; mkdir(tDir); if(~isempty(executable) && exist(executable,'file')) fprintf('Reusing compiled executable...\n'); copyfile(executable,tDir); else t=clock; fprintf('Compiling (this may take a while)...\n'); [~,f,e]=fileparts(executable); if(isempty(f)), f='fevalDistrDisk'; end mcc('-m','fevalDistrDisk','-d',tDir,'-o',f,'-a',funNm,mccOptions{:}); t=etime(clock,t); fprintf('Compile complete (%.1f seconds).\n',t); if(~isempty(executable)), copyfile([tDir filesep f e],executable); end end end function ids = jobFileIds( tDir, type ) % Helper: get list of job files ids on disk of given type fs=dir([tDir '*-' type '*']); fs={fs.name}; n=length(fs); ids=zeros(1,n); for i=1:n, ids(i)=str2double(fs{i}(1:10)); end end function jobSave( tDir, job, ind ) %#ok<INUSL> % Helper: save job to temporary file for use with fevalDistrDisk() save([tDir int2str2(ind,10) '-in'],'job'); end function r = jobLoad( tDir, ind, store ) % Helper: load job and delete temporary files from fevalDistrDisk() f=[tDir int2str2(ind,10)]; if(store), r=load([f '-out']); r=r.r; else r=[]; end fs={[f '-done'],[f '-in.mat'],[f '-out.mat']}; delete(fs{:}); pause(.1); for i=1:3, k=0; while(exist(fs{i},'file')==2) %#ok<ALIGN> warning('Waiting to delete %s.',fs{i}); %#ok<WNTAG> delete(fs{i}); pause(5); k=k+1; if(k>12), break; end; end; end end function msg = system2( cmd, show ) % Helper: wraps system() call if(show), disp(cmd); end [status,msg]=system(cmd); msg=msg(1:end-1); if(status), error(msg); end if(show), disp(msg); end end
github
jacksky64/imageProcessing-master
medfilt1m.m
.m
imageProcessing-master/piotr/toolbox/filters/medfilt1m.m
2,998
utf_8
a3733d27c60efefd57ada9d83ccbaa3d
function y = medfilt1m( x, r, z ) % One-dimensional adaptive median filtering with missing values. % % Applies a width s=2*r+1 one-dimensional median filter to vector x, which % may contain missing values (elements equal to z). If x contains no % missing values, y(j) is set to the median of x(j-r:j+r). If x contains % missing values, y(j) is set to the median of x(j-R:j+R), where R is the % smallest radius such that sum(valid(x(j-R:j+R)))>=s, i.e. the number of % valid values in the window is at least s (a value x is valid x~=z). Note % that the radius R is adaptive and can vary as a function of j. % % This function uses a modified version of medfilt1.m from Matlab's 'Signal % Processing Toolbox'. Note that if x contains no missing values, % medfilt1m(x) and medfilt1(x) are identical execpt at boundary regions. % % USAGE % y = medfilt1m( x, r, [z] ) % % INPUTS % x - [nx1] length n vector with possible missing entries % r - filter radius % z - [NaN] element that represents missing entries % % OUTPUTS % y - [nx1] filtered vector x % % EXAMPLE % x=repmat((1:4)',1,5)'; x=x(:)'; x0=x; % n=length(x); x(rand(n,1)>.8)=NaN; % y = medfilt1m(x,2); [x0; x; y; x0-y] % % See also MODEFILT1, MEDFILT1 % % Piotr's Computer Vision Matlab Toolbox Version 2.35 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] % apply medfilt1 (standard median filter) to valid locations in x if(nargin<3 || isempty(z)), z=NaN; end; x=x(:)'; n=length(x); if(isnan(z)), valid=~isnan(x); else valid=x~=z; end; v=sum(valid); if(v==0), y=repmat(z,1,n); return; end if(v<2*r+1), y=repmat(median(x(valid)),1,n); return; end y=medfilt1(x(valid),2*r+1); % get radius R needed at each location j to span s=2r+1 valid values % get start (a) and end (b) locations and map back to location in y C=[0 cumsum(valid)]; s=2*r+1; R=find(C==s); R=R(1)-2; pos=zeros(1,n); for j=1:n, R0=R; R=R0-1; a=max(1,j-R); b=min(n,j+R); if(C(b+1)-C(a)<s), R=R0; a=max(1,j-R); b=min(n,j+R); if(C(b+1)-C(a)<s), R=R0+1; a=max(1,j-R); b=min(n,j+R); end end pos(j)=(C(b+1)+C(a+1))/2; end y=y(floor(pos)); end function y = medfilt1( x, s ) % standard median filter (copied from medfilt1.m) n=length(x); r=floor(s/2); indr=(0:s-1)'; indc=1:n; ind=indc(ones(1,s),1:n)+indr(:,ones(1,n)); x0=x(ones(r,1))*0; X=[x0'; x'; x0']; X=reshape(X(ind),s,n); y=median(X,1); end % function y = medfilt1( x, s ) % % standard median filter (slow) % % get unique values in x % [vals,disc,inds]=unique(x); m=length(vals); n=length(x); % if(m>256), warning('x takes on large number of diff vals'); end %#ok<WNTAG> % % create quantized representation [H(i,j)==1 iff x(j)==vals(i)] % H=zeros(m,n); H(sub2ind2([m,n],[inds; 1:n]'))=1; % % create histogram [H(i,j) is count of x(j-r:j+r)==vals(i)] % H=localSum(H,[0 s],'same'); % % compute median for each j and map inds back to original vals % [disc,inds]=max(cumsum(H,1)>s/2,[],1); y=vals(inds); % end
github
jacksky64/imageProcessing-master
FbMake.m
.m
imageProcessing-master/piotr/toolbox/filters/FbMake.m
6,692
utf_8
b625c1461a61485af27e490333350b4b
function FB = FbMake( dim, flag, show ) % Various 1D/2D/3D filterbanks (hardcoded). % % USAGE % FB = FbMake( dim, flag, [show] ) % % INPUTS % dim - dimension % flag - controls type of filterbank to create % - if d==1 % 1: gabor filter bank for spatiotemporal stuff % - if d==2 % 1: filter bank from Serge Belongie % 2: 1st/2nd order DooG filters. Similar to Gabor filterbank. % 3: similar to Laptev&Lindberg ICPR04 % 4: decent seperable steerable? filterbank % 5: berkeley filterbank for textons papers % 6: symmetric DOOG filters % - if d==3 % 1: decent seperable steerable filterbank % show - [0] figure to use for optional display % % OUTPUTS % % EXAMPLE % FB = FbMake( 2, 1, 1 ); % % See also FBAPPLY2D % % Piotr's Computer Vision Matlab Toolbox Version 2.0 % Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com] % Licensed under the Simplified BSD License [see external/bsd.txt] if( nargin<3 || isempty(show) ); show=0; end % create FB switch dim case 1 FB = FbMake1D( flag ); case 2 FB = FbMake2D( flag ); case 3 FB = FbMake3d( flag ); otherwise error( 'dim must be 1 2 or 3'); end % display FbVisualize( FB, show ); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FB = FbMake1D( flag ) switch flag case 1 %%% gabor filter bank for spatiotemporal stuff omegas = 1 ./ [3 4 5 7.5 11]; sigmas = [3 4 5 7.5 11]; FB = FbMakegabor1D( 15, sigmas, omegas ); otherwise error('none created.'); end function FB = FbMakegabor1D( r, sigmas, omegas ) for i=1:length(omegas) [feven,fodd]=filterGabor1d(r,sigmas(i),omegas(i)); if( i==1 ); FB=repmat(feven,[2*length(omegas) 1]); end FB(i*2-1,:)=feven; FB(i*2,:)=fodd; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FB = FbMake2D( flag ) switch flag case 1 %%% filter bank from Berkeley / Serge Belongie r=15; FB = FbMakegabor( r, 6, 3, 3, sqrt(2) ); FB2 = FbMakeDOG( r, .6, 2.8, 4); FB = cat(3, FB, FB2); %FB = FB(:,:,1:2:36); %include only even symmetric filters %FB = FB(:,:,2:2:36); %include only odd symmetric filters case 2 %%% 1st/2nd order DooG filters. Similar to Gabor filterbank. FB = FbMakeDooG( 15, 6, 3, 5, .5) ; case 3 %%% similar to Laptev&Lindberg ICPR04 % Wierd filterbank of Gaussian derivatives at various scales % Higher order filters probably not useful. r = 9; dims=[2*r+1 2*r+1]; sigs = [.5 1 1.5 3]; % sigs = [1,1.5,2]; derivs = []; %derivs = [ derivs; 0 0 ]; % 0th order %derivs = [ derivs; 1 0; 0 1 ]; % first order %derivs = [ derivs; 2 0; 0 2; 1 1 ]; % 2nd order %derivs = [ derivs; 3 0; 0 3; 1 2; 2 1 ]; % 3rd order %derivs = [ derivs; 4 0; 0 4; 1 3; 3 1; 2 2 ]; % 4th order derivs = [ derivs; 0 1; 0 2; 0 3; 0 4; 0 5]; % 0n order derivs = [ derivs; 1 0; 2 0; 3 0; 4 0; 5 0]; % n0 order cnt=1; nderivs = size(derivs,1); for s=1:length(sigs) for i=1:nderivs dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 ); if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end FB(:,:,cnt) = dG; cnt=cnt+1; %dG = filterDoog( dims, [sigs(s)*3 sigs(s)], derivs(i,:), 0 ); %FB(:,:,cnt) = dG; cnt=cnt+1; %dG = filterDoog( dims, [sigs(s) sigs(s)*3], derivs(i,:), 0 ); %FB(:,:,cnt) = dG; cnt=cnt+1; end end case 4 % decent seperable steerable? filterbank r = 9; dims=[2*r+1 2*r+1]; sigs = [.5 1.5 3]; derivs = [1 0; 0 1; 2 0; 0 2]; cnt=1; nderivs = size(derivs,1); for s=1:length(sigs) for i=1:nderivs dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 ); if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end FB(:,:,cnt) = dG; cnt=cnt+1; end end FB2 = FbMakeDOG( r, .6, 2.8, 4); FB = cat(3, FB, FB2); case 5 %%% berkeley filterbank for textons papers FB = FbMakegabor( 7, 6, 1, 2, 2 ); case 6 %%% symmetric DOOG filters FB = FbMakeDooGSym( 4, 2, [.5 1] ); otherwise error('none created.'); end function FB = FbMakegabor( r, nOrient, nScales, lambda, sigma ) % multi-scale even/odd gabor filters. Adapted from code by Serge Belongie. cnt=1; for m=1:nScales for n=1:nOrient [F1,F2]=filterGabor2d(r,sigma^m,lambda,180*(n-1)/nOrient); if(m==1 && n==1); FB=repmat(F1,[1 1 nScales*nOrient*2]); end FB(:,:,cnt)=F1; cnt=cnt+1; FB(:,:,cnt)=F2; cnt=cnt+1; end end function FB = FbMakeDooGSym( r, nOrient, sigs ) % Adds symmetric DooG filters. These are similar to gabor filters. cnt=1; dims=[2*r+1 2*r+1]; for s=1:length(sigs) Fodd = -filterDoog( dims, [sigs(s) sigs(s)], [1 0], 0 ); Feven = filterDoog( dims, [sigs(s) sigs(s)], [2 0], 0 ); if(s==1); FB=repmat(Fodd,[1 1 length(sigs)*nOrient*2]); end for n=1:nOrient theta = 180*(n-1)/nOrient; FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1; FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1; end end function FB = FbMakeDooG( r, nOrient, nScales, lambda, sigma ) % 1st/2nd order DooG filters. Similar to Gabor filterbank. % Defaults: nOrient=6, nScales=3, lambda=5, sigma=.5, cnt=1; dims=[2*r+1 2*r+1]; for m=1:nScales sigma = sigma * m^.7; Fodd = -filterDoog( dims, [sigma lambda*sigma^.6], [1,0], 0 ); Feven = filterDoog( dims, [sigma lambda*sigma^.6], [2,0], 0 ); if(m==1); FB=repmat(Fodd,[1 1 nScales*nOrient*2]); end for n=1:nOrient theta = 180*(n-1)/nOrient; FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1; FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1; end end function FB = FbMakeDOG( r, sigmaStr, sigmaEnd, n ) % adds a serires of difference of Gaussian filters. sigs = sigmaStr:(sigmaEnd-sigmaStr)/(n-1):sigmaEnd; for s=1:length(sigs) FB(:,:,s) = filterDog2d(r,sigs(s),2); %#ok<AGROW> if( s==1 ); FB=repmat(FB,[1 1 length(sigs)]); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function FB = FbMake3d( flag ) switch flag case 1 % decent seperable steerable filterbank r = 25; dims=[2*r+1 2*r+1 2*r+1]; sigs = [.5 1.5 3]; derivs = [0 0 1; 0 1 0; 1 0 0; 0 0 2; 0 2 0; 2 0 0]; cnt=1; nderivs = size(derivs,1); for s=1:length(sigs) for i=1:nderivs dG = filterDoog( dims, repmat(sigs(s),[1 3]), derivs(i,:), 0 ); if(s==1 && i==1); FB=repmat(dG,[1 1 1 nderivs*length(sigs)]); end FB(:,:,:,cnt) = dG; cnt=cnt+1; end end otherwise error('none created.'); end
github
jacksky64/imageProcessing-master
mhd_read_volume.m
.m
imageProcessing-master/matlab_elastix/code/mhd_read_volume.m
2,646
utf_8
b4ec0a486a54b723e63226bfcf7494a9
function V = mhd_read_volume(info) % Function for reading the volume of a Insight Meta-Image (.mhd, .mhd) file % % volume = tk_read_volume(file-header) % % examples: % 1: info = mhd_read_header() % V = mhd_read_volume(info); % imshow(squeeze(V(:,:,round(end/2))),[]); % % 2: V = mhd_read_volume('test.mhd'); if(~isstruct(info)), info=mhd_read_header(info); end switch(lower(info.DataFile)) case 'local' otherwise % Seperate file info.Filename=fullfile(fileparts(info.Filename),info.DataFile); end % Open file switch(info.ByteOrder(1)) case ('true') fid=fopen(info.Filename','rb','ieee-be'); otherwise fid=fopen(info.Filename','rb','ieee-le'); end switch(lower(info.DataFile)) case 'local' % Skip header fseek(fid,info.HeaderSize,'bof'); otherwise fseek(fid,0,'bof'); end datasize=prod(info.Dimensions)*info.BitDepth/8; switch(info.CompressedData(1)) case 'f' % Read the Data switch(info.DataType) case 'char' V = int8(fread(fid,datasize,'char')); case 'uchar' V = uint8(fread(fid,datasize,'uchar')); case 'short' V = int16(fread(fid,datasize,'short')); case 'ushort' V = uint16(fread(fid,datasize,'ushort')); case 'int' V = int32(fread(fid,datasize,'int')); case 'uint' V = uint32(fread(fid,datasize,'uint')); case 'float' V = single(fread(fid,datasize,'float')); case 'double' V = double(fread(fid,datasize,'double')); end case 't' switch(info.DataType) case 'char', DataType='int8'; case 'uchar', DataType='uint8'; case 'short', DataType='int16'; case 'ushort', DataType='uint16'; case 'int', DataType='int32'; case 'uint', DataType='uint32'; case 'float', DataType='single'; case 'double', DataType='double'; end Z = fread(fid,inf,'uchar=>uint8'); V = zlib_decompress(Z,DataType); end fclose(fid); V = reshape(V,info.Dimensions); function M = zlib_decompress(Z,DataType) import com.mathworks.mlwidgets.io.InterruptibleStreamCopier a=java.io.ByteArrayInputStream(Z); b=java.util.zip.InflaterInputStream(a); isc = InterruptibleStreamCopier.getInterruptibleStreamCopier; c = java.io.ByteArrayOutputStream; isc.copyStream(b,c); M=typecast(c.toByteArray,DataType);
github
jacksky64/imageProcessing-master
example_invert.m
.m
imageProcessing-master/matlab_elastix/MelastiX_examples/invert_transform/example_invert.m
1,976
utf_8
27a15a8293fb85504bed3384cfc4886b
function example_invert % This example shows how to invert a transform. % We load a fixed image and a distorted version of it, the moving image. % Landmarks are defined in the moving image space and overlaid on the moving image. % The goal is to overlay these points on the fixed image. % Achieving this goal requires calculating the inverse transform. % % This approach is useful in scenarios where you have a single reference % image and multiple sample images that you want to register to the one % reference image. If these sample images are associated with landmarks, % you can overlay the landmarks from the different sample images into a common % reference space. help(mfilename) fprintf('\nStep One:\nLoad images and points.\n') tmpDir = fullfile(tempdir,'dog_registration'); params = {'params_0.txt','params_1.txt'}; fixed = imread('../transformix/uma.tiff'); moving = imread('../transformix/uma_distorted.tiff'); pointsInMovingSpace = csvread('points_on_deformed_dog.csv'); %read sparse points clf subplot(2,2,1) showImage(fixed,'Fixed image') subplot(2,2,2) showImage(moving,'Moving image with sparse points') hold on plot(pointsInMovingSpace(:,1),pointsInMovingSpace(:,2),'g.') hold off drawnow fprintf('\nStep Two:\nRegistering moving image to fixed image with elastix...\n') elastix(moving,fixed,tmpDir,params) registered_dog = mhd_read(fullfile(tmpDir,'result.1.mhd')); subplot(2,2,3) showImage(registered_dog,'Registered moving image') drawnow fprintf('\nStep Three:\nInverting the transform...\n') inverted = invertElastixTransform(tmpDir); fprintf('\nStep Four:\nUsing transformix to apply inverted transform to sparse points in moving space...\n') subplot(2,2,4) showImage(fixed,'Fixed image with inverse transformed points') drawnow REG=transformix(pointsInMovingSpace,inverted); hold on plot(REG.OutputPoint(:,1),REG.OutputPoint(:,2),'g.') hold off function showImage(im,thisTitle) imagesc(im) axis equal off title(thisTitle)
github
jacksky64/imageProcessing-master
RUN_ALL.m
.m
imageProcessing-master/matlab_elastix/MelastiX_examples/elastix/RUN_ALL.m
277
utf_8
c80336424b937464c219ad82e07d73a3
function RUN_ALL str = ' ====> PRESS RETURN <==== '; example_2D_affine_nSpatialSamples disp(str), pause example_2D_affine_alpha disp(str), pause example_2D_warping disp(str), pause example_2D_affineThenWarping disp(str), pause example_2D_affineThenWarping_withParams
github
jacksky64/imageProcessing-master
example_2D_affine_alpha.m
.m
imageProcessing-master/matlab_elastix/MelastiX_examples/elastix/example_2D_affine_alpha.m
1,253
utf_8
afae938a8945690eabab520f6723dd18
function varargout=example_2D_affine_alpha % Shows the effect of changing alpha given a fixed number of spatial samples % and iterations. Here we choose relatively low % numbers for the iterations and spatial samples. Affine-transformed moving image. fprintf('\n=====================\nRunning %s\n\n',mfilename) help(mfilename) %Load the data load lena %Plot original data clf colormap gray subplot(2,3,1) imagesc(lena), axis off equal title('Original') %apply an affine transform tform = affine2d([1 0 0; .35 1 0; 0 0 1]); lenaTrans=imwarp(lena,tform); subplot(2,3,2) imagesc(lenaTrans), axis off title('Transformed') drawnow p.Transform='AffineTransform'; p.MaximumNumberOfIterations=400; p.NumberOfSpatialSamples=300; alphas=[0.2, 0.3, 0.4, 0.6]; ind=3; for thisAlpha=alphas p.SP_alpha=thisAlpha; runExampleLena(lenaTrans,lena,p,ind) ind=ind+1; end function runExampleLena(lenaTrans,lena,p,ind) tic fprintf('\nStarting registration\n') paramsReporter(p) reg=elastix(lenaTrans,lena,[],'elastix_default.yml','paramstruct',p); fprintf('Finished registration in %d seconds\n', round(toc)) subplot(2,3,ind) imagesc(reg), axis off equal title(sprintf('CORRECTED: alpha=%0.1f',p.SP_alpha)) set(gca,'Clim',[0,255]) drawnow
github
jacksky64/imageProcessing-master
example_2D_affine_nSpatialSamples.m
.m
imageProcessing-master/matlab_elastix/MelastiX_examples/elastix/example_2D_affine_nSpatialSamples.m
1,279
utf_8
40b6d6511fa402790a963e20194ee275
function example_2D_affine_nSpatialSamples % Shows the effect of changing the number of spatial samples with a % fixed number of iterations. Uses the suggested value for alpha. % Here we choose relatively low numbers for the iterations and spatial % samples. Affine-transformed moving image. help(mfilename) %Load the data load lena %Plot original data clf colormap gray subplot(2,3,1) imagesc(lena), axis off equal title('Original') %apply an affine transform tform = affine2d([1 0 0; .35 1 0; 0 0 1]); lenaTrans=imwarp(lena,tform); subplot(2,3,2) imagesc(lenaTrans), axis off title('Transformed') drawnow p.Transform='AffineTransform'; p.MaximumNumberOfIterations=1.5E3; p.SP_alpha=0.6; %The recomended value nSamples=[50,100,200,500]; ind=3; for theseNSamples=nSamples p.NumberOfSpatialSamples=theseNSamples; runExampleLena(lenaTrans,lena,p,ind) ind=ind+1; end function runExampleLena(lenaTrans,lena,p,ind) tic fprintf('\nStarting registration\n') paramsReporter(p) reg=elastix(lenaTrans,lena,[],'elastix_default.yml','paramstruct',p); fprintf('Finished registration in %d seconds\n', round(toc)) subplot(2,3,ind) imagesc(reg), axis off equal title(sprintf('CORRECTED: %d samples',p.NumberOfSpatialSamples)) drawnow set(gca,'Clim',[0,255])
github
jacksky64/imageProcessing-master
RUN_ALL.m
.m
imageProcessing-master/matlab_elastix/MelastiX_examples/transformix/RUN_ALL.m
261
utf_8
5bac13dff3aba8815f16fb5c849b0332
function RUN_ALL applyLenaTransform2Dog disp('PRESS RETURN') pause %Note: the parameter files are slightly different here so you don't get quite the same image back applyLenaTransform2Dog_withParams disp('PRESS RETURN') pause transformSparsePoints_forward
github
jacksky64/imageProcessing-master
wfb2rec.m
.m
imageProcessing-master/contourlet_toolbox/wfb2rec.m
1,419
utf_8
a8eb98892d022925b472758e34d4640d
function x = wfb2rec(x_LL, x_LH, x_HL, x_HH, h, g) % WFB2REC 2-D Wavelet Filter Bank Decomposition % % x = wfb2rec(x_LL, x_LH, x_HL, x_HH, h, g) % % Input: % x_LL, x_LH, x_HL, x_HH: Four 2-D wavelet subbands % h, g: lowpass analysis and synthesis wavelet filters % % Output: % x: reconstructed image % Make sure filter in a row vector h = h(:)'; g = g(:)'; g0 = g; len_g0 = length(g0); ext_g0 = floor((len_g0 - 1) / 2); % Highpass synthesis filter: G1(z) = -z H0(-z) len_g1 = length(h); c = floor((len_g1 + 1) / 2); g1 = (-1) * h .* (-1) .^ ([1:len_g1] - c); ext_g1 = len_g1 - (c + 1); % Get the output image size [height, width] = size(x_LL); x_B = zeros(height * 2, width); x_B(1:2:end, :) = x_LL; % Column-wise filtering x_L = rowfiltering(x_B', g0, ext_g0)'; x_B(1:2:end, :) = x_LH; x_L = x_L + rowfiltering(x_B', g1, ext_g1)'; x_B(1:2:end, :) = x_HL; x_H = rowfiltering(x_B', g0, ext_g0)'; x_B(1:2:end, :) = x_HH; x_H = x_H + rowfiltering(x_B', g1, ext_g1)'; % Row-wise filtering x_B = zeros(2*height, 2*width); x_B(:, 1:2:end) = x_L; x = rowfiltering(x_B, g0, ext_g0); x_B(:, 1:2:end) = x_H; x = x + rowfiltering(x_B, g1, ext_g1); % Internal function: Row-wise filtering with border handling function y = rowfiltering(x, f, ext1) ext2 = length(f) - ext1 - 1; x = [x(:, end-ext1+1:end) x x(:, 1:ext2)]; y = conv2(x, f, 'valid');
github
jacksky64/imageProcessing-master
wfb2dec.m
.m
imageProcessing-master/contourlet_toolbox/wfb2dec.m
1,359
utf_8
cf0a7abcc9abae631039550460b07a48
function [x_LL, x_LH, x_HL, x_HH] = wfb2dec(x, h, g) % WFB2DEC 2-D Wavelet Filter Bank Decomposition % % y = wfb2dec(x, h, g) % % Input: % x: input image % h, g: lowpass analysis and synthesis wavelet filters % % Output: % x_LL, x_LH, x_HL, x_HH: Four 2-D wavelet subbands % Make sure filter in a row vector h = h(:)'; g = g(:)'; h0 = h; len_h0 = length(h0); ext_h0 = floor(len_h0 / 2); % Highpass analysis filter: H1(z) = -z^(-1) G0(-z) len_h1 = length(g); c = floor((len_h1 + 1) / 2); % Shift the center of the filter by 1 if its length is even. if mod(len_h1, 2) == 0 c = c + 1; end h1 = - g .* (-1).^([1:len_h1] - c); ext_h1 = len_h1 - c + 1; % Row-wise filtering x_L = rowfiltering(x, h0, ext_h0); x_L = x_L(:, 1:2:end); x_H = rowfiltering(x, h1, ext_h1); x_H = x_H(:, 1:2:end); % Column-wise filtering x_LL = rowfiltering(x_L', h0, ext_h0)'; x_LL = x_LL(1:2:end, :); x_LH = rowfiltering(x_L', h1, ext_h1)'; x_LH = x_LH(1:2:end, :); x_HL = rowfiltering(x_H', h0, ext_h0)'; x_HL = x_HL(1:2:end, :); x_HH = rowfiltering(x_H', h1, ext_h1)'; x_HH = x_HH(1:2:end, :); % Internal function: Row-wise filtering with border handling function y = rowfiltering(x, f, ext1) ext2 = length(f) - ext1 - 1; x = [x(:, end-ext1+1:end) x x(:, 1:ext2)]; y = conv2(x, f, 'valid');
github
jacksky64/imageProcessing-master
extend2.m
.m
imageProcessing-master/contourlet_toolbox/extend2.m
1,861
utf_8
40bc6d67909280efd214bb2536a4a46f
function y = extend2(x, ru, rd, cl, cr, extmod) % EXTEND2 2D extension % % y = extend2(x, ru, rd, cl, cr, extmod) % % Input: % x: input image % ru, rd: amount of extension, up and down, for rows % cl, cr: amount of extension, left and rigth, for column % extmod: extension mode. The valid modes are: % 'per': periodized extension (both direction) % 'qper_row': quincunx periodized extension in row % 'qper_col': quincunx periodized extension in column % % Output: % y: extended image % % Note: % Extension modes 'qper_row' and 'qper_col' are used multilevel % quincunx filter banks, assuming the original image is periodic in % both directions. For example: % [y0, y1] = fbdec(x, h0, h1, 'q', '1r', 'per'); % [y00, y01] = fbdec(y0, h0, h1, 'q', '2c', 'qper_col'); % [y10, y11] = fbdec(y1, h0, h1, 'q', '2c', 'qper_col'); % % See also: FBDEC [rx, cx] = size(x); switch extmod case 'per' I = getPerIndices(rx, ru, rd); y = x(I, :); I = getPerIndices(cx, cl, cr); y = y(:, I); case 'qper_row' rx2 = round(rx / 2); y = [[x(rx2+1:rx, cx-cl+1:cx); x(1:rx2, cx-cl+1:cx)], x, ... [x(rx2+1:rx, 1:cr); x(1:rx2, 1:cr)]]; I = getPerIndices(rx, ru, rd); y = y(I, :); case 'qper_col' cx2 = round(cx / 2); y = [x(rx-ru+1:rx, cx2+1:cx), x(rx-ru+1:rx, 1:cx2); x; ... x(1:rd, cx2+1:cx), x(1:rd, 1:cx2)]; I = getPerIndices(cx, cl, cr); y = y(:, I); otherwise error('Invalid input for EXTMOD') end %----------------------------------------------------------------------------% % Internal Function(s) %----------------------------------------------------------------------------% function I = getPerIndices(lx, lb, le) I = [lx-lb+1:lx , 1:lx , 1:le]; if (lx < lb) | (lx < le) I = mod(I, lx); I(I==0) = lx; end
github
jacksky64/imageProcessing-master
phantom3dAniso.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Test_data/Shepp_logan/phantom3dAniso.m
9,551
utf_8
036a548fce8cb3deec7807cf87f39f45
function [p,ellipse]=phantom3dAniso(varargin) %PHANTOM3D Three-dimensional analogue of MATLAB Shepp-Logan phantom % P = PHANTOM3D(DEF,N) generates a 3D head phantom that can % be used to test 3-D reconstruction algorithms. % % DEF is a string that specifies the type of head phantom to generate. % Valid values are: % % 'Shepp-Logan' A test image used widely by researchers in % tomography % 'Modified Shepp-Logan' (default) A variant of the Shepp-Logan phantom % in which the contrast is improved for better % visual perception. % 'yu-ye-wang' Another version of the modified Shepp-Logan % phantom from "Katsevich-Type Algorithms for % Variable Radius Spiral Cone-BeamCT" % % N specifies the 3D grid size of P % If N is a scalar, P will have isotropic size [N, N, N] % If N is a 3-vector, P will have size [N(1) N(2) N(3)] % If you omit the argument, N defaults to [64 64 64]. % % P = PHANTOM3D(E,N) generates a user-defined phantom, where each row % of the matrix E specifies an ellipsoid in the image. E has ten columns, % with each column containing a different parameter for the ellipsoids: % % Column 1: A the additive intensity value of the ellipsoid % Column 2: a the length of the x semi-axis of the ellipsoid % Column 3: b the length of the y semi-axis of the ellipsoid % Column 4: c the length of the z semi-axis of the ellipsoid % Column 5: x0 the x-coordinate of the center of the ellipsoid % Column 6: y0 the y-coordinate of the center of the ellipsoid % Column 7: z0 the z-coordinate of the center of the ellipsoid % Column 8: phi phi Euler angle (in degrees) (rotation about z-axis) % Column 9: theta theta Euler angle (in degrees) (rotation about x-axis) % Column 10: psi psi Euler angle (in degrees) (rotation about z-axis) % % For purposes of generating the phantom, the domains for the x-, y-, and % z-axes span [-1,1]. Columns 2 through 7 must be specified in terms % of this range. % % [P,E] = PHANTOM3D(...) returns the matrix E used to generate the phantom. % % Class Support % ------------- % All inputs must be of class double. All outputs are of class double. % % Remarks % ------- % For any given voxel in the output image, the voxel's value is equal to the % sum of the additive intensity values of all ellipsoids that the voxel is a % part of. If a voxel is not part of any ellipsoid, its value is 0. % % The additive intensity value A for an ellipsoid can be positive or negative; % if it is negative, the ellipsoid will be darker than the surrounding pixels. % Note that, depending on the values of A, some voxels may have values outside % the range [0,1]. % % Example % ------- % ph = phantom3d(128); % figure, imshow(squeeze(ph(64,:,:))) % % Copyright 2005 Matthias Christian Schabel (matthias @ stanfordalumni . org) % University of Utah Department of Radiology % Utah Center for Advanced Imaging Research % 729 Arapeen Drive % Salt Lake City, UT 84108-1218 % % This code is released under the Gnu Public License (GPL). For more information, % see : http://www.gnu.org/copyleft/gpl.html % % Portions of this code are based on phantom.m, copyrighted by the Mathworks % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Modification May 25, 2015, by Patrick J. Bolan, University of Minnesota % Added support for anisotropic phantom sizes: the phantom size can now be % a vector. % [ellipse,n] = parse_inputs(varargin{:}); nx = n(1); ny = n(2); nz = n(3); p = zeros([nx ny nz]); rngx = ( (0:nx-1)-(nx-1)/2 ) / ((nx-1)/2); rngy = ( (0:ny-1)-(ny-1)/2 ) / ((ny-1)/2); rngz = ( (0:nz-1)-(nz-1)/2 ) / ((nz-1)/2); % PJB: Note the swap of the x and y with meshgrid parameters. %[x,y,z] = meshgrid(rngx,rngy,rngz); [x,y,z] = meshgrid(rngy,rngx,rngz); coord = [flatten(x); flatten(y); flatten(z)]; p = flatten(p); for k = 1:size(ellipse,1) A = ellipse(k,1); % Amplitude change for this ellipsoid asq = ellipse(k,2)^2; % a^2 bsq = ellipse(k,3)^2; % b^2 csq = ellipse(k,4)^2; % c^2 x0 = ellipse(k,5); % x offset y0 = ellipse(k,6); % y offset z0 = ellipse(k,7); % z offset phi = ellipse(k,8)*pi/180; % first Euler angle in radians theta = ellipse(k,9)*pi/180; % second Euler angle in radians psi = ellipse(k,10)*pi/180; % third Euler angle in radians cphi = cos(phi); sphi = sin(phi); ctheta = cos(theta); stheta = sin(theta); cpsi = cos(psi); spsi = sin(psi); % Euler rotation matrix alpha = [cpsi*cphi-ctheta*sphi*spsi cpsi*sphi+ctheta*cphi*spsi spsi*stheta; -spsi*cphi-ctheta*sphi*cpsi -spsi*sphi+ctheta*cphi*cpsi cpsi*stheta; stheta*sphi -stheta*cphi ctheta]; % rotated ellipsoid coordinates coordp = alpha*coord; idx = find((coordp(1,:)-x0).^2./asq + (coordp(2,:)-y0).^2./bsq + (coordp(3,:)-z0).^2./csq <= 1); p(idx) = p(idx) + A; end %p = reshape(p,[nx ny nz]); p = reshape(p, [nx ny nz]); return; function out = flatten(in) out = reshape(in,[1 numel(in)]); return; function [e,n] = parse_inputs(varargin) % e is the m-by-10 array which defines ellipsoids % n is a 3-vector with the size of the phantom brain image, [nx ny nz] n = [64 64 64]; % The default size e = []; defaults = {'shepp-logan', 'modified shepp-logan', 'yu-ye-wang'}; for i=1:nargin if ischar(varargin{i}) % Look for a default phantom def = varargin{i}; idx = strcmpi(def, defaults); if isempty(idx) eid = sprintf('Images:%s:unknownPhantom',mfilename); msg = 'Unknown default phantom selected.'; error(eid,'%s',msg); end switch defaults{idx} case 'shepp-logan' e = shepp_logan; case 'modified shepp-logan' e = modified_shepp_logan; case 'yu-ye-wang' e = yu_ye_wang; end elseif numel(varargin{i})==1 n = [varargin{i} varargin{i} varargin{i}]; % a scalar is the image size elseif numel(varargin{i})==3 siz = varargin{i}; n = [siz(1) siz(2) siz(3)]; % 3 integers specify image dimensions elseif ndims(varargin{i})==2 && size(varargin{i},2)==10 e = varargin{i}; % user specified phantom else eid = sprintf('Images:%s:invalidInputArgs',mfilename); msg = 'Invalid input arguments.'; error(eid,'%s',msg); end end % ellipse is not yet defined if isempty(e) e = modified_shepp_logan; end return; %%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Default head phantoms: % %%%%%%%%%%%%%%%%%%%%%%%%%%%%% function e = shepp_logan e = modified_shepp_logan; e(:,1) = [1 -.98 -.02 -.02 .01 .01 .01 .01 .01 .01]; return; function e = modified_shepp_logan % % This head phantom is the same as the Shepp-Logan except % the intensities are changed to yield higher contrast in % the image. Taken from Toft, 199-200. % % A a b c x0 y0 z0 phi theta psi % ----------------------------------------------------------------- e = [ 1 .6900 .920 .810 0 0 0 0 0 0 -.8 .6624 .874 .780 0 -.0184 0 0 0 0 -.2 .1100 .310 .220 .22 0 0 -18 0 10 -.2 .1600 .410 .280 -.22 0 0 18 0 10 .1 .2100 .250 .410 0 .35 -.15 0 0 0 .1 .0460 .046 .050 0 .1 .25 0 0 0 .1 .0460 .046 .050 0 -.1 .25 0 0 0 .1 .0460 .023 .050 -.08 -.605 0 0 0 0 .1 .0230 .023 .020 0 -.606 0 0 0 0 .1 .0230 .046 .020 .06 -.605 0 0 0 0 ]; return; function e = yu_ye_wang % % Yu H, Ye Y, Wang G, Katsevich-Type Algorithms for Variable Radius Spiral Cone-Beam CT % % A a b c x0 y0 z0 phi theta psi % ----------------------------------------------------------------- e = [ 1 .6900 .920 .900 0 0 0 0 0 0 -.8 .6624 .874 .880 0 0 0 0 0 0 -.2 .4100 .160 .210 -.22 0 -.25 108 0 0 -.2 .3100 .110 .220 .22 0 -.25 72 0 0 .2 .2100 .250 .500 0 .35 -.25 0 0 0 .2 .0460 .046 .046 0 .1 -.25 0 0 0 .1 .0460 .023 .020 -.08 -.65 -.25 0 0 0 .1 .0460 .023 .020 .06 -.65 -.25 90 0 0 .2 .0560 .040 .100 .06 -.105 .625 90 0 0 -.2 .0560 .056 .100 0 .100 .625 0 0 0 ]; return;
github
jacksky64/imageProcessing-master
plotgeometry.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Utilities/plotgeometry.m
2,673
utf_8
d2f582a908d999c8a1ed7960aabd9b7c
function h=plotgeometry(geo,angle) %PLOTGEOMETRY(GEO,ANGLE) plots a simplified version of the CBCT geometry with the % given geomerty GEO and angle ANGLE. If angle is nnot Give, 0 will be chosen. % % h=PLOTGEOMETRY(...) will return the figure handle %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- if nargin<2 angle=0; end angle=angle*180/pi; %% Figure stuff h=figure('Name','Cone Beam Compute Tomography geometry'); hold on title('Current CBCT geometry, in scale') xlabel('X'); ylabel('Y'); zlabel('Z'); set(gcf, 'color', [1 1 1]) %% CUBE/Image drawCube(geo.offOrigin,geo.sVoxel,'k',0.05,0); %% Detector drawCube([-geo.DSD+geo.DSO; geo.offDetector],[1; geo.sDetector],'r',1,angle) plotCircle3D([0 0 0],-geo.DSD+geo.DSO); %% source p=plot3(geo.DSO,0,0,'.','MarkerSize',30); rotate(p,[0 0 1],angle,[0 0 0]); plotCircle3D([0 0 0],geo.DSO); %% Arrows. arrow=geo.sVoxel; %XYZ arrows try arrow3d([0 arrow(1)],[0 0],[0 0],.90,5,15,'r'); arrow3d([0 0],[0 arrow(2)],[0 0],.90,5,15,'b'); arrow3d([0 0],[0 0],[0 arrow(3)],.90,5,15,'g'); catch e error('CBCT:plotgeometry:Arrow','arrow3D not found, make sure its added to the path'); end %UV arrows %% axis equal; view(128,26) % grid on % axis off; end function drawCube( origin, size,color,alpha,a) % From % http://www.mathworks.com/matlabcentral/newsreader/view_thread/235581 x=([0 1 1 0 0 0;1 1 0 0 1 1;1 1 0 0 1 1;0 1 1 0 0 0]-0.5)*size(1)+origin(1); y=([0 0 1 1 0 0;0 1 1 0 0 0;0 1 1 0 1 1;0 0 1 1 1 1]-0.5)*size(2)+origin(2); z=([0 0 0 0 0 1;0 0 0 0 0 1;1 1 1 1 0 1;1 1 1 1 0 1]-0.5)*size(3)+origin(3); for i=1:6 h=patch(x(:,i),y(:,i),z(:,i),color); set(h,'facealpha',alpha) rotate(h,[0 0 1],a,[0 0 0]); end end function plotCircle3D(center,radius) theta=0:0.1:2*pi; v=null([0 0 1]); points=repmat(center',1,size(theta,2))+radius*(v(:,1)*cos(theta)+v(:,2)*sin(theta)); plot3(points(1,:),points(2,:),points(3,:),'k-.'); end
github
jacksky64/imageProcessing-master
gradientTVnorm.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Utilities/gradientTVnorm.m
3,706
utf_8
f5ee0ee596c4040081cdc6897a9f6175
function [ tvgrad ] = gradientTVnorm(f,type) %GRADIENTTVNORM Computes the gradient of the TV-norm fucntional %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- if strcmp(type,'central') warning('It seems that central does not give correct results. Please consider using back or forward') tvgrad= gradientTVnormCentral(f); return; end if strcmp(type,'backward') tvgrad= gradientTVnormBackward(f); return; end if strcmp(type,'forward') tvgrad= gradientTVnormForward(f); return; end error('Undefined type of gradient. Check spelling'); end %% Backward differences function tvg=gradientTVnormBackward(f) Gx=diff(f,1,1); Gy=diff(f,1,2); Gz=diff(f,1,3); tvg=zeros(size(f)); clear f % these are not defined, but we will define them just for indexing % readability. They shoudl never be used. Gx=cat(1,zeros(size(Gx(1,:,:))),Gx); Gy=cat(2,zeros(size(Gy(:,1,:))),Gy); Gz=cat(3,zeros(size(Gz(:,:,1))),Gz); nrm=safenorm(Gx,Gy,Gz); tvg(1:end,1:end,1:end)= tvg(1:end,1:end,1:end)+(Gx(1:end,1:end,1:end)+Gy(1:end,1:end,1:end)+Gz(1:end,1:end,1:end))./nrm(1:end,1:end,1:end); tvg(2:end-1,:,:)=tvg(2:end-1,:,:)-Gx([2:end-1]+1,:,:)./nrm([2:end-1]+1,:,:); tvg(:,2:end-1,:)=tvg(:,2:end-1,:)-Gy(:,[2:end-1]+1,:)./nrm(:,[2:end-1]+1,:); tvg(:,:,2:end-1)=tvg(:,:,2:end-1)-Gz(:,:,[2:end-1]+1)./nrm(:,:,[2:end-1]+1); end %% Forward differences function tvg=gradientTVnormForward(f) Gx=diff(f,1,1); Gy=diff(f,1,2); Gz=diff(f,1,3); tvg=zeros(size(f)); clear f % these are not defined, but we will define them just for indexing % readability. They shoudl never be used. Gx=cat(1,Gx,zeros(size(Gx(end,:,:)))); Gy=cat(2,Gy,zeros(size(Gy(:,end,:)))); Gz=cat(3,Gz,zeros(size(Gz(:,:,end)))); nrm=safenorm(Gx,Gy,Gz); tvg(1:end-1,1:end-1,1:end-1)=tvg(1:end-1,1:end-1,1:end-1)-(Gx(1:end-1,1:end-1,1:end-1)+Gy(1:end-1,1:end-1,1:end-1)+Gz(1:end-1,1:end-1,1:end-1))./nrm(1:end-1,1:end-1,1:end-1); tvg(2:end-1,:,:)=tvg(2:end-1,:,:)+Gx([2:end-1]-1,:,:)./nrm([2:end-1]-1,:,:); tvg(:,2:end-1,:)=tvg(:,2:end-1,:)+Gy(:,[2:end-1]-1,:)./nrm(:,[2:end-1]-1,:); tvg(:,:,2:end-1)=tvg(:,:,2:end-1)+Gz(:,:,[2:end-1]-1)./nrm(:,:,[2:end-1]-1); end %% Central differences % Doesnt accound for edges of the image!!! % https://math.stackexchange.com/questions/1612017/gradient-of-the-tv-norm-of-an-image function tvg=gradientTVnormCentral(f) [Gx,Gy,Gz]=gradient(f); tvg=zeros(size(Gx)); nrm=safenorm(Gx,Gy,Gz); tvg(2:end,:,:) = tvg(2:end,:,:) + Gx(1:end-1,:,:)./nrm(1:end-1,:,:); tvg(1:end-1,:,:) = tvg(1:end-1,:,:) - Gx(2:end,:,:) ./nrm(2:end,:,:); tvg(:,2:end,:) = tvg(:,2:end,:) + Gy(:,1:end-1,:)./nrm(:,1:end-1,:); tvg(:,1:end-1,:) = tvg(:,1:end-1,:) - Gy(:,2:end,:) ./nrm(:,2:end,:); tvg(:,:,2:end) = tvg(:,:,2:end) + Gz(:,:,1:end-1)./nrm(:,:,1:end-1); tvg(:,:,1:end-1) = tvg(:,:,1:end-1) - Gz(:,:,2:end) ./nrm(:,:,2:end); tvg = tvg/2; end %% Utils function nrm=safenorm(Gx,Gy,Gz) nrm=sqrt(Gx.^2+Gy.^2+Gz.^2)+0.00000001; nrm(nrm==0)=1; end
github
jacksky64/imageProcessing-master
filtering.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Utilities/filtering.m
2,822
utf_8
c1ba4fc67ad21176c4870f7bb4043653
function [ proj ] = filtering(proj,geo,alpha) %FILTERING Summary of this function goes here % Detailed explanation goes here %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % and % https://www.mathworks.com/matlabcentral/fileexchange/view_license?file_info_id=35548 % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Kyungsang Kim, modified by Ander Biguri %-------------------------------------------------------------------------- filt_len = max(64,2^nextpow2(2*geo.nDetector(1))); [ramp_kernel] = ramp_flat(filt_len); d = 1; % cut off (0~1) [filt] = Filter(geo.filter, ramp_kernel, filt_len, d); filt = repmat(filt',[1 geo.nDetector(2)]); for ii=1:length(alpha) fproj = (zeros(filt_len,geo.nDetector(2),'single')); fproj(filt_len/2-geo.nDetector(1)/2+1:filt_len/2+geo.nDetector(1)/2,:) = proj(:,:,ii); fproj = fft(fproj); fproj = fproj.*filt; fproj = (real(ifft(fproj))); proj(:,:,ii) = fproj(end/2-geo.nDetector(1)/2+1:end/2+geo.nDetector(1)/2,:)/2/geo.dDetector(1)*(2*pi/ length(alpha) )/2*(geo.DSD/geo.DSO); end proj=permute(proj,[2 1 3]); end function [h, nn] = ramp_flat(n) nn = [-(n/2):(n/2-1)]'; h = zeros(size(nn),'single'); h(n/2+1) = 1 / 4; odd = mod(nn,2) == 1; h(odd) = -1 ./ (pi * nn(odd)).^2; end function [filt] = Filter(filter, kernel, order, d) f_kernel = abs(fft(kernel))*2; filt = f_kernel(1:order/2+1)'; w = 2*pi*(0:size(filt,2)-1)/order; % frequency axis up to Nyquist switch lower(filter) case 'ram-lak' % Do nothing case 'shepp-logan' % be careful not to divide by 0: filt(2:end) = filt(2:end) .* (sin(w(2:end)/(2*d))./(w(2:end)/(2*d))); case 'cosine' filt(2:end) = filt(2:end) .* cos(w(2:end)/(2*d)); case 'hamming' filt(2:end) = filt(2:end) .* (.54 + .46 * cos(w(2:end)/d)); case 'hann' filt(2:end) = filt(2:end) .*(1+cos(w(2:end)./d)) / 2; otherwise disp(filter); error('Invalid filter selected.'); end filt(w>pi*d) = 0; % Crop the frequency response filt = [filt , filt(end-1:-1:2)]; % Symmetry of the filter return end
github
jacksky64/imageProcessing-master
read_mhd.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Third_party_tools/readMHD/read_mhd.m
6,151
utf_8
12ac2204991d25ed251aac90e2dd41f9
function [img info]=read_mhd(filename) % This function is based upon "read_mhd" function from the package % ReadData3D_version1 from the matlab exchange. % Copyright (c) 2010, Dirk-Jan Kroon % [image info ] = read_mhd(filename) info = mhareadheader(filename); [path name extension] = fileparts(filename); if (isfield(info,'ElementNumberOfChannels')) ndims = str2num(info.ElementNumberOfChannels); else ndims = 1; end img = ImageType(); if (ndims == 1) data = read_raw([ path filesep info.DataFile ], info.Dimensions,info.DataType,'native',0,ndims); img=ImageType(size(data),info.Offset',info.PixelDimensions',reshape(info.TransformMatrix,numel(info.PixelDimensions),numel(info.PixelDimensions))); img.data = data; elseif (ndims == 3) clear img; [datax datay dataz] = read_raw([ path filesep info.DataFile], info.Dimensions,info.DataType,'native',0,ndims); img = VectorImageType(size(datax),info.Offset',info.PixelDimensions',reshape(info.TransformMatrix,numel(info.PixelDimensions),numel(info.PixelDimensions))); img.datax = datax; clear datax; img.datay=datay; clear datay; img.dataz = dataz; clear dataz; img.data = img.datax.^2+img.datay.^2+img.dataz.^2; end end function [rawData rdy rdz] =read_raw(filename,imSize,type,endian,skip,ndims) % Reads a raw file % Inputs: filename, image size, image type, byte ordering, skip % If you are using an offset to access another slice of the volume image % be sure to multiply your skip value by the number of bytes of the % type (ie. float is 4 bytes). % Inputs: filename, image size, pixel type, endian, number of values to % skip. % Output: image rdy=[]; rdz=[]; fid = fopen(filename,'rb',endian); if (fid < 0) display(['Filename ' filename ' does not exist']); rawData = -1; else if (ndims == 1) status = fseek(fid,skip,'bof'); if status == 0 rawData = fread(fid,prod(imSize),type); fclose(fid); rawData = reshape(rawData,imSize); else rawData = status; end else %disp('Vector Image'); status = fseek(fid,skip,'bof'); if status == 0 r = fread(fid,prod(imSize)*3,type); fclose(fid); if length(imSize) == 3 % slices = length(r)/imSize(1)/imSize(2)/3;% 3 for vx, vy, vz % imSize(3) = slices; % imSize(4) = 3; im_size=[ 3 imSize([1 2 3]) ]; elseif length(imSize) == 4 im_size=[3 imSize([1 2 3 4]) ]; end r = reshape(r,im_size); else r = status; end if length(imSize) == 3 rawData=squeeze(r(1,:,:,:)); rdy=squeeze(r(2,:,:,:)); rdz=squeeze(r(3,:,:,:)); elseif length(imSize) == 4 rawData=squeeze(r(1,:,:,:,:)); rdy=squeeze(r(2,:,:,:,:)); rdz=squeeze(r(3,:,:,:,:)); end end end end function info =mhareadheader(filename) % Function for reading the header of a Insight Meta-Image (.mha,.mhd) file % % info = mha_read_header(filename); % % examples: % 1, info=mha_read_header() % 2, info=mha_read_header('volume.mha'); info = []; if(exist('filename','var')==0) [filename, pathname] = uigetfile('*.mha', 'Read mha-file'); filename = [pathname filename]; end fid=fopen(filename,'rb'); if(fid<0) fprintf('could not open file %s\n',filename); return end info.Filename=filename; info.Format='MHA'; info.CompressedData='false'; readelementdatafile=false; while(~readelementdatafile) str=fgetl(fid); s=find(str=='=',1,'first'); if(~isempty(s)) type=str(1:s-1); data=str(s+1:end); while(type(end)==' '); type=type(1:end-1); end while(data(1)==' '); data=data(2:end); end else type=''; data=str; end switch(lower(type)) case 'ndims' info.NumberOfDimensions=sscanf(data, '%d')'; case 'dimsize' info.Dimensions=sscanf(data, '%d')'; case 'elementspacing' info.PixelDimensions=sscanf(data, '%lf')'; case 'elementsize' info.ElementSize=sscanf(data, '%lf')'; if(~isfield(info,'PixelDimensions')) info.PixelDimensions=info.ElementSize; end case 'elementbyteordermsb' info.ByteOrder=lower(data); case 'anatomicalorientation' info.AnatomicalOrientation=data; case 'centerofrotation' info.CenterOfRotation=sscanf(data, '%lf')'; case 'offset' info.Offset=sscanf(data, '%lf')'; case 'binarydata' info.BinaryData=lower(data); case 'compresseddatasize' info.CompressedDataSize=sscanf(data, '%d')'; case 'objecttype', info.ObjectType=lower(data); case 'transformmatrix' info.TransformMatrix=sscanf(data, '%lf')'; case 'compresseddata'; info.CompressedData=lower(data); case 'binarydatabyteordermsb' info.ByteOrder=lower(data); case 'elementdatafile' info.DataFile=data; readelementdatafile=true; case 'elementtype' info.DataType=lower(data(5:end)); case 'headersize' val=sscanf(data, '%d')'; if(val(1)>0), info.HeaderSize=val(1); end otherwise info.(type)=data; end end switch(info.DataType) case 'char', info.BitDepth=8; case 'uchar', info.BitDepth=8; case 'short', info.BitDepth=16; case 'ushort', info.BitDepth=16; case 'int', info.BitDepth=32; case 'uint', info.BitDepth=32; case 'float', info.BitDepth=32; case 'double', info.BitDepth=64; otherwise, info.BitDepth=0; end if(~isfield(info,'HeaderSize')) info.HeaderSize=ftell(fid); end fclose(fid); end
github
jacksky64/imageProcessing-master
secs2hms.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Third_party_tools/sec2hours/secs2hms.m
1,080
utf_8
8e95082e182b573d2719d1a2ff66f315
%SECS2HMS - converts a time in seconds to a string giving the time in hours, minutes and second %Usage TIMESTRING = SECS2HMS(TIME)]); %Example 1: >> secs2hms(7261) %>> ans = 2 hours, 1 min, 1.0 sec %Example 2: >> tic; pause(61); disp(['program took ' secs2hms(toc)]); %>> program took 1 min, 1.0 secs function time_string=secs2hms(time_in_secs) time_string=''; nhours = 0; nmins = 0; if time_in_secs >= 3600 nhours = floor(time_in_secs/3600); if nhours > 1 hour_string = ' hours, '; else hour_string = ' hour, '; end time_string = [num2str(nhours) hour_string]; end if time_in_secs >= 60 nmins = floor((time_in_secs - 3600*nhours)/60); if nmins > 1 minute_string = ' mins, '; else minute_string = ' min, '; end time_string = [time_string num2str(nmins) minute_string]; end nsecs = time_in_secs - 3600*nhours - 60*nmins; time_string = [time_string sprintf('%2.1f', nsecs) ' secs']; end
github
jacksky64/imageProcessing-master
SIRT.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/SIRT.m
10,299
utf_8
bf9a3cfb8b29671c442d63bfb4d7c8d6
function [res,errorL2,qualMeasOut]=SIRT(proj,geo,angles,niter,varargin) % SIRT_CBCT solves Cone Beam CT image reconstruction using Oriented Subsets % Simultaneous Algebraic Reconxtruction Techique algorithm % % SIRT_CBCT(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % SIRT_CBCT(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % % 'lambda': Sets the value of the hyperparameter. Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.95 % % 'Init': Describes diferent initialization techniques. % 'none' : Initializes the image to zeros (default) % 'FDK' : intializes image to FDK reconstrucition % 'multigrid': Initializes image by solving the problem in % small scale and increasing it when relative % convergence is reached. % 'image' : Initialization using a user specified % image. Not recomended unless you really % know what you are doing. % 'InitImg' an image for the 'image' initialization. Avoid. % % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. % 'QualMeas' Asks the algorithm for a set of quality measurement % parameters. Input should contain a cell array of desired % quality measurement names. Example: {'CC','RMSE','MSSIM'} % These will be computed in each iteration. %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- %% Deal with input parameters [lambda,res,lamdbared,verbose,QualMeasOpts]=parse_inputs(proj,geo,angles,varargin); measurequality=~isempty(QualMeasOpts); if nargout>1 computeL2=true; else computeL2=false; end errorL2=[]; %% initialize stuff %% Create weigthing matrices % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; clear geoaux; % Back-Projection weigth, V if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; V=single(sum(V,3)); else V=ones([geo.nVoxel(1:2).'],'single')*length(angles); end clear A x y dx dz; %% Iterate errorL2=[]; % TODO : Add options for Stopping criteria for ii=1:niter if (ii==1 && verbose==1);tic;end % If quality is going to be measured, then we need to save previous image % THIS TAKES MEMORY! if measurequality res_prev=res; end % --------- Memory expensive----------- % proj_err=proj-Ax(res,geo,angles); % (b-Ax) % weighted_err=W.*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,angles); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./V,backprj); % V * At * W^-1 * (b-Ax) % res=res+lambda*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) % ------------------------------------ % --------- Memory cheap(er)----------- res=res+lambda*bsxfun(@times,1./V,Atb(W.*(proj-Ax(res,geo,angles)),geo,angles)); % x= x + lambda * V * At * W^-1 * (b-Ax) % ------------------------------------ res(res<0)=0; % If quality is being measured if measurequality % HERE GOES qualMeasOut(:,ii)=Measure_Quality(res_prev,res,QualMeasOpts); end if computeL2 errornow=im3Dnorm(proj-Ax(res,geo,angles),'L2'); % Compute error norm2 of b-Ax % If the error is not minimized. if ii~=1 && errornow>errorL2(end) if verbose disp(['Convergence criteria met, exiting on iteration number:', num2str(ii)]); end return; end errorL2=[errorL2 errornow]; end lambda=lambda*lamdbared; if (ii==1 && verbose==1); expected_time=toc*niter; disp('SIRT'); disp(['Expected duration : ',secs2hms(expected_time)]); disp(['Exected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function initres=init_multigrid(proj,geo,alpha) finalsize=geo.nVoxel; % start with 64 geo.nVoxel=[64;64;64]; geo.dVoxel=geo.sVoxel./geo.nVoxel; if any(finalsize<geo.nVoxel) initres=zeros(finalsize'); return; end niter=100; initres=zeros(geo.nVoxel'); while ~isequal(geo.nVoxel,finalsize) % solve subsampled grid initres=SIRT(proj,geo,alpha,niter,'Init','image','InitImg',initres,'Verbose',0); % Get new dims. geo.nVoxel=geo.nVoxel*2; geo.nVoxel(geo.nVoxel>finalsize)=finalsize(geo.nVoxel>finalsize); geo.dVoxel=geo.sVoxel./geo.nVoxel; % Upsample! % (hopefully computer has enough memory............) [y, x, z]=ndgrid(linspace(1,size(initres,1),geo.nVoxel(1)),... linspace(1,size(initres,2),geo.nVoxel(2)),... linspace(1,size(initres,3),geo.nVoxel(3))); initres=interp3(initres,x,y,z); clear x y z end end function [lambda,res,lamdbared,verbose,QualMeasOpts]=parse_inputs(proj,geo,alpha,argin) opts= {'lambda','Init','InitImg','Verbose','lambdaRed','QualMeas'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:SIRT:InvalidInput','Invalid number of inputs') end % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extranc value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end switch opt % % % % % % % Verbose case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % % % % % % % hyperparameter, LAMBDA case 'lambda' if default lambda=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:SIRT:InvalidInput','Invalid lambda') end lambda=val; end case 'lambdaRed' if default lamdbared=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:SIRT:InvalidInput','Invalid lambda') end lamdbared=val; end case 'Init' res=[]; if default || strcmp(val,'none') res=zeros(geo.nVoxel','single'); continue; end if strcmp(val,'FDK') res=FDK_CBCT(proj,geo,alpha); continue; end if strcmp(val,'multigrid') res=init_multigrid(proj,geo,alpha); continue; end if strcmp(val,'image') initwithimage=1; continue; end if isempty(res) error('CBCT:SIRT:InvalidInput','Invalid Init option') end % % % % % % % ERROR case 'InitImg' if default continue; end if exist('initwithimage','var'); if isequal(size(val),geo.nVoxel'); res=single(val); else error('CBCT:SIRT:InvalidInput','Invalid image for initialization'); end end case 'QualMeas' if default QualMeasOpts={}; else if iscellstr(val) QualMeasOpts=val; else error('CBCT:SIRT:InvalidInput','Invalid quality measurement parameters'); end end otherwise error('CBCT:SIRT:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in SIRT()']); end end end
github
jacksky64/imageProcessing-master
OS_SART.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/OS_SART.m
13,009
utf_8
40c86c320744ac6e9d1cdebebeffc810
function [res,errorL2,qualMeasOut]=OS_SART(proj,geo,angles,niter,varargin) % OS_SART_CBCT solves Cone Beam CT image reconstruction using Oriented Subsets % Simultaneous Algebraic Reconxtruction Techique algorithm % % OS_SART_CBCT(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % OS_SART_CBCT(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % 'BlockSize': Sets the projection block size used simultaneously. If % BlockSize = 1 OS-SART becomes SART and if BlockSize = length(alpha) % then OS-SART becomes SIRT. Default is 20. % % 'lambda': Sets the value of the hyperparameter. Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.95 % % 'Init': Describes diferent initialization techniques. % 'none' : Initializes the image to zeros (default) % 'FDK' : intializes image to FDK reconstrucition % 'multigrid': Initializes image by solving the problem in % small scale and increasing it when relative % convergence is reached. % 'image' : Initialization using a user specified % image. Not recomended unless you really % know what you are doing. % 'InitImg' an image for the 'image' initialization. Aviod. % % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. % 'QualMeas' Asks the algorithm for a set of quality measurement % parameters. Input should contain a cell array of desired % quality measurement names. Example: {'CC','RMSE','MSSIM'} % These will be computed in each iteration. % 'OrderStrategy' Chooses the subset ordering strategy. Options are % 'ordered' :uses them in the input order, but divided % 'random' : orders them randomply % 'angularDistance': chooses the next subset with the % biggest angular distance with the ones used. % % OUTPUTS: % % [img] will output the reconstructed image % [img,errorL2] will output the L2 norm of the residual % (the function being minimized) % [img,errorL2,qualMeas] will output the quality measurements asked % by the input 'QualMeas' % %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- %% Deal with input parameters [blocksize,lambda,res,lamdbared,verbose,QualMeasOpts,OrderStrategy]=parse_inputs(proj,geo,angles,varargin); measurequality=~isempty(QualMeasOpts); if nargout>1 computeL2=true; else computeL2=false; end %% weigth matrices % first order the projection angles [alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy); % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; % Back-Projection weigth, V if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; V=single(V); else V=ones([geo.nVoxel(1:2).',length(angles)],'single'); end clear A x y dx dz; %% Iterate errorL2=[]; offOrigin=geo.offOrigin; offDetector=geo.offDetector; % TODO : Add options for Stopping criteria for ii=1:niter % If verbose, time the algorithm if (ii==1 && verbose==1);tic;end % If quality is going to be measured, then we need to save previous image % THIS TAKES MEMORY! if measurequality res_prev=res; end for jj=1:length(alphablocks); % Get offsets if size(offOrigin,2)==length(angles) geo.offOrigin=offOrigin(:,orig_index{jj}); end if size(offDetector,2)==length(angles) geo.offDetector=offDetector(:,orig_index{jj}); end %proj is data: b=Ax %res= initial image is zero (default) % proj_err=proj(:,:,orig_index{jj})-Ax(res,geo,alphablocks{jj},'interpolated'); % (b-Ax) % weighted_err=W(:,:,orig_index{jj}).*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,alphablocks{jj},'FDK'); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./sum(V(:,:,orig_index{jj}),3),backprj); % V * At * W^-1 * (b-Ax) % res=res+lambda*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) res=res+lambda* bsxfun(@times,1./sum(V(:,:,orig_index{jj}),3),Atb(W(:,:,orig_index{jj}).*(proj(:,:,orig_index{jj})-Ax(res,geo,alphablocks{jj})),geo,alphablocks{jj})); % Non-negativity constrain res(res<0)=0; end % If quality is being measured if measurequality %Can save quality measure for every iteration here %See if some image quality measure should be used for every %iteration? qualMeasOut(:,ii)=Measure_Quality(res_prev,res,QualMeasOpts); end % reduce hyperparameter lambda=lambda*lamdbared; if computeL2 % Compute error norm2 of b-Ax geo.offOrigin=offOrigin; geo.offDetector=offDetector; errornow=im3Dnorm(proj-Ax(res,geo,angles,'ray-voxel'),'L2'); % If the error is not minimized if ii~=1 && errornow>errorL2(end) % This 1.1 is for multigrid, we need to focus to only that case if verbose disp(['Convergence criteria met, exiting on iteration number:', num2str(ii)]); end return; end % Store Error errorL2=[errorL2 errornow]; end % If timing was asked if ii==1 && verbose==1 expected_time=toc*(niter-1); expected_duration=toc*(niter); disp('OS-SART'); disp(['Expected duration : ',secs2hms(expected_duration)]); disp(['Expected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function initres=init_multigrid(proj,geo,alpha) finalsize=geo.nVoxel; % start with 64 geo.nVoxel=[64;64;64]; geo.dVoxel=geo.sVoxel./geo.nVoxel; if any(finalsize<geo.nVoxel) initres=zeros(finalsize'); return; end niter=100; nblock=20; initres=zeros(geo.nVoxel'); while ~isequal(geo.nVoxel,finalsize) % solve subsampled grid initres=OS_SART(proj,geo,alpha,niter,'BlockSize',nblock,'Init','image','InitImg',initres,'Verbose',0); % Get new dims. geo.nVoxel=geo.nVoxel*2; geo.nVoxel(geo.nVoxel>finalsize)=finalsize(geo.nVoxel>finalsize); geo.dVoxel=geo.sVoxel./geo.nVoxel; % Upsample! % (hopefully computer has enough memory............) [y, x, z]=ndgrid(linspace(1,size(initres,1),geo.nVoxel(1)),... linspace(1,size(initres,2),geo.nVoxel(2)),... linspace(1,size(initres,3),geo.nVoxel(3))); initres=interp3(initres,x,y,z); clear x y z end end %% Parse inputs function [block_size,lambda,res,lamdbared,verbose,QualMeasOpts,OrderStrategy]=parse_inputs(proj,geo,alpha,argin) opts= {'BlockSize','lambda','Init','InitImg','Verbose','lambdaRed','QualMeas','OrderStrategy'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:OS-SART:InvalidInput','Invalid number of inputs') end % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extranc value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end switch opt % % % % % % % Verbose case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % % % % % % % hyperparameter, LAMBDA case 'lambda' if default lambda=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:OS_SART_CBCT:InvalidInput','Invalid lambda') end lambda=val; end case 'lambdaRed' if default lamdbared=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:OS_SART_CBCT:InvalidInput','Invalid lambda') end lamdbared=val; end case 'BlockSize' if default block_size=20; else if length(val)>1 || ~isnumeric( val) error('CBCT:OS_SART_CBCT:InvalidInput','Invalid BlockSize') end block_size=val; end case 'Init' res=[]; if default || strcmp(val,'none') res=zeros(geo.nVoxel','single'); continue; end if strcmp(val,'FDK') res=FDK_CBCT(proj,geo,alpha); continue; end if strcmp(val,'multigrid') res=init_multigrid(proj,geo,alpha); continue; end if strcmp(val,'image') initwithimage=1; continue; end if isempty(res) error('CBCT:OS_SART_CBCT:InvalidInput','Invalid Init option') end % % % % % % % ERROR case 'InitImg' if default continue; end if exist('initwithimage','var'); if isequal(size(val),geo.nVoxel'); res=single(val); else error('CBCT:OS_SART_CBCT:InvalidInput','Invalid image for initialization'); end end case 'QualMeas' if default QualMeasOpts={}; else if iscellstr(val) QualMeasOpts=val; else error('CBCT:OS_SART_CBCT:InvalidInput','Invalid quality measurement parameters'); end end case 'OrderStrategy' if default OrderStrategy='angularDistance'; else OrderStrategy=val; end otherwise error('CBCT:OS_SART_CBCT:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in OS_SART_CBCT()']); end end end
github
jacksky64/imageProcessing-master
OSC_TV.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/OSC_TV.m
12,828
utf_8
4d5cae328b50056fad216452c9f0f202
function [ fres ] = OSC_TV(proj,geo,angles,maxiter,varargin) %ASD_POCS Solves the ASD_POCS total variation constrained image in 3D % tomography. % % ASD_POCS(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % ASD_POCS(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % % 'lambda': Sets the value of the hyperparameter for the SART iterations. % Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.99 % % 'TViter': Defines the amount of TV iterations performed per SART % iteration. Default is 20 % % 'alpha': Defines the TV hyperparameter. default is 0.002 % % 'alpha_red': Defines the reduction rate of the TV hyperparameter % % 'Ratio': The maximum allowed image/TV update ration. If the TV % update changes the image more than this, the parameter % will be reduced.default is 0.95 % 'maxL2err' Maximum L2 error to accept an image as valid. This % parameter is crucial for the algorithm, determines at % what point an image should not be updated further. % Default is 20% of the FDK L2 norm. % 'BlockSize': Sets the projection block size used simultaneously. If % BlockSize = 1 OS-SART becomes SART and if BlockSize = length(alpha) % then OS-SART becomes SIRT. Default is 20. % 'OrderStrategy' Chooses the subset ordering strategy. Options are % 'ordered' :uses them in the input order, but divided % 'random' : orders them randomply % 'angularDistance': chooses the next subset with the % biggest angular distance with the ones used. % % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- %% parse inputs [beta,beta_red,ng,verbose,alpha,alpha_red,rmax,epsilon,blocksize,OrderStrategy]=parse_inputs(proj,geo,angles,varargin); %% Create weigthing matrices for the SART step % the reason we do this, instead of calling the SART fucntion is not to % recompute the weigths every ASD-POCS iteration, thus effectively doubling % the computational time % first order the projection angles [alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy); % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; % Back-Projection weigth, V if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; else V=ones([geo.nVoxel(1:2).',length(angles)],'single'); end clear A x y dx dz; % initialize image. f=zeros(geo.nVoxel','single'); stop_criteria=0; iter=0; offOrigin=geo.offOrigin; offDetector=geo.offDetector; while ~stop_criteria %POCS f0=f; if (iter==0 && verbose==1);tic;end iter=iter+1; for jj=1:length(alphablocks); % Get offsets if size(offOrigin,2)==length(angles) geo.offOrigin=offOrigin(:,orig_index{jj}); end if size(offDetector,2)==length(angles) geo.offDetector=offDetector(:,orig_index{jj}); end %proj is data: b=Ax %res= initial image is zero (default) % proj_err=proj(:,:,orig_index{jj})-Ax(f,geo,alphablocks{jj},'interpolated'); % (b-Ax) % weighted_err=W(:,:,orig_index{jj}).*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,alphablocks{jj},'FDK'); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./sum(V(:,:,orig_index{jj}),3),backprj); % V * At * W^-1 * (b-Ax) % f=f+beta*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) f=f+beta* bsxfun(@times,1./sum(V(:,:,orig_index{jj}),3),Atb(W(:,:,orig_index{jj}).*(proj(:,:,orig_index{jj})-Ax(f,geo,alphablocks{jj})),geo,alphablocks{jj})); % Non-negativity constrain f(f<0)=0; end geo.offDetector=offDetector; geo.offOrigin=offOrigin; % Save copy of image. fres=f; % compute L2 error of actual image. Ax-b g=Ax(f,geo,angles); dd=im3Dnorm(g-proj,'L2'); % compute change in the image after last SART iteration dp_vec=(f-f0); dp=im3Dnorm(dp_vec,'L2'); if iter==1 dtvg=alpha*dp; end f0=f; % TV MINIMIZATION % ========================================================================= % Call GPU to minimize TV f=minimizeTV(f0,dtvg,ng); % This is the MATLAB CODE, the functions are sill in the library, but CUDA is used nowadays % for ii=1:ng % % Steepest descend of TV norm % tv(ng*(iter-1)+ii)=im3Dnorm(f,'TV','forward'); % df=gradientTVnorm(f,'forward'); % df=df./im3Dnorm(df,'L2'); % f=f-dtvg.*df; % end % update parameters % ========================================================================== % compute change by TV min dg_vec=(f-f0); dg=im3Dnorm(dg_vec,'L2'); % if change in TV is bigger than the change in SART AND image error is still bigger than acceptable if dg>rmax*dp && dd>epsilon dtvg=dtvg*alpha_red; end % reduce SART step beta=beta*beta_red; % Check convergence criteria % ========================================================================== c=dot(dg_vec(:),dp_vec(:))/(norm(dg_vec(:),2)*norm(dp_vec(:),2)); if (c<-0.99 && dd<=epsilon) || beta<0.005|| iter>maxiter if verbose disp(['Stopping criteria met']); disp([' c = ' num2str(c)]); disp([' beta = ' num2str(beta)]); disp([' iter = ' num2str(iter)]); end stop_criteria=true; end if (iter==1 && verbose==1); expected_time=toc*maxiter; disp('OSC-TV'); disp(['Expected duration : ',secs2hms(expected_time)]); disp(['Exected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function [beta,beta_red,ng,verbose,alpha,alpha_red,rmax,epsilon,block_size,OrderStrategy]=parse_inputs(proj,geo,angles,argin) opts= {'lambda','lambda_red','TViter','Verbose','alpha','alpha_red','Ratio','maxL2err','BlockSize','OrderStrategy','BlockSize'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:OSC_TV:InvalidInput','Invalid number of inputs') end % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extract value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end % parse inputs switch opt % Verbose % ========================================================================= case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % Lambda % ========================================================================= % Its called beta in OSC_TV case 'lambda' if default beta=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:OSC_TV:InvalidInput','Invalid lambda') end beta=val; end % Lambda reduction % ========================================================================= case 'lambda_red' if default beta_red=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:OSC_TV:InvalidInput','Invalid lambda') end beta_red=val; end % Number of iterations of TV % ========================================================================= case 'TViter' if default ng=20; else ng=val; end % TV hyperparameter % ========================================================================= case 'alpha' if default alpha=0.002; % 0.2 else alpha=val; end % TV hyperparameter redution % ========================================================================= case 'alpha_red' if default alpha_red=0.95; else alpha_red=val; end % Maximum update ratio % ========================================================================= case 'Ratio' if default rmax=0.95; else rmax=val; end % Maximum L2 error to have a "good image" % ========================================================================= case 'maxL2err' if default epsilon=im3Dnorm(FDK(proj,geo,angles))*0.2; %heuristic else epsilon=val; end % Block size for OS-SART % ========================================================================= case 'BlockSize' if default block_size=20; else if length(val)>1 || ~isnumeric( val) error('CBCT:OSC_TV:InvalidInput','Invalid BlockSize') end block_size=val; end % Order strategy % ========================================================================= case 'OrderStrategy' if default OrderStrategy='angularDistance'; else OrderStrategy=val; end otherwise error('CBCT:OSC_TV:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in OSC_TV()']); end end end
github
jacksky64/imageProcessing-master
SART.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/SART.m
11,488
utf_8
6e4d467e70f1d2bc45e9c1f69c247dad
function [res,errorL2,qualMeasOut]=SART(proj,geo,angles,niter,varargin) % SART_CBCT solves Cone Beam CT image reconstruction using Oriented Subsets % Simultaneous Algebraic Reconxtruction Techique algorithm % % SART(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % SART_CBCT(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % % 'lambda': Sets the value of the hyperparameter. Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.99 % % 'Init': Describes diferent initialization techniques. % 'none' : Initializes the image to zeros (default) % 'FDK' : intializes image to FDK reconstrucition % 'multigrid': Initializes image by solving the problem in % small scale and increasing it when relative % convergence is reached. % 'image' : Initialization using a user specified % image. Not recomended unless you really % know what you are doing. % 'InitImg' an image for the 'image' initialization. Aviod. % % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. % 'QualMeas' Asks the algorithm for a set of quality measurement % parameters. Input should contain a cell array of desired % quality measurement names. Example: {'CC','RMSE','MSSIM'} % These will be computed in each iteration. % 'OrderStrategy' Chooses the subset ordering strategy. Options are % 'ordered' :uses them in the input order, but divided % 'random' : orders them randomply % 'angularDistance': chooses the next subset with the % biggest angular distance with the ones used. %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- %% Deal with input parameters blocksize=1; [lambda,res,lamdbared,verbose,QualMeasOpts,OrderStrategy]=parse_inputs(proj,geo,angles,varargin); measurequality=~isempty(QualMeasOpts); if nargout>1 computeL2=true; else computeL2=false; end errorL2=[]; % reorder angles [alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy); angles=cell2mat(alphablocks); index_angles=cell2mat(orig_index); %% Create weigthing matrices % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; % Back-Projection weigth, V if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; V=single(V); else V=ones([geo.nVoxel(1:2).',length(angles)],'single'); end clear A x y dx dz; %% Iterate offOrigin=geo.offOrigin; offDetector=geo.offDetector; % TODO : Add options for Stopping criteria for ii=1:niter if (ii==1 && verbose==1);tic;end % If quality is going to be measured, then we need to save previous image % THIS TAKES MEMORY! if measurequality res_prev=res; end for jj=1:length(angles); if size(offOrigin,2)==length(angles) geo.offOrigin=offOrigin(:,index_angles(jj)); end if size(offDetector,2)==length(angles) geo.offDetector=offDetector(:,index_angles(jj)); end % --------- Memory expensive----------- % and does not include angle reordering!!! % proj_err=proj(:,:,jj)-Ax(res,geo,angles(jj)); % (b-Ax) % weighted_err=W(:,:,jj).*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,angles(jj)); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./V(:,:,jj),backprj); % V * At * W^-1 * (b-Ax) % res=res+lambda*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) %------------------------------------ %--------- Memory cheap(er)----------- res=res+lambda* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,jj).*(proj(:,:,index_angles(jj))-Ax(res,geo,angles(jj))),geo,angles(jj))); res(res<0)=0; end % If quality is being measured if measurequality % HERE GOES qualMeasOut(:,ii)=Measure_Quality(res,res_prev,QualMeasOpts); end lambda=lambda*lamdbared; if computeL2 geo.offOrigin=offOrigin; geo.offDetector=offDetector; errornow=im3Dnorm(proj(:,:,index_angles)-Ax(res,geo,angles),'L2'); % Compute error norm2 of b-Ax % If the error is not minimized. if ii~=1 && errornow>errorL2(end) if verbose disp(['Convergence criteria met, exiting on iteration number:', num2str(ii)]); end return; end errorL2=[errorL2 errornow]; end if (ii==1 && verbose==1); expected_time=toc*niter; disp('SART'); disp(['Expected duration : ',secs2hms(expected_time)]); disp(['Exected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function initres=init_multigrid(proj,geo,alpha) finalsize=geo.nVoxel; % start with 64 geo.nVoxel=[64;64;64]; geo.dVoxel=geo.sVoxel./geo.nVoxel; if any(finalsize<geo.nVoxel) initres=zeros(finalsize'); return; end niter=100; initres=zeros(geo.nVoxel'); while ~isequal(geo.nVoxel,finalsize) % solve subsampled grid initres=SART(proj,geo,alpha,niter,'Init','image','InitImg',initres,'Verbose',0); % Get new dims. geo.nVoxel=geo.nVoxel*2; geo.nVoxel(geo.nVoxel>finalsize)=finalsize(geo.nVoxel>finalsize); geo.dVoxel=geo.sVoxel./geo.nVoxel; % Upsample! % (hopefully computer has enough memory............) [y, x, z]=ndgrid(linspace(1,size(initres,1),geo.nVoxel(1)),... linspace(1,size(initres,2),geo.nVoxel(2)),... linspace(1,size(initres,3),geo.nVoxel(3))); initres=interp3(initres,x,y,z); clear x y z end end function [lambda,res,lamdbared,verbose,QualMeasOpts,OrderStrategy]=parse_inputs(proj,geo,alpha,argin) opts= {'lambda','Init','InitImg','Verbose','lambdaRed','QualMeas','OrderStrategy'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:SART:InvalidInput','Invalid number of inputs') end % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extranc value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end switch opt % % % % % % % Verbose case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % % % % % % % hyperparameter, LAMBDA case 'lambda' if default lambda=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:SART:InvalidInput','Invalid lambda') end lambda=val; end case 'lambdaRed' if default lamdbared=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:SART:InvalidInput','Invalid lambda') end lamdbared=val; end case 'Init' res=[]; if default || strcmp(val,'none') res=zeros(geo.nVoxel','single'); continue; end if strcmp(val,'FDK') res=FDK_CBCT(proj,geo,alpha); continue; end if strcmp(val,'multigrid') res=init_multigrid(proj,geo,alpha); continue; end if strcmp(val,'image') initwithimage=1; continue; end if isempty(res) error('CBCT:SART:InvalidInput','Invalid Init option') end % % % % % % % ERROR case 'InitImg' if default continue; end if exist('initwithimage','var'); if isequal(size(val),geo.nVoxel'); res=single(val); else error('CBCT:SART:InvalidInput','Invalid image for initialization'); end end case 'QualMeas' if default QualMeasOpts={}; else if iscellstr(val) QualMeasOpts=val; else error('CBCT:SART:InvalidInput','Invalid quality measurement parameters'); end end case 'OrderStrategy' if default OrderStrategy='random'; else OrderStrategy=val; end otherwise error('CBCT:SART:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in SART()']); end end end
github
jacksky64/imageProcessing-master
ASD_POCS.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/ASD_POCS.m
12,069
utf_8
c3ad62ba6412de2953c29a4e1cf7c6c2
function [ fres ] = ASD_POCS(proj,geo,angles,maxiter,varargin) %ASD_POCS Solves the ASD_POCS total variation constrained image in 3D % tomography. % % ASD_POCS(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % ASD_POCS(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % % 'lambda': Sets the value of the hyperparameter for the SART iterations. % Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.99 % % 'TViter': Defines the amount of TV iterations performed per SART % iteration. Default is 20 % % 'alpha': Defines the TV hyperparameter. default is 0.002 % % 'alpha_red': Defines the reduction rate of the TV hyperparameter % % 'Ratio': The maximum allowed image/TV update ration. If the TV % update changes the image more than this, the parameter % will be reduced.default is 0.95 % 'maxL2err' Maximum L2 error to accept an image as valid. This % parameter is crucial for the algorithm, determines at % what point an image should not be updated further. % Default is 20% of the FDK L2 norm. % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. % % 'OrderStrategy' Chooses the subset ordering strategy. Options are % 'ordered' :uses them in the input order, but divided % 'random' : orders them randomply % 'angularDistance': chooses the next subset with the % biggest angular distance with the ones used. %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri and Manasavee Lohvithee %-------------------------------------------------------------------------- %% parse inputs blocksize=1; [beta,beta_red,ng,verbose,alpha,alpha_red,rmax,epsilon,OrderStrategy]=parse_inputs(proj,geo,angles,varargin); [alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy); angles=cell2mat(alphablocks); index_angles=cell2mat(orig_index); %% Create weigthing matrices for the SART step % the reason we do this, instead of calling the SART fucntion is not to % recompute the weigths every ASD-POCS iteration, thus effectively doubling % the computational time % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; else V=ones([geo.nVoxel(1:2).',length(angles)],'single'); end clear A x y dx dz; % initialize image. f=zeros(geo.nVoxel','single'); %% stop_criteria=0; iter=0; offOrigin=geo.offOrigin; offDetector=geo.offDetector; while ~stop_criteria %POCS f0=f; if (iter==0 && verbose==1);tic;end iter=iter+1; for jj=1:length(angles); if size(offOrigin,2)==length(angles) geo.OffOrigin=offOrigin(:,jj); end if size(offDetector,2)==length(angles) geo.offDetector=offDetector(:,jj); end % proj_err=proj(:,:,jj)-Ax(f,geo,angles(jj)); % (b-Ax) % weighted_err=W(:,:,jj).*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,angles(jj)); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./V(:,:,jj),backprj); % V * At * W^-1 * (b-Ax) % f=f+beta*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) % Enforce positivity f=f+beta* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,jj).*(proj(:,:,index_angles(jj))-Ax(f,geo,angles(jj))),geo,angles(jj))); f(f<0)=0; end geo.offDetector=offDetector; geo.offOrigin=offOrigin; % Save copy of image. fres=f; % compute L2 error of actual image. Ax-b g=Ax(f,geo,angles); dd=im3Dnorm(g-proj(:,:,index_angles),'L2'); % compute change in the image after last SART iteration dp_vec=(f-f0); dp=im3Dnorm(dp_vec,'L2'); if iter==1 dtvg=alpha*dp; %Convert the steepest-descent step-size from a fraction of a %step-size to an absolute image distance on the first iteration. end f0=f; % TV MINIMIZATION % ========================================================================= % Call GPU to minimize TV f=minimizeTV(f0,dtvg,ng); % This is the MATLAB CODE, the functions are sill in the library, but CUDA is used nowadays % for ii=1:ng % % Steepest descend of TV norm % tv(ng*(iter-1)+ii)=im3Dnorm(f,'TV','forward'); % df=weighted_gradientTVnorm2(f,0.002); % df=df./im3Dnorm(df,'L2'); % f=f-dtvg.*df; % end % update parameters % ========================================================================== % compute change by TV min dg_vec=(f-f0); dg=im3Dnorm(dg_vec,'L2'); % if change in TV is bigger than the change in SART AND image error is still bigger than acceptable if dg>rmax*dp && dd>epsilon dtvg=dtvg*alpha_red; end % reduce SART step beta=beta*beta_red; % Check convergence criteria % ========================================================================== %Define c_alpha as in equation 21 in the journal c=dot(dg_vec(:),dp_vec(:))/(norm(dg_vec(:),2)*norm(dp_vec(:),2)); %This c is examined to see if it is close to -1.0 if (c<-0.99 && dd<=epsilon) || beta<0.005|| iter>maxiter if verbose disp(['Stopping criteria met']); disp([' c = ' num2str(c)]); disp([' beta = ' num2str(beta)]); disp([' iter = ' num2str(iter)]); end stop_criteria=true; end if (iter==1 && verbose==1); expected_time=toc*maxiter; disp('ADS-POCS'); disp(['Expected duration : ',secs2hms(expected_time)]); disp(['Exected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function [beta,beta_red,ng,verbose,alpha,alpha_red,rmax,epsilon,OrderStrategy]=parse_inputs(proj,geo,angles,argin) opts= {'lambda','lambda_red','TViter','Verbose','alpha','alpha_red','Ratio','maxL2err','OrderStrategy'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:ASD_POCS:InvalidInput','Invalid number of inputs') end % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extract value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end % parse inputs switch opt % Verbose % ========================================================================= case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % Lambda % ========================================================================= % Its called beta in ASD-POCS case 'lambda' if default beta=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:ASD_POCS:InvalidInput','Invalid lambda') end beta=val; end % Lambda reduction % ========================================================================= case 'lambda_red' if default beta_red=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:ASD_POCS:InvalidInput','Invalid lambda') end beta_red=val; end % Number of iterations of TV % ========================================================================= case 'TViter' if default ng=20; else ng=val; end % TV hyperparameter % ========================================================================= case 'alpha' if default alpha=0.002; % 0.2 else alpha=val; end % TV hyperparameter redution % ========================================================================= case 'alpha_red' if default alpha_red=0.95; else alpha_red=val; end % Maximum update ratio % ========================================================================= case 'Ratio' if default rmax=0.95; else rmax=val; end % Maximum L2 error to have a "good image" % ========================================================================= case 'maxL2err' if default epsilon=im3Dnorm(FDK(proj,geo,angles))*0.2; %heuristic else epsilon=val; end case 'OrderStrategy' if default OrderStrategy='random'; else OrderStrategy=val; end otherwise error('CBCT:ASD_POCS:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in ASD_POCS()']); end end end
github
jacksky64/imageProcessing-master
B_ASD_POCS_beta.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/B_ASD_POCS_beta.m
13,313
utf_8
69808cbf82a42a1282377cd14fb2e6ec
function [ fres ] = B_ASD_POCS_beta(proj,geo,angles,maxiter,varargin) % B_ASD_POCS_beta Solves the ASD_POCS total variation constrained image in 3D % tomography using bregman iteration for the data. % % ASD_POCS(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % ASD_POCS(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % % 'lambda': Sets the value of the hyperparameter for the SART iterations. % Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.99 % % 'TViter': Defines the amount of TV iterations performed per SART % iteration. Default is 20 % % 'alpha': Defines the TV hyperparameter. default is 0.002 % % 'alpha_red': Defines the reduction rate of the TV hyperparameter % % 'Ratio': The maximum allowed image/TV update ration. If the TV % update changes the image more than this, the parameter % will be reduced.default is 0.95 % 'maxL2err' Maximum L2 error to accept an image as valid. This % parameter is crucial for the algorithm, determines at % what point an image should not be updated further. % Default is 20% of the FDK L2 norm. % % 'beta' hyperparameter controling the Bragman update. default=1 % % 'beta_red' reduction of the beta hyperparameter. default =0.75 % % 'bregman_iter' amount of global bregman iterations. This will define % how often the bregman iteration is executed. It has to % be smaller than the number of iterations. % % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. % % 'OrderStrategy' Chooses the subset ordering strategy. Options are % 'ordered' :uses them in the input order, but divided % 'random' : orders them randomply % 'angularDistance': chooses the next subset with the % biggest angular distance with the ones used. %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- % http://ieeexplore.ieee.org/xpl/abstractAuthors.jsp?arnumber=5874264 %% parse inputs blocksize=1; [beta,beta_red,ng,verbose,alpha,alpha_red,rmax,epsilon,bregman,bregman_red,bregman_iter,OrderStrategy]=parse_inputs(proj,geo,angles,varargin); [alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy); angles=cell2mat(alphablocks); index_angles=cell2mat(orig_index); %% Create weigthing matrices for the SART step % the reason we do this, instead of calling the SART fucntion is not to % recompute the weigths every ASD-POCS iteration, thus effectively doubling % the computational time % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; % Back-Projection weigth, V if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; else V=ones([geo.nVoxel(1:2).',length(angles)],'single'); end clear A x y dx dz; % initialize image. f=zeros(geo.nVoxel','single'); stop_criteria=0; iter=0; offOrigin=geo.offOrigin; offDetector=geo.offDetector; while ~stop_criteria %POCS f0=f; if (iter==0 && verbose==1);tic;end iter=iter+1; for jj=1:length(angles); if size(offOrigin,2)==length(angles) geo.OffOrigin=offOrigin(:,jj); end if size(offDetector,2)==length(angles) geo.offDetector=offDetector(:,jj); end % proj_err=proj(:,:,jj)-Ax(f,geo,angles(jj)); % (b-Ax) % weighted_err=W(:,:,jj).*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,angles(jj)); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./V(:,:,jj),backprj); % V * At * W^-1 * (b-Ax) % f=f+beta*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) f=f+beta* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,jj).*(proj(:,:,index_angles(jj))-Ax(f,geo,angles(jj))),geo,angles(jj))); % Enforce positivity f(f<0)=0; end geo.offDetector=offDetector; geo.offOrigin=offOrigin; % Save copy of image. fres=f; % compute L2 error of actual image. Ax-b g=Ax(f,geo,angles); dd=im3Dnorm(g-proj(:,:,index_angles),'L2'); % compute change in the image after last SART iteration dp_vec=(f-f0); dp=im3Dnorm(dp_vec,'L2'); if iter==1 dtvg=alpha*dp; end f0=f; % TV MINIMIZATION % ========================================================================= % Call GPU to minimize TV f=minimizeTV(f0,dtvg,ng); % This is the MATLAB CODE, the functions are sill in the library, but CUDA is used nowadays % for ii=1:ng % % Steepest descend of TV norm % tv(ng*(iter-1)+ii)=im3Dnorm(f,'TV','forward'); % df=gradientTVnorm(f,'forward'); % df=df./im3Dnorm(df,'L2'); % f=f-dtvg.*df; % end % update parameters % ========================================================================== % compute change by TV min dg_vec=(f-f0); dg=im3Dnorm(dg_vec,'L2'); % if change in TV is bigger than the change in SART AND image error is still bigger than acceptable if dg>rmax*dp && dd>epsilon dtvg=dtvg*alpha_red; end % reduce SART step beta=beta*beta_red; % Check convergence criteria % ========================================================================== c=dot(dg_vec(:),dp_vec(:))/(norm(dg_vec(:),2)*norm(dp_vec(:),2)); if (c<-0.99 && dd<=epsilon) || beta<0.005|| iter>maxiter if verbose disp(['Stopping criteria met']); disp([' c = ' num2str(c)]); disp([' beta = ' num2str(beta)]); disp([' iter = ' num2str(iter)]); end stop_criteria=true; end if ~mod(iter,bregman_iter) proj=proj+bregman*(proj(:,:,index_angles)-Ax(f,geo,angles)); bregman=bregman*bregman_red; end if (iter==1 && verbose==1); expected_time=toc*maxiter; disp('B-ADS-POCS-beta'); disp(['Expected duration : ',secs2hms(expected_time)]); disp(['Exected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function [beta,beta_red,ng,verbose,alpha,alpha_red,rmax,epsilon,bregman,bregman_red,bregman_iter,OrderStrategy]=parse_inputs(proj,geo,angles,argin) opts= {'lambda','lambda_red','TViter','Verbose','alpha','alpha_red','Ratio','maxL2err','beta','beta_red','bregman_iter','OrderStrategy'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:ASD_POCS:InvalidInput','Invalid number of inputs') end % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extract value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end % parse inputs switch opt % Verbose % ========================================================================= case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % Lambda % ========================================================================= % Its called beta in ASD-POCS case 'lambda' if default beta=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:ASD_POCS:InvalidInput','Invalid lambda') end beta=val; end % Lambda reduction % ========================================================================= case 'lambda_red' if default beta_red=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:ASD_POCS:InvalidInput','Invalid lambda') end beta_red=val; end % Number of iterations of TV % ========================================================================= case 'TViter' if default ng=20; else ng=val; end % TV hyperparameter % ========================================================================= case 'alpha' if default alpha=0.002; % 0.2 else alpha=val; end % TV hyperparameter redution % ========================================================================= case 'alpha_red' if default alpha_red=0.95; else alpha_red=val; end % Maximum update ratio % ========================================================================= case 'Ratio' if default rmax=0.95; else rmax=val; end % Maximum L2 error to have a "good image" % ========================================================================= case 'maxL2err' if default epsilon=im3Dnorm(FDK(proj,geo,angles))*0.2; %heuristic else epsilon=val; end % TV bregman hyperparameter % ========================================================================= case 'beta' if default bregman=1; else bregman=val; end % TV bregman hyperparameter redution % ========================================================================= case 'beta_red' if default bregman_red=0.75; else bregman_red=val; end case 'bregman_iter' if default bregman_iter=5; else bregman_iter=val; end case 'OrderStrategy' if default OrderStrategy='random'; else OrderStrategy=val; end otherwise error('CBCT:B_ASD_POCS_beta:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in ASD_POCS()']); end end end
github
jacksky64/imageProcessing-master
SART_TV.m
.m
imageProcessing-master/cone beam/CERN-TIGRE-v1.1.3-2-g2ee570e/CERN-TIGRE-2ee570e/Algorithms/SART_TV.m
11,882
utf_8
ff74dbf3c25b8132a01c45b319c25a85
function [res,errorL2,qualMeasOut]=SART_TV(proj,geo,angles,niter,varargin) % SART_TV solves Cone Beam CT image reconstruction using Oriented Subsets % Simultaneous Algebraic Reconxtruction Techique algorithm % % SART_TV(PROJ,GEO,ALPHA,NITER) solves the reconstruction problem % using the projection data PROJ taken over ALPHA angles, corresponding % to the geometry descrived in GEO, using NITER iterations. % % SART_TV(PROJ,GEO,ALPHA,NITER,OPT,VAL,...) uses options and values for solving. The % possible options in OPT are: % % % 'lambda': Sets the value of the hyperparameter. Default is 1 % % 'lambdared': Reduction of lambda.Every iteration % lambda=lambdared*lambda. Default is 0.99 % % 'Init': Describes diferent initialization techniques. % 'none' : Initializes the image to zeros (default) % 'FDK' : intializes image to FDK reconstrucition % 'multigrid': Initializes image by solving the problem in % small scale and increasing it when relative % convergence is reached. % 'image' : Initialization using a user specified % image. Not recomended unless you really % know what you are doing. % 'InitImg' an image for the 'image' initialization. Aviod. % % 'TViter' amoutn of iteration in theTV step. Default 50 % % 'TVlambda' hyperparameter in TV iteration. IT gives the ratio of % importance of the image vs the minimum total variation. % default is 15. Lower means more TV denoising. % % 'Verbose' 1 or 0. Default is 1. Gives information about the % progress of the algorithm. % % 'QualMeas' Asks the algorithm for a set of quality measurement % parameters. Input should contain a cell array of desired % quality measurement names. Example: {'CC','RMSE','MSSIM'} % These will be computed in each iteration. % 'OrderStrategy' Chooses the subset ordering strategy. Options are % 'ordered' :uses them in the input order, but divided % 'random' : orders them randomply % 'angularDistance': chooses the next subset with the % biggest angular distance with the ones used. %-------------------------------------------------------------------------- %-------------------------------------------------------------------------- % This file is part of the TIGRE Toolbox % % Copyright (c) 2015, University of Bath and % CERN-European Organization for Nuclear Research % All rights reserved. % % License: Open Source under BSD. % See the full license at % https://github.com/CERN/TIGRE/license.txt % % Contact: [email protected] % Codes: https://github.com/CERN/TIGRE/ % Coded by: Ander Biguri %-------------------------------------------------------------------------- %% Deal with input parameters [lambda,res,lamdbared,verbose,QualMeasOpts,TViter,TVlambda,OrderStrategy]=parse_inputs(proj,geo,angles,varargin); measurequality=~isempty(QualMeasOpts); if nargout>1 computeL2=true; else computeL2=false; end errorL2=[]; blocksize=1; [alphablocks,orig_index]=order_subsets(angles,blocksize,OrderStrategy); angles=cell2mat(alphablocks); index_angles=cell2mat(orig_index); %% Create weigthing matrices % Projection weigth, W geoaux=geo; geoaux.sVoxel(3)=max(geo.sDetector(2),geo.sVoxel(3)); % make sure lines are not cropped. One is for when image is bigger than detector and viceversa geoaux.nVoxel=[2,2,2]'; % accurate enough? geoaux.dVoxel=geoaux.sVoxel./geoaux.nVoxel; W=Ax(ones(geoaux.nVoxel','single'),geoaux,angles,'ray-voxel'); % W(W<min(geo.dVoxel)/4)=Inf; W=1./W; % Back-Projection weigth, V if ~isfield(geo,'mode')||~strcmp(geo.mode,'parallel') [x,y]=meshgrid(geo.sVoxel(1)/2-geo.dVoxel(1)/2+geo.offOrigin(1):-geo.dVoxel(1):-geo.sVoxel(1)/2+geo.dVoxel(1)/2+geo.offOrigin(1),... -geo.sVoxel(2)/2+geo.dVoxel(2)/2+geo.offOrigin(2): geo.dVoxel(2): geo.sVoxel(2)/2-geo.dVoxel(2)/2+geo.offOrigin(2)); A = permute(angles+pi/2, [1 3 2]); V = (geo.DSO ./ (geo.DSO + bsxfun(@times, y, sin(-A)) - bsxfun(@times, x, cos(-A)))).^2; else V=ones([geo.nVoxel(1:2).',length(angles)],'single'); end clear A x y dx dz; %% Iterate offOrigin=geo.offOrigin; offDetector=geo.offDetector; % TODO : Add options for Stopping criteria for ii=1:niter if (ii==1 && verbose==1);tic;end % If quality is going to be measured, then we need to save previous image % THIS TAKES MEMORY! if measurequality res_prev=res; end for jj=1:length(angles); if size(offOrigin,2)==length(angles) geo.OffOrigin=offOrigin(:,jj); end if size(offDetector,2)==length(angles) geo.offDetector=offDetector(:,jj); end % proj_err=proj(:,:,jj)-Ax(res,geo,angles(jj)); % (b-Ax) % weighted_err=W(:,:,jj).*proj_err; % W^-1 * (b-Ax) % backprj=Atb(weighted_err,geo,angles(jj)); % At * W^-1 * (b-Ax) % weigth_backprj=bsxfun(@times,1./V(:,:,jj),backprj); % V * At * W^-1 * (b-Ax) % res=res+lambda*weigth_backprj; % x= x + lambda * V * At * W^-1 * (b-Ax) res=res+lambda* bsxfun(@times,1./V(:,:,jj),Atb(W(:,:,jj).*(proj(:,:,index_angles(jj))-Ax(res,geo,angles(jj))),geo,angles(jj))); res(res<0)=0; end % If quality is being measured if measurequality % HERE GOES qualMeasOut(:,ii)=Measure_Quality(res,res_prev,QualMeasOpts); end lambda=lambda*lamdbared; % TV denoising res=im3DDenoise(res,'TV',TViter,TVlambda); if computeL2 geo.offOrigin=offOrigin; geo.offDetector=offDetector; errornow=im3Dnorm(proj(:,:,index_angles)-Ax(res,geo,angles),'L2'); % Compute error norm2 of b-Ax % If the error is not minimized. if ii~=1 && errornow>errorL2(end) if verbose disp(['Convergence criteria met, exiting on iteration number:', num2str(ii)]); end return; end errorL2=[errorL2 errornow]; end if (ii==1 && verbose==1); expected_time=toc*niter; disp('SART_TV'); disp(['Expected duration : ',secs2hms(expected_time)]); disp(['Exected finish time: ',datestr(datetime('now')+seconds(expected_time))]); disp(''); end end end function initres=init_multigrid(proj,geo,alpha,TViter,TVlambda) finalsize=geo.nVoxel; % start with 64 geo.nVoxel=[64;64;64]; geo.dVoxel=geo.sVoxel./geo.nVoxel; if any(finalsize<geo.nVoxel) initres=zeros(finalsize'); return; end niter=100; initres=zeros(geo.nVoxel','single'); while ~isequal(geo.nVoxel,finalsize) % solve subsampled grid initres=SART_TV(proj,geo,alpha,niter,'Init','image','InitImg',initres,'Verbose',0,'TViter',TViter,'TVlambda',TVlambda); % Get new dims. geo.nVoxel=geo.nVoxel*2; geo.nVoxel(geo.nVoxel>finalsize)=finalsize(geo.nVoxel>finalsize); geo.dVoxel=geo.sVoxel./geo.nVoxel; % Upsample! % (hopefully computer has enough memory............) [y, x, z]=ndgrid(linspace(1,size(initres,1),geo.nVoxel(1)),... linspace(1,size(initres,2),geo.nVoxel(2)),... linspace(1,size(initres,3),geo.nVoxel(3))); initres=interp3(initres,x,y,z); clear x y z end end function [lambda,res,lamdbared,verbose,QualMeasOpts,TViter,TVlambda,OrderStrategy]=parse_inputs(proj,geo,alpha,argin) opts= {'lambda','Init','InitImg','Verbose','lambdaRed','QualMeas','TViter','TVlambda','OrderStrategy'}; defaults=ones(length(opts),1); % Check inputs nVarargs = length(argin); if mod(nVarargs,2) error('CBCT:SART:InvalidInput','Invalid number of inputs') end multigrid=false; % check if option has been passed as input for ii=1:2:nVarargs ind=find(ismember(opts,argin{ii})); if ~isempty(ind) defaults(ind)=0; end end for ii=1:length(opts) opt=opts{ii}; default=defaults(ii); % if one option isnot default, then extranc value from input if default==0 ind=double.empty(0,1);jj=1; while isempty(ind) ind=find(isequal(opt,argin{jj})); jj=jj+1; end val=argin{jj}; end switch opt % % % % % % % Verbose case 'Verbose' if default verbose=1; else verbose=val; end if ~is2014bOrNewer warning('Verbose mode not available for older versions than MATLAB R2014b'); verbose=false; end % % % % % % % hyperparameter, LAMBDA case 'lambda' if default lambda=1; else if length(val)>1 || ~isnumeric( val) error('CBCT:SART:InvalidInput','Invalid lambda') end lambda=val; end case 'lambdaRed' if default lamdbared=0.99; else if length(val)>1 || ~isnumeric( val) error('CBCT:SART:InvalidInput','Invalid lambda') end lamdbared=val; end case 'Init' res=[]; if default || strcmp(val,'none') res=zeros(geo.nVoxel','single'); continue; end if strcmp(val,'multigrid') multigrid=true; continue; end if strcmp(val,'image') initwithimage=1; continue; end if isempty(res) error('CBCT:SART:InvalidInput','Invalid Init option') end % % % % % % % ERROR case 'InitImg' if default continue; end if exist('initwithimage','var'); if isequal(size(val),geo.nVoxel'); res=single(val); else error('CBCT:SART:InvalidInput','Invalid image for initialization'); end end case 'QualMeas' if default QualMeasOpts={}; else if iscellstr(val) QualMeasOpts=val; else error('CBCT:SART:InvalidInput','Invalid quality measurement parameters'); end end case 'TViter' if default TViter=50; else TViter=val; end case 'TVlambda' if default TVlambda=50; else TVlambda=val; end case 'OrderStrategy' if default OrderStrategy='random'; else OrderStrategy=val; end otherwise error('CBCT:SART:InvalidInput',['Invalid input name:', num2str(opt),'\n No such option in SART()']); end end if multigrid; res=init_multigrid(proj,geo,alpha,TViter,TVlambda);end; end
github
jacksky64/imageProcessing-master
filtering.m
.m
imageProcessing-master/cone beam/CBCT_Kyungsang_matlab_Feb2015/bin/filtering.m
2,320
utf_8
5fb94b13622703c07659af861f665663
function [ proj ] = filtering(proj,param ) %FILTERING Summary of this function goes here % Detailed explanation goes here us = ((-param.nu/2+0.5):1:(param.nu/2-0.5))*param.du + param.off_u; vs = ((-param.nv/2+0.5):1:(param.nv/2-0.5))*param.dv + param.off_v; [uu,vv] = meshgrid(us,vs); w = (param.DSD)./sqrt((param.DSD)^2+uu.^2 + vv.^2); for i=1:param.nProj proj(:,:,i) = proj(:,:,i).*w'; end if param.parker == 1 proj = ParkerWeight(proj,param); end filt_len = max(64,2^nextpow2(2*param.nu)); [ramp_kernel] = ramp_flat(filt_len); d = 1; % cut off (0~1) [filt] = Filter(param.filter, ramp_kernel, filt_len, d); filt = repmat(filt',[1 param.nv]); for i=1:param.nProj fproj = (zeros(filt_len,param.nv,'single')); fproj(filt_len/2-param.nu/2+1:filt_len/2+param.nu/2,:) = proj(:,:,i); fproj = fft(fproj); fproj = fproj.*filt; fproj = (real(ifft(fproj))); if param.parker == 1 proj(:,:,i) = fproj(end/2-param.nu/2+1:end/2+param.nu/2,:)/2/param.du*(2*pi/(180/param.dang))/2*(param.DSD/param.DSO); else proj(:,:,i) = fproj(end/2-param.nu/2+1:end/2+param.nu/2,:)/2/param.du*(2*pi/param.nProj)/2*(param.DSD/param.DSO); end end end function [h, nn] = ramp_flat(n) nn = [-(n/2):(n/2-1)]'; h = zeros(size(nn),'single'); h(n/2+1) = 1 / 4; odd = mod(nn,2) == 1; h(odd) = -1 ./ (pi * nn(odd)).^2; end function [filt] = Filter(filter, kernel, order, d) f_kernel = abs(fft(kernel))*2; filt = f_kernel(1:order/2+1)'; w = 2*pi*(0:size(filt,2)-1)/order; % frequency axis up to Nyquist switch lower(filter) case 'ram-lak' % Do nothing case 'shepp-logan' % be careful not to divide by 0: filt(2:end) = filt(2:end) .* (sin(w(2:end)/(2*d))./(w(2:end)/(2*d))); case 'cosine' filt(2:end) = filt(2:end) .* cos(w(2:end)/(2*d)); case 'hamming' filt(2:end) = filt(2:end) .* (.54 + .46 * cos(w(2:end)/d)); case 'hann' filt(2:end) = filt(2:end) .*(1+cos(w(2:end)./d)) / 2; otherwise filter error('Invalid filter selected.'); end filt(w>pi*d) = 0; % Crop the frequency response filt = [filt , filt(end-1:-1:2)]; % Symmetry of the filter return end
github
jacksky64/imageProcessing-master
llf.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/llf.m
1,583
utf_8
7a14718e491c75a5df4d50397b210a26
% Perform the local laplacian filter using the function % f(x,ref)=x+fact*(I-ref)*exp(-(I-ref)²/(2*sigma²)) % Perform the local laplacian filter using any function % This script implements edge-aware detail and tone manipulation as % described in : % Fast and Robust Pyramid-based Image Processing. % Mathieu Aubry, Sylvain Paris, Samuel W. Hasinoff, Jan Kautz, and Frédo Durand. % MIT technical report, November 2011 % INPUT % I : input greyscale image % r : a function handle to the remaping function % N : number discretisation values of the intensity % % OUTPUT % F : filtered image % [email protected] Sept 2012 function [F]=llf(I,sigma,fact,N) [height width]=size(I); n_levels=ceil(log(min(height,width))-log(2))+2; discretisation=linspace(0,1,N); discretisation_step=discretisation(2); input_gaussian_pyr=gaussian_pyramid(I,n_levels); output_laplace_pyr=laplacian_pyramid(I,n_levels); output_laplace_pyr{n_levels}=input_gaussian_pyr{n_levels}; for ref=discretisation I_remap=fact*(I-ref).*exp(-(I-ref).*(I-ref)./(2*sigma*sigma)); temp_laplace_pyr=laplacian_pyramid(I_remap,n_levels); for level=1:n_levels-1 output_laplace_pyr{level}=output_laplace_pyr{level}+... (abs(input_gaussian_pyr{level}-ref)<discretisation_step).*... temp_laplace_pyr{level}.*... (1-abs(input_gaussian_pyr{level}-ref)/discretisation_step); end end F=reconstruct_laplacian_pyramid(output_laplace_pyr);
github
jacksky64/imageProcessing-master
remapping_function.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/remapping_function.m
193
utf_8
39f4e6083a03bed8b5fed18c4b63f877
%This is just a toy example! function y=remapping_function(x) % y=(x-0.1).*(x>0.1)+(x+0.1).*(x<-0.1); %smoothing y=3.*x.*(abs(x)<0.1)+(x+0.2).*(x>0.1)+(x-0.2).*(x<-0.1); %enhancement end
github
jacksky64/imageProcessing-master
reconstruct_laplacian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/reconstruct_laplacian_pyramid.m
1,074
utf_8
7ba1435cc8f4ff0d1428d1179e7cd9ea
% Reconstruction of image from Laplacian pyramid % % Arguments: % pyramid 'pyr', as generated by function 'laplacian_pyramid' % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % % % More information: % 'The Laplacian Pyramid as a Compact Image Code' % Burt, P., and Adelson, E. H., % IEEE Transactions on Communication, COM-31:532-540 (1983). % function R = reconstruct_laplacian_pyramid(pyr,subwindow) r = size(pyr{1},1); c = size(pyr{1},2); nlev = length(pyr); subwindow_all = zeros(nlev,4); if ~exist('subwindow','var') subwindow_all(1,:) = [1 r 1 c]; else subwindow_all(1,:) = subwindow; end for lev = 2:nlev subwindow_all(lev,:) = child_window(subwindow_all(lev-1,:)); end % start with low pass residual R = pyr{nlev}; filter = pyramid_filter; for lev = nlev-1 : -1 : 1 % upsample, and add to current level R = pyr{lev} + upsample(R,filter,subwindow_all(lev,:)); end
github
jacksky64/imageProcessing-master
laplacian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/laplacian_pyramid.m
1,251
utf_8
8d160a39954ea8ac8ef42ee22d0f8181
% Contruction of Laplacian pyramid % % Arguments: % image 'I' % 'nlev', number of levels in the pyramid (optional) % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % % % More information: % 'The Laplacian Pyramid as a Compact Image Code' % Burt, P., and Adelson, E. H., % IEEE Transactions on Communication, COM-31:532-540 (1983). % function pyr = laplacian_pyramid(I,nlev,subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end if ~exist('nlev','var') nlev = numlevels([r c]); % build highest possible pyramid end % recursively build pyramid pyr = cell(nlev,1); filter = pyramid_filter; J = I; for l = 1:nlev - 1 % apply low pass filter, and downsample [I,subwindow_child] = downsample(J,filter,subwindow); % in each level, store difference between image and upsampled low pass version pyr{l} = J - upsample(I,filter,subwindow); J = I; % continue with low pass image subwindow = subwindow_child; end pyr{nlev} = J; % the coarest level contains the residual low pass image
github
jacksky64/imageProcessing-master
llf_general.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/llf_general.m
1,278
utf_8
7d132e2ca02f40f77332200e3a4e5f48
% Perform the local laplacian filter using any function % INPUT % I : input greyscale image % r : a function handle to the remaping function % N : number discretisation values of the intensity % % OUTPUT % F : filtered image % [email protected] Sept 2012 function [F]=llf_general(I,r,N) [height width]=size(I); n_levels=ceil(log(min(height,width))-log(2))+2; discretisation=linspace(0,1,N); discretisation_step=discretisation(2); input_gaussian_pyr=gaussian_pyramid(I,n_levels); output_laplace_pyr=laplacian_pyramid(I,n_levels); output_laplace_pyr{n_levels}=input_gaussian_pyr{n_levels}; for level=1:n_levels-1 output_laplace_pyr{level}=zeros(size(output_laplace_pyr{level})); end for ref=discretisation I_remap=r(I-ref); temp_laplace_pyr=laplacian_pyramid(I_remap,n_levels); for level=1:n_levels-1 output_laplace_pyr{level}=output_laplace_pyr{level}+... (abs(input_gaussian_pyr{level}-ref)<discretisation_step).*... temp_laplace_pyr{level}.*... (1-abs(input_gaussian_pyr{level}-ref)/discretisation_step); end end F=reconstruct_laplacian_pyramid(output_laplace_pyr);
github
jacksky64/imageProcessing-master
gaussian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/gaussian_pyramid.m
785
utf_8
c37904c322f0ffcdfb042808f7b58b42
% Construction of Gaussian pyramid % % Arguments: % image 'I' % 'nlev', number of levels in the pyramid (optional) % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % function pyr = gaussian_pyramid(I,nlev,subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end if ~exist('nlev','var') nlev = numlevels([r c]); % build highest possible pyramid end % start by copying the image to the finest level pyr = cell(nlev,1); pyr{1} = I; % recursively downsample the image filter = pyramid_filter; for l = 2:nlev I = downsample(I,filter,subwindow); pyr{l} = I; end
github
jacksky64/imageProcessing-master
pyramid_filter.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/pyramid_filter.m
415
utf_8
6bdb380bd8a557e8170203e732d1f7df
% This is a 2D separable low pass filter for constructing Gaussian and % Laplacian pyramids, built from a 1D 5-tap low pass filter. % % [email protected], August 2007 % [email protected], March 2011 [imfilter faster with 2D filter] % function f = pyramid_filter() f = [.05, .25, .4, .25, .05]; % original [Burt and Adelson, 1983] %f = [.0625, .25, .375, .25, .0625]; % binom-5 f = f'*f; end
github
jacksky64/imageProcessing-master
downsample.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/downsample.m
1,235
utf_8
aae6c458109d70f4c77f2465e543c4bf
% Downsampling procedure. % % Arguments: % 'I': image % downsampling filter 'filter', should be a 2D separable filter. % 'border_mode' should be 'circular', 'symmetric', or 'replicate'. See 'imfilter'. % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [handle subwindows, reweighted boundaries] % function [R,subwindow_child] = downsample(I, filter, subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end subwindow_child = child_window(subwindow); border_mode = 'reweighted'; %border_mode = 'symmetric'; switch border_mode case 'reweighted' % low pass, convolve with 2D separable filter R = imfilter(I,filter); % reweight, brute force weights from 1's in valid image positions Z = imfilter(ones(size(I)),filter); R = R./Z; otherwise % low pass, convolve with 2D separable filter R = imfilter(I,filter,border_mode); end % decimate reven = mod(subwindow(1),2)==0; ceven = mod(subwindow(3),2)==0; R = R(1+reven:2:r, 1+ceven:2:c, :); end
github
jacksky64/imageProcessing-master
upsample.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer_original/upsample.m
1,504
utf_8
3e8cf7f9ffd5675cc72aaa396f478ffe
% Upsampling procedure. % % Argments: % 'I': image % 'filter': 2D separable upsampling filter % parent subwindow indices 'subwindow', given as [r1 r2 c1 c2] % % [email protected], August 2007 % [email protected], March 2011 [handle subwindows, reweighted boundaries] % function R = upsample(I, filter, subwindow) % increase size to match dimensions of the parent subwindow, % about 2x in each dimension r = subwindow(2) - subwindow(1) + 1; c = subwindow(4) - subwindow(3) + 1; k = size(I,3); reven = mod(subwindow(1),2)==0; ceven = mod(subwindow(3),2)==0; border_mode = 'reweighted'; %border_mode = 'symmetric'; switch border_mode case 'reweighted' % interpolate, convolve with 2D separable filter R = zeros(r,c,k); R(1+reven:2:r, 1+ceven:2:c, :) = I; R = imfilter(R,filter); % reweight, brute force weights from 1's in valid image positions Z = zeros(r,c,k); Z(1+reven:2:r, 1+ceven:2:c, :) = 1; Z = imfilter(Z,filter); R = R./Z; otherwise % increase resolution I = padarray(I,[1 1 0],'replicate'); % pad the image with a 1-pixel border R = zeros(r+4,c+4,k); R(1+reven:2:end, 1+ceven:2:end, :) = 4*I; % interpolate, convolve with 2D separable filter R = imfilter(R,filter,border_mode); % remove the border R = R(3:end-2, 3:end-2, :); end end
github
jacksky64/imageProcessing-master
llf.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/llf.m
1,656
utf_8
93f40bcebe4ecb248415b493e2c9e2ac
% Perform the local laplacian filter using the function % f(x,ref)=x+fact*(I-ref)*exp(-(I-ref)²/(2*sigma²)) % Perform the local laplacian filter using any function % This script implements edge-aware detail and tone manipulation as % described in : % Fast and Robust Pyramid-based Image Processing. % Mathieu Aubry, Sylvain Paris, Samuel W. Hasinoff, Jan Kautz, and Frédo Durand. % MIT technical report, November 2011 % INPUT % I : input greyscale image % r : a function handle to the remaping function % N : number discretisation values of the intensity % % OUTPUT % F : filtered image % LP : fitered laplacian pyramid % [email protected] Sept 2012 function [F, LP]=llf(I,sigma,fact,N) if numel(fact) < N fact(end:N)=fact(end); end [height, width]=size(I); n_levels=ceil(log(min(height,width))-log(2))+2; discretisation=linspace(0,1,N); discretisation_step=discretisation(2); input_gaussian_pyr=gaussian_pyramid(I,n_levels); LP=laplacian_pyramid(I,n_levels); LP{n_levels}=input_gaussian_pyr{n_levels}; pFact=1; for ref=discretisation I_remap=fact(pFact)*(I-ref).*exp(-(I-ref).*(I-ref)./(2*sigma*sigma)); pFact = pFact+1; temp_laplace_pyr=laplacian_pyramid(I_remap,n_levels); for level=1:n_levels-1 LP{level}=LP{level}+... (abs(input_gaussian_pyr{level}-ref)<discretisation_step).*... temp_laplace_pyr{level}.*... (1-abs(input_gaussian_pyr{level}-ref)/discretisation_step); end end F=reconstruct_laplacian_pyramid(LP);
github
jacksky64/imageProcessing-master
remapping_function.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/remapping_function.m
193
utf_8
39f4e6083a03bed8b5fed18c4b63f877
%This is just a toy example! function y=remapping_function(x) % y=(x-0.1).*(x>0.1)+(x+0.1).*(x<-0.1); %smoothing y=3.*x.*(abs(x)<0.1)+(x+0.2).*(x>0.1)+(x-0.2).*(x<-0.1); %enhancement end
github
jacksky64/imageProcessing-master
reconstruct_laplacian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/reconstruct_laplacian_pyramid.m
1,074
utf_8
7ba1435cc8f4ff0d1428d1179e7cd9ea
% Reconstruction of image from Laplacian pyramid % % Arguments: % pyramid 'pyr', as generated by function 'laplacian_pyramid' % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % % % More information: % 'The Laplacian Pyramid as a Compact Image Code' % Burt, P., and Adelson, E. H., % IEEE Transactions on Communication, COM-31:532-540 (1983). % function R = reconstruct_laplacian_pyramid(pyr,subwindow) r = size(pyr{1},1); c = size(pyr{1},2); nlev = length(pyr); subwindow_all = zeros(nlev,4); if ~exist('subwindow','var') subwindow_all(1,:) = [1 r 1 c]; else subwindow_all(1,:) = subwindow; end for lev = 2:nlev subwindow_all(lev,:) = child_window(subwindow_all(lev-1,:)); end % start with low pass residual R = pyr{nlev}; filter = pyramid_filter; for lev = nlev-1 : -1 : 1 % upsample, and add to current level R = pyr{lev} + upsample(R,filter,subwindow_all(lev,:)); end
github
jacksky64/imageProcessing-master
laplacian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/laplacian_pyramid.m
1,251
utf_8
8d160a39954ea8ac8ef42ee22d0f8181
% Contruction of Laplacian pyramid % % Arguments: % image 'I' % 'nlev', number of levels in the pyramid (optional) % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % % % More information: % 'The Laplacian Pyramid as a Compact Image Code' % Burt, P., and Adelson, E. H., % IEEE Transactions on Communication, COM-31:532-540 (1983). % function pyr = laplacian_pyramid(I,nlev,subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end if ~exist('nlev','var') nlev = numlevels([r c]); % build highest possible pyramid end % recursively build pyramid pyr = cell(nlev,1); filter = pyramid_filter; J = I; for l = 1:nlev - 1 % apply low pass filter, and downsample [I,subwindow_child] = downsample(J,filter,subwindow); % in each level, store difference between image and upsampled low pass version pyr{l} = J - upsample(I,filter,subwindow); J = I; % continue with low pass image subwindow = subwindow_child; end pyr{nlev} = J; % the coarest level contains the residual low pass image
github
jacksky64/imageProcessing-master
llf_general.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/llf_general.m
1,278
utf_8
7d132e2ca02f40f77332200e3a4e5f48
% Perform the local laplacian filter using any function % INPUT % I : input greyscale image % r : a function handle to the remaping function % N : number discretisation values of the intensity % % OUTPUT % F : filtered image % [email protected] Sept 2012 function [F]=llf_general(I,r,N) [height width]=size(I); n_levels=ceil(log(min(height,width))-log(2))+2; discretisation=linspace(0,1,N); discretisation_step=discretisation(2); input_gaussian_pyr=gaussian_pyramid(I,n_levels); output_laplace_pyr=laplacian_pyramid(I,n_levels); output_laplace_pyr{n_levels}=input_gaussian_pyr{n_levels}; for level=1:n_levels-1 output_laplace_pyr{level}=zeros(size(output_laplace_pyr{level})); end for ref=discretisation I_remap=r(I-ref); temp_laplace_pyr=laplacian_pyramid(I_remap,n_levels); for level=1:n_levels-1 output_laplace_pyr{level}=output_laplace_pyr{level}+... (abs(input_gaussian_pyr{level}-ref)<discretisation_step).*... temp_laplace_pyr{level}.*... (1-abs(input_gaussian_pyr{level}-ref)/discretisation_step); end end F=reconstruct_laplacian_pyramid(output_laplace_pyr);
github
jacksky64/imageProcessing-master
gaussian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/gaussian_pyramid.m
785
utf_8
c37904c322f0ffcdfb042808f7b58b42
% Construction of Gaussian pyramid % % Arguments: % image 'I' % 'nlev', number of levels in the pyramid (optional) % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % function pyr = gaussian_pyramid(I,nlev,subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end if ~exist('nlev','var') nlev = numlevels([r c]); % build highest possible pyramid end % start by copying the image to the finest level pyr = cell(nlev,1); pyr{1} = I; % recursively downsample the image filter = pyramid_filter; for l = 2:nlev I = downsample(I,filter,subwindow); pyr{l} = I; end
github
jacksky64/imageProcessing-master
pyramid_filter.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/pyramid_filter.m
415
utf_8
6bdb380bd8a557e8170203e732d1f7df
% This is a 2D separable low pass filter for constructing Gaussian and % Laplacian pyramids, built from a 1D 5-tap low pass filter. % % [email protected], August 2007 % [email protected], March 2011 [imfilter faster with 2D filter] % function f = pyramid_filter() f = [.05, .25, .4, .25, .05]; % original [Burt and Adelson, 1983] %f = [.0625, .25, .375, .25, .0625]; % binom-5 f = f'*f; end
github
jacksky64/imageProcessing-master
downsample.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/downsample.m
1,235
utf_8
aae6c458109d70f4c77f2465e543c4bf
% Downsampling procedure. % % Arguments: % 'I': image % downsampling filter 'filter', should be a 2D separable filter. % 'border_mode' should be 'circular', 'symmetric', or 'replicate'. See 'imfilter'. % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [handle subwindows, reweighted boundaries] % function [R,subwindow_child] = downsample(I, filter, subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end subwindow_child = child_window(subwindow); border_mode = 'reweighted'; %border_mode = 'symmetric'; switch border_mode case 'reweighted' % low pass, convolve with 2D separable filter R = imfilter(I,filter); % reweight, brute force weights from 1's in valid image positions Z = imfilter(ones(size(I)),filter); R = R./Z; otherwise % low pass, convolve with 2D separable filter R = imfilter(I,filter,border_mode); end % decimate reven = mod(subwindow(1),2)==0; ceven = mod(subwindow(3),2)==0; R = R(1+reven:2:r, 1+ceven:2:c, :); end
github
jacksky64/imageProcessing-master
upsample.m
.m
imageProcessing-master/HDR/local laplacian filter/fast_llf_and_style_transfer/upsample.m
1,504
utf_8
3e8cf7f9ffd5675cc72aaa396f478ffe
% Upsampling procedure. % % Argments: % 'I': image % 'filter': 2D separable upsampling filter % parent subwindow indices 'subwindow', given as [r1 r2 c1 c2] % % [email protected], August 2007 % [email protected], March 2011 [handle subwindows, reweighted boundaries] % function R = upsample(I, filter, subwindow) % increase size to match dimensions of the parent subwindow, % about 2x in each dimension r = subwindow(2) - subwindow(1) + 1; c = subwindow(4) - subwindow(3) + 1; k = size(I,3); reven = mod(subwindow(1),2)==0; ceven = mod(subwindow(3),2)==0; border_mode = 'reweighted'; %border_mode = 'symmetric'; switch border_mode case 'reweighted' % interpolate, convolve with 2D separable filter R = zeros(r,c,k); R(1+reven:2:r, 1+ceven:2:c, :) = I; R = imfilter(R,filter); % reweight, brute force weights from 1's in valid image positions Z = zeros(r,c,k); Z(1+reven:2:r, 1+ceven:2:c, :) = 1; Z = imfilter(Z,filter); R = R./Z; otherwise % increase resolution I = padarray(I,[1 1 0],'replicate'); % pad the image with a 1-pixel border R = zeros(r+4,c+4,k); R(1+reven:2:end, 1+ceven:2:end, :) = 4*I; % interpolate, convolve with 2D separable filter R = imfilter(R,filter,border_mode); % remove the border R = R(3:end-2, 3:end-2, :); end end
github
jacksky64/imageProcessing-master
reconstruct_laplacian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/reconstruct_laplacian_pyramid.m
1,074
utf_8
7ba1435cc8f4ff0d1428d1179e7cd9ea
% Reconstruction of image from Laplacian pyramid % % Arguments: % pyramid 'pyr', as generated by function 'laplacian_pyramid' % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % % % More information: % 'The Laplacian Pyramid as a Compact Image Code' % Burt, P., and Adelson, E. H., % IEEE Transactions on Communication, COM-31:532-540 (1983). % function R = reconstruct_laplacian_pyramid(pyr,subwindow) r = size(pyr{1},1); c = size(pyr{1},2); nlev = length(pyr); subwindow_all = zeros(nlev,4); if ~exist('subwindow','var') subwindow_all(1,:) = [1 r 1 c]; else subwindow_all(1,:) = subwindow; end for lev = 2:nlev subwindow_all(lev,:) = child_window(subwindow_all(lev-1,:)); end % start with low pass residual R = pyr{nlev}; filter = pyramid_filter; for lev = nlev-1 : -1 : 1 % upsample, and add to current level R = pyr{lev} + upsample(R,filter,subwindow_all(lev,:)); end
github
jacksky64/imageProcessing-master
laplacian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/laplacian_pyramid.m
1,251
utf_8
8d160a39954ea8ac8ef42ee22d0f8181
% Contruction of Laplacian pyramid % % Arguments: % image 'I' % 'nlev', number of levels in the pyramid (optional) % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % % % More information: % 'The Laplacian Pyramid as a Compact Image Code' % Burt, P., and Adelson, E. H., % IEEE Transactions on Communication, COM-31:532-540 (1983). % function pyr = laplacian_pyramid(I,nlev,subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end if ~exist('nlev','var') nlev = numlevels([r c]); % build highest possible pyramid end % recursively build pyramid pyr = cell(nlev,1); filter = pyramid_filter; J = I; for l = 1:nlev - 1 % apply low pass filter, and downsample [I,subwindow_child] = downsample(J,filter,subwindow); % in each level, store difference between image and upsampled low pass version pyr{l} = J - upsample(I,filter,subwindow); J = I; % continue with low pass image subwindow = subwindow_child; end pyr{nlev} = J; % the coarest level contains the residual low pass image
github
jacksky64/imageProcessing-master
gaussian_pyramid.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/gaussian_pyramid.m
785
utf_8
c37904c322f0ffcdfb042808f7b58b42
% Construction of Gaussian pyramid % % Arguments: % image 'I' % 'nlev', number of levels in the pyramid (optional) % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [modified to handle subwindows] % function pyr = gaussian_pyramid(I,nlev,subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end if ~exist('nlev','var') nlev = numlevels([r c]); % build highest possible pyramid end % start by copying the image to the finest level pyr = cell(nlev,1); pyr{1} = I; % recursively downsample the image filter = pyramid_filter; for l = 2:nlev I = downsample(I,filter,subwindow); pyr{l} = I; end
github
jacksky64/imageProcessing-master
pyramid_filter.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/pyramid_filter.m
415
utf_8
6bdb380bd8a557e8170203e732d1f7df
% This is a 2D separable low pass filter for constructing Gaussian and % Laplacian pyramids, built from a 1D 5-tap low pass filter. % % [email protected], August 2007 % [email protected], March 2011 [imfilter faster with 2D filter] % function f = pyramid_filter() f = [.05, .25, .4, .25, .05]; % original [Burt and Adelson, 1983] %f = [.0625, .25, .375, .25, .0625]; % binom-5 f = f'*f; end
github
jacksky64/imageProcessing-master
downsample.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/downsample.m
1,253
utf_8
bac9552fb0054bf7db559b84985e8700
% Downsampling procedure. % % Arguments: % 'I': image % downsampling filter 'filter', should be a 2D separable filter. % 'border_mode' should be 'circular', 'symmetric', or 'replicate'. See 'imfilter'. % subwindow indices 'subwindow', given as [r1 r2 c1 c2] (optional) % % [email protected], August 2007 % [email protected], March 2011 [handle subwindows, reweighted boundaries] % function [R,subwindow_child] = downsample(I, filter, subwindow) r = size(I,1); c = size(I,2); if ~exist('subwindow','var') subwindow = [1 r 1 c]; end subwindow_child = child_window(subwindow); border_mode = 'reweighted'; %border_mode = 'symmetric'; switch border_mode case 'reweighted' % low pass, convolve with 2D separable filter R = imfilter(I,filter); % reweight, brute force weights from 1's in valid image positions Z = imfilter(ones(size(I)),filter); R = R./Z; otherwise % low pass, convolve with 2D separable filter R = imfilter(I,filter,border_mode); end R(isnan(R))=0; % decimate reven = mod(subwindow(1),2)==0; ceven = mod(subwindow(3),2)==0; R = R(1+reven:2:r, 1+ceven:2:c, :); end
github
jacksky64/imageProcessing-master
lapfilter_core.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/lapfilter_core.m
3,509
utf_8
38e746962e3577fcd0c4f1ad92623cdb
% Laplacian Filtering % - public Matlab implementation for reproducibility % - about 30x slower than our single-thread C++ version % % This script implements the core image processing algorithm % described in Paris, Hasinoff, and Kautz, "Local Laplacian Filters: % Edge-aware Image Processing with a Laplacian Pyramid", ACM % Transactions on Graphics (Proc. SIGGRAPH 2011), 30(4), 2011. % % Processes an input image using a general pointwise remapping function % r(I,g0) in a pyramid-based way. Its running time is O(N log N), where % N is the number of pixels. % % Most of the code is bookkeeping to isolate the subpyramid contributing % to a particular Laplacian coefficient. See below for a 14-line naive % O(N^2) implementation that gives identical results. % % Arguments: % image 'I' % pixel-wise remapping function 'r', expects arguments r(I,g0) % % [email protected], March 2011 % function R = lapfilter_core(I,r) G = gaussian_pyramid(I); % compute input Gaussian pyramid % build up the result, one Laplacian coefficient at a time L = laplacian_pyramid(zeros(size(I))); % allocate space for result tic; for lev0 = 1:length(L)-1 hw = 3*2^lev0 - 2; % half-width of full-res footprint (conservative) fprintf('level %d (%dx%d), footprint %dx%d ... 0%',lev0,size(G{lev0},1),size(G{lev0},2),min(2*hw+1,size(I,1)),min(2*hw+1,size(I,2))); for y0 = 1:size(G{lev0},1) for x0 = 1:size(G{lev0},2) % coords in full-res image corresponding to (lev0,y0,x0) yf = (y0-1)*2^(lev0-1) + 1; xf = (x0-1)*2^(lev0-1) + 1; % subwindow in full-res image needed to evaluate (lev0,y0,x0) in result yrng = [max(1,yf-hw) min(size(I,1),yf+hw)]; xrng = [max(1,xf-hw) min(size(I,2),xf+hw)]; Isub = I(yrng(1):yrng(2),xrng(1):xrng(2),:); % use the corresponding Gaussian pyramid coefficient to remap % the full-res subwindow g0 = G{lev0}(y0,x0,:); Iremap = r(Isub,g0); % compute Laplacian pyramid for remapped subwindow Lremap = laplacian_pyramid(Iremap,lev0+1,[yrng xrng]); % bookkeeping to compute index of (lev0,y0,x0) within the % subwindow, at full-res and at current pyramid level yfc = yf - yrng(1) + 1; xfc = xf - xrng(1) + 1; yfclev0 = floor((yfc-1)/2^(lev0-1)) + 1; xfclev0 = floor((xfc-1)/2^(lev0-1)) + 1; % set coefficient in result based on the corresponding % coefficient in the remapped pyramid L{lev0}(y0,x0,:) = Lremap{lev0}(yfclev0,xfclev0,:); end fprintf('\b\b\b\b%3d%%',floor(y0/size(G{lev0},1)*100)); end fprintf('\n'); end L{end} = G{end}; % residual not affected R = reconstruct_laplacian_pyramid(L); % collapse result Laplacian pyramid toc; end %% naive O(N^2) version for reference % % G = gaussian_pyramid(I); % L = laplacian_pyramid(zeros(size(I))); % for lev0 = 1:length(L)-1 % for y0 = 1:size(G{lev0},1) % for x0 = 1:size(G{lev0},2) % g0 = G{lev0}(y0,x0,:); % Iremap = r(I,g0); % Lremap = laplacian_pyramid(Iremap,lev0+1); % L{lev0}(y0,x0,:) = Lremap{lev0}(y0,x0,:); % end % end % end % L{end} = G{end}; % R = reconstruct_laplacian_pyramid(L);
github
jacksky64/imageProcessing-master
upsample.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/upsample.m
1,504
utf_8
3e8cf7f9ffd5675cc72aaa396f478ffe
% Upsampling procedure. % % Argments: % 'I': image % 'filter': 2D separable upsampling filter % parent subwindow indices 'subwindow', given as [r1 r2 c1 c2] % % [email protected], August 2007 % [email protected], March 2011 [handle subwindows, reweighted boundaries] % function R = upsample(I, filter, subwindow) % increase size to match dimensions of the parent subwindow, % about 2x in each dimension r = subwindow(2) - subwindow(1) + 1; c = subwindow(4) - subwindow(3) + 1; k = size(I,3); reven = mod(subwindow(1),2)==0; ceven = mod(subwindow(3),2)==0; border_mode = 'reweighted'; %border_mode = 'symmetric'; switch border_mode case 'reweighted' % interpolate, convolve with 2D separable filter R = zeros(r,c,k); R(1+reven:2:r, 1+ceven:2:c, :) = I; R = imfilter(R,filter); % reweight, brute force weights from 1's in valid image positions Z = zeros(r,c,k); Z(1+reven:2:r, 1+ceven:2:c, :) = 1; Z = imfilter(Z,filter); R = R./Z; otherwise % increase resolution I = padarray(I,[1 1 0],'replicate'); % pad the image with a 1-pixel border R = zeros(r+4,c+4,k); R(1+reven:2:end, 1+ceven:2:end, :) = 4*I; % interpolate, convolve with 2D separable filter R = imfilter(R,filter,border_mode); % remove the border R = R(3:end-2, 3:end-2, :); end end
github
jacksky64/imageProcessing-master
lapfilter.m
.m
imageProcessing-master/HDR/local laplacian filter/LocalLaplacianFilter/lapfilter.m
4,599
utf_8
f47f1f7e8da1a593eb0236c448e11fd1
% Laplacian Filtering % - public Matlab implementation for reproducibility % - about 30x slower than our single-thread C++ version % % This script implements edge-aware detail and tone manipulation as % described in Paris, Hasinoff, and Kautz, "Local Laplacian Filters: % Edge-aware Image Processing with a Laplacian Pyramid", ACM % Transactions on Graphics (Proc. SIGGRAPH 2011), 30(4), 2011. % % This is a wrapper around the core algorithm (see lapfilter_core.m). % It defines the remapping function, the color treatment, the processing % domain (linear or log), and it implements simple postprocessing % for our tone mapping results. % % Arguments: % image 'I' % pixel-wise remapping parameters 'sigma_r', 'alpha', 'beta' % remapping method for color images 'colorRemapping' ['rgb' or 'lum'] % processing domain 'domain' ['lin' or 'log'] % % [email protected], April 2011 % function R = lapfilter(I,sigma_r,alpha,beta,colorRemapping,domain) % interpret the input arguments if size(I,3)==1 I = repmat(I,[1 1 3]); end if strcmp(domain,'log') sigma_r = log(sigma_r); end % detail remapping function noise_level = 0.01; function out = fd(d) out = d.^alpha; if alpha<1 tau = smooth_step(noise_level,2*noise_level,d*sigma_r); out = tau.*out + (1-tau).*d; end end % edge remapping function function out = fe(a) out = beta*a; end % define the overall pixel-wise remapping function r, using % the threshold sigma_r for edge-detail separation switch colorRemapping case 'rgb' % process pixels as vectors in RGB color space r = @(i,g0)(r_color(i,g0,sigma_r,@fd,@fe)); case 'lum' % save RGB color ratios for later, process the luminance IY = luminance(I); Iratio = I ./ repmat(IY+eps,[1 1 3]); I = IY; r = @(i,g0)(r_gray(i,g0,sigma_r,@fd,@fe)); otherwise error('invalid color remapping'); end % define the processing domain switch domain case 'lin', to_domain = @(I) I; from_domain = @(R) R; case 'log', to_domain = @(I) log(I + eps); from_domain = @(R) exp(R) - eps; otherwise error('invalid domain'); end % call the core Laplacian filtering algorithm if alpha==1 && beta==1 R = I; else I = to_domain(I); R = lapfilter_core(I,r); R = from_domain(R); end % postprocessing if strcmp(domain,'log') && beta<=1 % for tone mapping, remap middle 99% of intensities to % fixed dynamic range using a gamma curve DR_desired = 100; prc_clip = 0.5; RY = luminance(R); Rmax_clip = prctile(RY(:),100-prc_clip); Rmin_clip = prctile(RY(:),prc_clip); DR_clip = Rmax_clip/Rmin_clip; exponent = log(DR_desired)/log(DR_clip); R = max(0,R/Rmax_clip) .^ exponent; end if strcmp(colorRemapping,'lum') % if working with luminance, reintroduce color ratios R = repmat(R,[1 1 3]) .* Iratio; end % clip out of bounds intensities R = max(0,R); if beta<=1 R = min(1,R); end if strcmp(domain,'log') && beta<=1 % for tone mapping, gamma correct linear intensities for display gamma_val = 2.2; R = R.^(1/gamma_val); end %% helper functions % smooth step edge between (xmin,0) and (xmax,1) function y = smooth_step(xmin,xmax,x) y = (x - xmin)/(xmax - xmin); y = max(0,min(1,y)); y = y.^2.*(y-2).^2; end % convert RGB to grayscale intensity function Y = luminance(I) switch size(I,3), case 1, Y = I; case 3, Y = (20*I(:,:,1) + 40*I(:,:,2) + I(:,:,3))/61; end end % color remapping function function inew = r_color(i,g0,sigma_r,fd,fe) g0 = repmat(g0,[size(i,1) size(i,2) 1]); dnrm = sqrt(sum((i-g0).^2,3)); unit = (i-g0)./repmat(eps + dnrm,[1 1 3]); % detail and edge processing rd = g0 + unit.*repmat(sigma_r*fd(dnrm/sigma_r),[1 1 3]); re = g0 + unit.*repmat((fe(dnrm - sigma_r) + sigma_r),[1 1 3]); % edge-detail separation based on sigma_r threshold isedge = repmat(dnrm > sigma_r,[1 1 3]); inew = ~isedge.*rd + isedge.*re; end % grayscale remapping function function inew = r_gray(i,g0,sigma_r,fd,fe) dnrm = abs(i-g0); dsgn = sign(i-g0); % detail and edge processing rd = g0 + dsgn*sigma_r.*fd(dnrm/sigma_r); re = g0 + dsgn.*(fe(dnrm - sigma_r) + sigma_r); % edge-detail separation based on sigma_r threshold isedge = dnrm > sigma_r; inew = ~isedge.*rd + isedge.*re; end end
github
jacksky64/imageProcessing-master
reinhardLocal.m
.m
imageProcessing-master/HDR/reinhardToneMapping/reinhardLocal.m
4,460
utf_8
7bbe7ca37665d87e90fd7d181174b877
% Implements the Reinhard local tonemapping operator % % parameters: % hdr: high dynamic range radiance map, a matrix of size rows * columns * 3 % luminance map: the corresponding lumiance map of the hdr image % % % function [ ldrPic, luminanceCompressed, v, v1Final, sm ] = reinhardLocal( hdr, saturation, eps, phi ) fprintf('Computing luminance map\n'); luminanceMap = makeLuminanceMap(hdr); alpha = 1 / (2*sqrt(2)); key = 0.18; v1 = zeros(size(luminanceMap,1), size(luminanceMap,2), 8); v = zeros(size(luminanceMap,1), size(luminanceMap,2), 8); % compute nine gaussian filtered version of the hdr luminance map, such % that we can compute eight differences. Each image gets filtered by a % standard gaussian filter, each time with sigma 1.6 times higher than % the sigma of the predecessor. for scale=1:(8+1) %s = exp(sigma0 + ((scale) / range) * (sigma1 - sigma0)) * 8 s = 1.6 ^ (scale-1); sigma = alpha * s; % dicretize gaussian filter to a fixed size kernel. % a radius of 2*sigma should keep the error low enough... kernelRadius = ceil(2*sigma); kernelSize = 2*kernelRadius+1; gaussKernelHorizontal = fspecial('gaussian', [kernelSize 1], sigma); v1(:,:,scale) = conv2(luminanceMap, gaussKernelHorizontal, 'same'); gaussKernelVertical = fspecial('gaussian', [1 kernelSize], sigma); v1(:,:,scale) = conv2(v1(:,:,scale), gaussKernelVertical, 'same'); end for i = 1:8 v(:,:,i) = abs((v1(:,:,i)) - v1(:,:,i+1)) ./ ((2^phi)*key / (s^2) + v1(:,:,i)); end sm = zeros(size(v,1), size(v,2)); for i=1:size(v,1) for j=1:size(v,2) for scale=1:size(v,3) % choose the biggest possible neighbourhood where v(i,j,scale) % is still smaller than a certain epsilon. % Note that we need to choose that neighbourhood which is % as big as possible but all smaller neighbourhoods also % fulfill v(i,j,scale) < eps !!! if v(i,j,scale) > eps % if we already have a high contrast change in the % first scale we can only use that one if (scale == 1) sm(i,j) = 1; end % if we have a contrast change bigger than epsilon, we % know that in scale scale-1 the contrast change was % smaller than epsilon and use that one if (scale > 1) sm(i,j) = scale-1; end break; end end end end % all areas in the pic that have very small variations and therefore in % any scale no contrast change > epsilon will not have been found in % the loop above. % We manually need to assign them the biggest possible scale. idx = find(sm == 0); sm(idx) = 8; v1Final = zeros(size(v,1), size(v,2)); % build the local luminance map with luminance values taken % from the neighbourhoods with appropriate scale for x=1:size(v1,1) for y=1:size(v1,2) v1Final(x,y) = v1(x,y,sm(x,y)); end end % TODO: try local scaling with a/key as in the global operator. % But compute key for each chosen neighbourhood! %numPixels = size(hdr,1) * size(hdr,2); %delta = 0.0001; %key = exp((1/numPixels)*(sum(sum(log(v1Final + delta))))) %scaledLuminance = v1Final * (a/key); %luminanceCompressed = (luminanceMap* (a/key)) ./ (1 + scaledLuminance); % Do the actual tonemapping luminanceCompressed = luminanceMap ./ (1 + v1Final); % re-apply color according to Fattals paper "Gradient Domain High Dynamic % Range Compression" % (hdr(:,:,i) ./ luminance) MUST be between 0 an 1!!!! % ...but hdr often contains bigger values than luminance!!!??? % so the resulting ldr pic needs to be clamped ldrPic = ((hdr ./ luminanceMap) .^ saturation) .* luminanceCompressed; % clamp ldrPic to 1 indices = find(ldrPic > 1); ldrPic(indices) = 1;
github
jacksky64/imageProcessing-master
readDir.m
.m
imageProcessing-master/HDR/reinhardToneMapping/readDir.m
1,328
utf_8
06fe56520890b71da5d858f608656ce5
% Creates a list of all pictures and their exposure values in a certain directory. % % Note that the directory must only contain images wich are named according to the % naming conventions, otherwise this function fails. % % Filename naming conventions: % The filename of a picture must contain two numbers specifying the % exposure time of that picture. The first number specifies the nominator, % the second one the denominator. E.g. "image_1_15.jpg" specifies that this % image has been taken with an exposure of 1/15 second. function [filenames, exposures, numExposures] = readDir(dirName) filelist = dir(dirName); for i = 3:size(filelist,1) filenames{i-2} = strcat(dirName,filelist(i).name); end i = 1; for filename = filenames filename = filename{1}; [s f] = regexp(filename, '(\d+)'); nominator = filename(s(1):f(1)); denominator = filename(s(2):f(2)); exposure = str2num(nominator) / str2num(denominator); exposures(i) = exposure; i = i + 1; end % sort ascending by exposure [exposures indices] = sort(exposures); filenames = filenames(indices); % then inverse to get descending sort order exposures = exposures(end:-1:1); filenames = filenames(end:-1:1); numExposures = size(filenames,2);
github
jacksky64/imageProcessing-master
hdr.m
.m
imageProcessing-master/HDR/reinhardToneMapping/hdr.m
3,360
utf_8
5114bac202a4a9b6c79d02a9dc67b0e2
% Generates a hdr radiance map from a set of pictures % % parameters: % filenames: a list of filenames containing the differently exposed % pictures used to make a hdr from % gRed: camera response function for the red color channel % gGreen: camera response function for the green color channel % gBlue: camera response function for the blue color channel function [ hdr ] = hdr( filenames, gRed, gGreen, gBlue, w, dt ) numExposures = size(filenames,2); % read the first image to get the width and height information image = imread(filenames{1}); % pre-allocate resulting hdr image hdr = zeros(size(image)); sum = zeros(size(image)); for i=1:numExposures fprintf('Adding picture %i of %i \n', i, numExposures); image = double(imread(filenames{i})); wij = w(image + 1); sum = sum + wij; m(:,:,1) = (gRed(image(:,:,1) + 1) - dt(1,i)); m(:,:,2) = (gGreen(image(:,:,2) + 1) - dt(1,i)); m(:,:,3) = (gBlue(image(:,:,3) + 1) - dt(1,i)); % If a pixel is saturated, its information and % that gathered from all prior pictures with longer exposure times is unreliable. Thus % we ignore its influence on the weighted sum (influence of the % same pixel from prior pics with longer exposure time ignored as % well) saturatedPixels = ones(size(image)); saturatedPixelsRed = find(image(:,:,1) == 255); saturatedPixelsGreen = find(image(:,:,2) == 255); saturatedPixelsBlue = find(image(:,:,3) == 255); % Mark the saturated pixels from a certain channel in *all three* % channels dim = size(image,1) * size(image,2); saturatedPixels(saturatedPixelsRed) = 0; saturatedPixels(saturatedPixelsRed + dim) = 0; saturatedPixels(saturatedPixelsRed + 2*dim) = 0; saturatedPixels(saturatedPixelsGreen) = 0; saturatedPixels(saturatedPixelsGreen + dim) = 0; saturatedPixels(saturatedPixelsGreen + 2*dim) = 0; saturatedPixels(saturatedPixelsBlue) = 0; saturatedPixels(saturatedPixelsBlue + dim) = 0; saturatedPixels(saturatedPixelsBlue + 2*dim) = 0; % add the weighted sum of the current pic to the resulting hdr radiance map hdr = hdr + (wij .* m); % remove saturated pixels from the radiance map and the sum (saturated pixels % are zero in the saturatedPixels matrix, all others are one) hdr = hdr .* saturatedPixels; sum = sum .* saturatedPixels; end % For those pixels that even in the picture with the smallest exposure time still are % saturated we approximate the radiance only from that picture instead % of taking the weighted sum saturatedPixelIndices = find(hdr == 0); % Don't multiply with the weights since they are zero for saturated % pixels. m contains the logRadiance value from the last pic, that one % with the longest exposure time. hdr(saturatedPixelIndices) = m(saturatedPixelIndices); % Fix the sum for those pixels to avoid division by zero sum(saturatedPixelIndices) = 1; % normalize hdr = hdr ./ sum; hdr = exp(hdr);
github
jacksky64/imageProcessing-master
gsolve.m
.m
imageProcessing-master/HDR/reinhardToneMapping/gsolve.m
1,641
utf_8
6444d430ac03c9277ae2c108e8557bc5
% gsolve.m - Solve for imaging system response function % % Code taken from Paul Debevec's SIGGRAPH'97 paper "Recovering High Dynamic Range % Radiance Maps from Photographs" % % % Given a set of pixel values observed for several pixels in several % images with different exposure times, this function returns the % imaging system's response function g as well as the log film irradiance % values for the observed pixels. % % Assumes: % % Zmin = 0 % Zmax = 255 % % Arguments: % % Z(i,j) is the pixel values of pixel location number i in image j % B(j) is the log delta t, or log shutter speed, for image j % l is lamdba, the constant that determines the amount of smoothness % w(z) is the weighting function value for pixel value z % % Returns: % % g(z) is the log exposure corresponding to pixel value z % lE(i) is the log film irradiance at pixel location i % function [g,lE]=gsolve(Z,B,l,w) n = 256; A = zeros(size(Z,1)*size(Z,2)+n+1,n+size(Z,1)); b = zeros(size(A,1),1); %% Include the data-fitting equations k = 1; for i=1:size(Z,1) for j=1:size(Z,2) wij = w(Z(i,j)+1); A(k,Z(i,j)+1) = wij; A(k,n+i) = -wij; b(k,1) = wij * B(i,j); k=k+1; end end %% Fix the curve by setting its middle value to 0 A(k,129) = 1; k=k+1; %% Include the smoothness equations for i=1:n-2 A(k,i)=l*w(i+1); A(k,i+1)=-2*l*w(i+1); A(k,i+2)=l*w(i+1); k=k+1; end %% Solve the system using SVD x = A\b; g = x(1:n); lE = x(n+1:size(x,1));
github
jacksky64/imageProcessing-master
makeImageMatrix.m
.m
imageProcessing-master/HDR/reinhardToneMapping/makeImageMatrix.m
1,571
utf_8
69b3db861855ce87ae5f3348385683ba
% Takes relevant samples from the images for use in gsolve.m % % function [ zRed, zGreen, zBlue, sampleIndices ] = makeImageMatrix( filenames, numPixels ) % determine the number of differently exposed images numExposures = size(filenames,2); % Create the vector of sample indices % We need N(P-1) > (Zmax - Zmin) % Assuming the maximum (Zmax - Zmin) = 255, % N = (255 * 2) / (P-1) clearly fulfills this requirement numSamples = ceil(255*2 / (numExposures - 1)) * 2; % create a random sampling matrix, telling us which % pixels of the original image we want to sample % using ceil fits the indices into the range [1,numPixels+1], % i.e. exactly the range of indices of zInput step = numPixels / numSamples; sampleIndices = floor((1:step:numPixels)); sampleIndices = sampleIndices'; % allocate resulting matrices zRed = zeros(numSamples, numExposures); zGreen = zeros(numSamples, numExposures); zBlue = zeros(numSamples, numExposures); for i=1:numExposures % read the nth image fprintf('Reading image number %i...', i); image = imread(filenames{i}); fprintf('sampling.\n'); % sample the image for each color channel [zRedTemp, zGreenTemp, zBlueTemp] = sample(image, sampleIndices); % build the resulting, small image consisting % of samples of the original image zRed(:,i) = zRedTemp; zGreen(:,i) = zGreenTemp; zBlue(:,i) = zBlueTemp; end
github
jacksky64/imageProcessing-master
reinhardGlobal.m
.m
imageProcessing-master/HDR/reinhardToneMapping/reinhardGlobal.m
1,697
utf_8
f00242ba0ee5d065648147f23c09c89f
% Implements the Reinhard global tonemapping operator. % % parameters: % hdr: a rows * cols * 3 matrix representing a hdr radiance map % % a: defines the desired brightness level of the resulting tonemapped % picture. Lower values generate darker pictures, higher values brighter % pictures. Use values like 0.18, 0.36 or 0.72 for bright pictures, 0.09, % 0.045, ... for darker pictures. % % saturation: a value between 0 and 1 defining the desired saturation of % the resulting tonemapped image % function [ ldrPic, ldrLuminanceMap ] = reinhardGlobal( hdr, a, saturation) fprintf('Computing luminance map\n'); luminanceMap = makeLuminanceMap(hdr); numPixels = size(hdr,1) * size(hdr,2); % small delta to avoid taking log(0) when encountering black pixels in the % luminance map delta = 0.0001; % compute the key of the image, a measure of the % average logarithmic luminance, i.e. the subjective brightness of the image a human % would approximateley perceive key = exp((1/numPixels)*(sum(sum(log(luminanceMap + delta))))); % scale to desired brightness level as defined by the user scaledLuminance = luminanceMap * (a/key); % all values are now mapped to the range [0,1] ldrLuminanceMap = scaledLuminance ./ (scaledLuminance + 1); ldrPic = zeros(size(hdr)); % re-apply color according to Fattals paper "Gradient Domain High Dynamic % Range Compression" % (hdr(:,:,i) ./ luminance) MUST be between 0 an 1!!!! % ...but hdr often contains bigger values than luminance!!!??? % so the resulting ldr pic needs to be clamped ldrPic = ((hdr ./ luminanceMap) .^ saturation) .* ldrLuminanceMap; % clamp ldrPic to 1 indices = find(ldrPic > 1); ldrPic(indices) = 1;
github
jacksky64/imageProcessing-master
buildSFpyrLevs_o.m
.m
imageProcessing-master/HDR/hdr_code/buildSFpyrLevs_o.m
3,137
utf_8
c6bf7bf51213e2a73c88aa27ca2fce88
% [pyr,pind] = % buildSFpyrLevs_o(lodft,log_rad,Xrcos,Yrcos,angle,ht,nbands,ncycs,angleCyc % s,ifSave,curScale); % % Recursive function for constructing levels of a steerable pyramid. This % is called by buildSFpyr, and is not usually called directly. % Eero Simoncelli, 5/97. modified by Yuanzhen Li, 5/05, to incorporate % spatial and orientation oversampling. % Then the pyramid is really really oversampled. function [pyr,pind] = buildSFpyrLevs_o(lodft,log_rad,Xrcos,Yrcos,angle,ht,nbands,ncycs,angleCycs,ifSave,curScale); if nargin < 10 ifSave = 0; curScale = 0; % current scale, determining the index of the band to be saved end % oversampled steerable pyramids if (ht <= 0) lo0 = ifft2(ifftshift(lodft)); pyr = real(lo0(:)); pind = size(lo0); else bands = zeros(prod(size(lodft)), nbands); bind = zeros(nbands,2); % log_rad = log_rad + 1; Xrcos = Xrcos - log2(2); % shift origin of lut by 1 octave. lutsize = 1024; Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] order = nbands-1; %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) %% Thanks to Patrick Teo for writing this out :) const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); Ycosn = sqrt(const) * (cos(Xcosn)).^order; himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); angle_increment = pi/nbands/angleCycs; for b = 1:nbands angle_start = Xcosn(1)+pi*(b-1)/nbands; for jj = 1:angleCycs anglemask = pointOp(angle, Ycosn, angle_start+(jj-1)*angle_increment, Xcosn(2)-Xcosn(1)); banddft = ((-sqrt(-1))^(nbands-1)) .* lodft .* anglemask .* himask; band = ifft2(ifftshift(banddft)); if ifSave == 0 bands(:,(b-1)*angleCycs+jj) = real(band(:)); else bands_here = real(band(:)); band_ind = (curScale-1)*nbands*angleCycs + (b-1)*angleCycs + jj + 1; band_name = sprintf('band_%04d.dat', band_ind); fp = fopen(band_name, 'w'); fwrite(fp, size(band), 'int32'); fwrite(fp, bands_here, 'float32'); fclose(fp); bands = []; end bind((b-1)*angleCycs+jj,:) = size(band); end end dims = size(lodft); ctr = ceil((dims+0.5)/2); lodims = ceil((dims-0.5)/(2^ncycs)); loctr = ceil((lodims+0.5)/2); lostart = ctr-loctr+1; loend = lostart+lodims-1; log_rad_ctr = log_rad(lostart(1):loend(1),lostart(2):loend(2)); log_rad = zeros(dims); log_rad(lostart(1):loend(1),lostart(2):loend(2)) = log_rad_ctr; % angle = angle(lostart(1):loend(1),lostart(2):loend(2)); % angle = imresize(angle, dims, 'bicubic'); % lodft = lodft(lostart(1):loend(1),lostart(2):loend(2)); % lodft = imresize(lodft, dims, 'bicubic'); YIrcos = abs(sqrt(1.0 - Yrcos.^2)); lomask = pointOp(log_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); lodft = lomask .* lodft; [npyr,nind] = buildSFpyrLevs_o(lodft, log_rad, Xrcos, Yrcos, angle, ht-1, nbands, ncycs+1, angleCycs, ifSave, curScale+1); pyr = [bands(:); npyr]; pind = [bind; nind]; end
github
jacksky64/imageProcessing-master
reconSFpyrLevs_o.m
.m
imageProcessing-master/HDR/hdr_code/reconSFpyrLevs_o.m
3,430
utf_8
70b5721fdf388e97921f5322cd23403e
% resdft = % reconSFpyrLevs_o(pyr,pind,log_rad,Xrcos,Yrcos,angle,nbands,ifSave,band_in % d,levs,bands,ncycs,angleCycs); % % Recursive function for reconstructing levels of a steerable pyramid % representation. This is called by reconSFpyr, and is not usually % called directly. % Eero Simoncelli, 5/97. modified by Yuanzhen Li, 5/05, to incorporate % spatial and orientation oversampling. % Then the pyramid is really really oversampled. function resdft = reconSFpyrLevs_o(pyr,pind,log_rad,Xrcos,Yrcos,angle,nbands,ifSave,band_ind,levs,bands,ncycs,angleCycs); lo_ind = nbands*angleCycs+1;; dims = pind(1,:); ctr = ceil((dims+0.5)/2); % log_rad = log_rad + 1; Xrcos = Xrcos - log2(2); % shift origin of lut by 1 octave. if any(levs > 1) lodims = ceil((dims-0.5)/(2^((ncycs)))); loctr = ceil((lodims+0.5)/2); lostart = ctr-loctr+1; loend = lostart+lodims-1; nlog_rad_ctr = log_rad(lostart(1):loend(1),lostart(2):loend(2)); nlog_rad = zeros(dims); nlog_rad(lostart(1):loend(1),lostart(2):loend(2)) = nlog_rad_ctr; nangle = angle; % nangle = angle(lostart(1):loend(1),lostart(2):loend(2)); if (size(pind,1) > lo_ind) if ifSave == 0 nresdft = reconSFpyrLevs_o( pyr(1+sum(prod(pind(1:lo_ind-1,:)')):size(pyr,1)),... pind(lo_ind:size(pind,1),:), ... log_rad, Xrcos, Yrcos, nangle, nbands, ifSave, band_ind+angleCycs*nbands, levs-1, bands, ncycs+1, angleCycs); else nresdft = reconSFpyrLevs_o( pyr,... pind(lo_ind:size(pind,1),:), ... log_rad, Xrcos, Yrcos, nangle, nbands, ifSave, band_ind+angleCycs*nbands, levs-1, bands, ncycs+1, angleCycs); end else if ifSave == 0 nresdft = fftshift(fft2(pyrBand(pyr,pind,lo_ind))); else nresdft = fftshift(fft2(pyrBand(pyr,pind,1))); end end YIrcos = sqrt(abs(1.0 - Yrcos.^2)); lomask = pointOp(nlog_rad, YIrcos, Xrcos(1), Xrcos(2)-Xrcos(1), 0); % lomask = zeros(dims); % lomask(lostart(1):loend(1),lostart(2):loend(2)) = lomask_ctr; resdft = zeros(dims); resdft = nresdft .* lomask; else resdft = zeros(dims); end if any(levs == 1) lutsize = 1024; Xcosn = pi*[-(2*lutsize+1):(lutsize+1)]/lutsize; % [-2*pi:pi] order = nbands-1; %% divide by sqrt(sum_(n=0)^(N-1) cos(pi*n/N)^(2(N-1)) ) const = (2^(2*order))*(factorial(order)^2)/(nbands*factorial(2*order)); Ycosn = sqrt(const) * (cos(Xcosn)).^order; himask = pointOp(log_rad, Yrcos, Xrcos(1), Xrcos(2)-Xrcos(1),0); angle_increment = pi/nbands/angleCycs; ind = 1; for b = 1:nbands if any(bands == b) angle_start = Xcosn(1)+pi*(b-1)/nbands; for jj = 1:angleCycs anglemask = pointOp(angle,Ycosn,angle_start+(jj-1)*angle_increment,Xcosn(2)-Xcosn(1)); if ifSave == 0 band = reshape(pyr(ind:ind+prod(dims)-1), dims(1), dims(2)); else band_name = sprintf('band_%04d.dat', band_ind); fp = fopen(band_name, 'r'); sz = fread(fp, 2, 'int32'); band = fread(fp, sz', 'float32'); fclose(fp); band_ind = band_ind+1; end banddft = fftshift(fft2(band)); resdft = resdft + (sqrt(-1))^(nbands-1) * banddft.*anglemask.*himask/angleCycs; ind = ind + prod(dims); end end end end
github
jacksky64/imageProcessing-master
modulateFlip.m
.m
imageProcessing-master/HDR/hdr_code/modulateFlip.m
461
utf_8
92f12f8068fcf49b9863851f106a5aa3
% [HFILT] = modulateFlipShift(LFILT) % % QMF/Wavelet highpass filter construction: modulate by (-1)^n, % reverse order (and shift by one, which is handled by the convolution % routines). This is an extension of the original definition of QMF's % (e.g., see Simoncelli90). % Eero Simoncelli, 7/96. function [hfilt] = modulateFlipShift(lfilt) lfilt = lfilt(:); sz = size(lfilt,1); sz2 = ceil(sz/2); ind = [sz:-1:1]'; hfilt = lfilt(ind) .* (-1).^(ind-sz2);
github
jacksky64/imageProcessing-master
gradient_guidedfilter.m
.m
imageProcessing-master/gradientGuidedFilter/gradient_guidedfilter.m
2,466
utf_8
47bb2aa5ef4702d96d8d32ce34aa3731
function q = gradient_guidedfilter(I, p, eps) % GUIDEDFILTER O(1) time implementation of guided filter. % % - guidance image: I (should be a gray-scale/single channel image) % - filtering input image: p (should be a gray-scale/single channel image) % - regularization parameter: eps r=16; [hei, wid] = size(I); N = boxfilter(ones(hei, wid), r); % the size of each local patch; N=(2r+1)^2 except for boundary pixels. mean_I = boxfilter(I, r) ./ N; mean_p = boxfilter(p, r) ./ N; mean_Ip = boxfilter(I.*p, r) ./ N; cov_Ip = mean_Ip - mean_I .* mean_p; % this is the covariance of (I, p) in each local patch. mean_II = boxfilter(I.*I, r) ./ N; var_I = mean_II - mean_I .* mean_I; %weight epsilon=(0.001*(max(p(:))-min(p(:))))^2; r1=1; N1 = boxfilter(ones(hei, wid), r1); % the size of each local patch; N=(2r+1)^2 except for boundary pixels. mean_I1 = boxfilter(I, r1) ./ N1; mean_II1 = boxfilter(I.*I, r1) ./ N1; var_I1 = mean_II1 - mean_I1 .* mean_I1; chi_I=sqrt(abs(var_I1.*var_I)); weight=(chi_I+epsilon)/(mean(chi_I(:))+epsilon); gamma = (4/(mean(chi_I(:))-min(chi_I(:))))*(chi_I-mean(chi_I(:))); gamma = 1 - 1./(1 + exp(gamma)); %result a = (cov_Ip + (eps./weight).*gamma) ./ (var_I + (eps./weight)); b = mean_p - a .* mean_I; mean_a = boxfilter(a, r) ./ N; mean_b = boxfilter(b, r) ./ N; q = mean_a .* I + mean_b; end function imDst = boxfilter(imSrc, r) % BOXFILTER O(1) time box filtering using cumulative sum % % - Definition imDst(x, y)=sum(sum(imSrc(x-r:x+r,y-r:y+r))); % - Running time independent of r; % - Equivalent to the function: colfilt(imSrc, [2*r+1, 2*r+1], 'sliding', @sum); % - But much faster. [hei, wid] = size(imSrc); imDst = zeros(size(imSrc)); %cumulative sum over Y axis imCum = cumsum(imSrc, 1); %difference over Y axis imDst(1:r+1, :) = imCum(1+r:2*r+1, :); imDst(r+2:hei-r, :) = imCum(2*r+2:hei, :) - imCum(1:hei-2*r-1, :); imDst(hei-r+1:hei, :) = repmat(imCum(hei, :), [r, 1]) - imCum(hei-2*r:hei-r-1, :); %cumulative sum over X axis imCum = cumsum(imDst, 2); %difference over X axis imDst(:, 1:r+1) = imCum(:, 1+r:2*r+1); imDst(:, r+2:wid-r) = imCum(:, 2*r+2:wid) - imCum(:, 1:wid-2*r-1); imDst(:, wid-r+1:wid) = repmat(imCum(:, wid), [1, r]) - imCum(:, wid-2*r:wid-r-1); end
github
jacksky64/imageProcessing-master
NLMF.m
.m
imageProcessing-master/nlmeans/NLMF.m
8,859
utf_8
5102383567c3b678cd4b448e84668b79
function J=NLMF(I,Options) % This function NLMF performs Non-Local Means noise filtering of % 2D grey/color or 3D image data. The function is partly c-coded for % cpu efficient filtering. % % Principle NL-Mean filter: % A local pixel region (patch) around a pixel is compared to patches % of pixels in the neighbourhood. The centerpixels of the patches are % averaged depending on the quadratic pixel distance between the patches. % % Function: % % J = NLMF( I, Options); % % inputs, % I : 2D grey/color or 3D image data, of type Single or Double % in range [0..1] % Options : Struct with options % % outputs, % J : The NL-means filtered image or image volume % % options, % Options.kernelratio : Radius of local Patch (default 3) % Options.windowratio : Radius of neighbourhood search window (default 3) % Options.filterstrength : Strength of the NLMF filtering (default 0.05) % Options.blocksize : The image is split in sub-blocks for efficienter % memory usage, (default 2D: 150, default 3D: 32); % Options.nThreads : Number of CPU Threads used default (2); % Options.verbose : When set to true display information (default false) % % Beta Options: % Options.enablepca : Do PCA on the patches to reduce amount of % calculations (default false) % Options.pcaskip : To reduce amount of PCA calculations the data for PCA % is first reduced with V(:,1:pcaskip:end) (default 10) % Options.pcane : Number of eigenvectors used (default 25) % % Literature: % - Non local filter proposed for A. Buades, B. Coll and J.M. Morel % "A non-local algorithm for image denoising" % - Basic Matlab implementation of Jose Vicente Manjon-Herrera % % % First Compile c-code!!!!, with : % mex vectors_nlmeans_single.c -v % mex image2vectors_single.c -v % mex vectors_nlmeans_double.c -v % mex image2vectors_double.c -v % % Example 2D greyscale, % I=im2double(imread('moon.tif')); % Options.kernelratio=4; % Options.windowratio=4; % Options.verbose=true; % J=NLMF(I,Options); % figure, % subplot(1,2,1),imshow(I); title('Noisy image') % subplot(1,2,2),imshow(J); title('NL-means image'); % % Example 2D color, % I=im2double(imread('lena.jpg')); % I=imnoise(I,'gaussian',0.01); % Options.kernelratio=4; % Options.windowratio=4; % Options.verbose=true; % Options.filterstrength=0.1; % J=NLMF(I,Options); % figure, % subplot(1,2,1),imshow(I); title('Noisy image') % subplot(1,2,2),imshow(J); title('NL-means image'); % % Example 3D, % load('mri'); % D=squeeze(D); D=single(D); D=D./max(D(:)); % Options.verbose=true; % Options.blocksize=45; % V=NLMF(D,Options); % figure, % subplot(1,2,1),imshow(imresize(D(:,:,3),5),[]); title('Noisy slice') % subplot(1,2,2),imshow(imresize(V(:,:,3),5),[]); title('NL-means slice') % % See also NLMF2Dtree. % % Function is written by D.Kroon University of Twente (April 2010) if((min(I(:))<0)||(max(I(:))>1)), warning('NLMF:inputs','Preferable data range [0..1]'); end if((~isa(I,'double'))&&(~isa(I,'single'))) error('NLMF:inputs','Input data must be single or double'); end is2D=size(I,3)<4; % Process inputs defaultoptions=struct('kernelratio',3,'windowratio',3,'filterstrength',0.05,'blocksize',150,'nThreads',2,'verbose',false,'enablepca',false,'pcaskip',10,'pcane',25); if(is2D), defaultoptions.blocksize=150; else defaultoptions.blocksize=32; end if(~exist('Options','var')), Options=defaultoptions; else tags = fieldnames(defaultoptions); for i=1:length(tags), if(~isfield(Options,tags{i})), Options.(tags{i})=defaultoptions.(tags{i}); end, end if(length(tags)~=length(fieldnames(Options))), warning('NLMF:unknownoption','unknown options found'); end end kernelratio=round(Options.kernelratio); windowratio=round(Options.windowratio); filterstrength=Options.filterstrength; blocksize=round(Options.blocksize); nThreads=round(Options.nThreads); verbose=Options.verbose; enablepca=Options.enablepca; pcaskip=round(Options.pcaskip); pcane=round(Options.pcane); if(is2D) Ipad = padarray(I,[kernelratio+windowratio kernelratio+windowratio],'symmetric'); %, else Ipad = padarray(I,[kernelratio+windowratio kernelratio+windowratio kernelratio+windowratio],'symmetric'); %, end % Separate the image into smaller blocks, for less memory usage % and efficient cpu-cache usage. block=makeBlocks(kernelratio,windowratio, blocksize, I, Ipad, is2D); tic; erms='***'; J=zeros(size(I),class(Ipad)); for i=1:length(block); if(verbose) disp(['Processing Block ' num2str(i) ' of ' num2str(length(block)) ' estimated time remaining ' erms]); end if(is2D) Iblock=Ipad(block(i).x1:block(i).x2,block(i).y1:block(i).y2,:); else Iblock=Ipad(block(i).x1:block(i).x2,block(i).y1:block(i).y2,block(i).z1:block(i).z2); end if(isa(Ipad,'double')) % Get the local patches of every pixel-coordinate in the block V=image2vectors_double(double(Iblock),double(kernelratio),double(nThreads)); else V=image2vectors_single(single(Iblock),single(kernelratio),single(nThreads)); end if(enablepca) % Do PCA on the block [Evalues, Evectors, x_mean]=PCA(V(:,1:pcaskip:end),pcane); % Project the block to the reduced PCA feature space V = Evectors'*(V-repmat(x_mean,1,size(V,2))); end % Do NL-means on the vectors in the block if(isa(Ipad,'double')) Iblock_filtered=vectors_nlmeans_double(double(Iblock),double(V),double(kernelratio),double(windowratio),double(filterstrength),double(nThreads)); else Iblock_filtered=vectors_nlmeans_single(single(Iblock),single(V),single(kernelratio),single(windowratio),single(filterstrength),single(nThreads)); end if(is2D) J(block(i).x3:block(i).x4,block(i).y3:block(i).y4,:)=Iblock_filtered; else J(block(i).x3:block(i).x4,block(i).y3:block(i).y4,block(i).z3:block(i).z4)=Iblock_filtered; end if(verbose) t=toc; erm=(t/i)*(length(block)-i); erms=num2str(erm); end end toc; function block=makeBlocks(kernelratio,windowratio,blocksize, I,Ipad, is2D) block=struct; i=0; blocksize_real=blocksize-(kernelratio+windowratio)*2; if(is2D) for y1=1:blocksize_real:size(Ipad,2) for x1=1:blocksize_real:size(Ipad,1) x2=x1+blocksize-1; y2=y1+blocksize-1; x2=max(min(x2,size(Ipad,1)),1); y2=max(min(y2,size(Ipad,2)),1); x3=x1; y3=y1; x4=min(x1+blocksize_real-1,size(I,1)); y4=min(y1+blocksize_real-1,size(I,2)); if((x4>=x3)&&(y4>=y3)) i=i+1; block(i).x1=x1; block(i).y1=y1; block(i).x2=x2; block(i).y2=y2; block(i).x3=x3; block(i).y3=y3; block(i).x4=x4; block(i).y4=y4; end end end else for z1=1:blocksize_real:size(Ipad,3) for y1=1:blocksize_real:size(Ipad,2) for x1=1:blocksize_real:size(Ipad,1) x2=x1+blocksize-1; y2=y1+blocksize-1; z2=z1+blocksize-1; x2=max(min(x2,size(Ipad,1)),1); y2=max(min(y2,size(Ipad,2)),1); z2=max(min(z2,size(Ipad,3)),1); x3=x1; y3=y1; z3=z1; x4=min(x1+blocksize_real-1,size(I,1)); y4=min(y1+blocksize_real-1,size(I,2)); z4=min(z1+blocksize_real-1,size(I,3)); if((x4>=x3)&&(y4>=y3)&&(z4>=z3)) i=i+1; block(i).x1=x1; block(i).y1=y1; block(i).z1=z1; block(i).x2=x2; block(i).y2=y2; block(i).z2=z2; block(i).x3=x3; block(i).y3=y3; block(i).z3=z3; block(i).x4=x4; block(i).y4=y4; block(i).z4=z4; end end end end end function [Evalues, Evectors, x_mean]=PCA(x,ne) % PCA using Single Value Decomposition % Obtaining mean vector, eigenvectors and eigenvalues % % [Evalues, Evectors, x_mean]=PCA(x,ne); % % inputs, % X : M x N matrix with M the trainingvector length and N the number % of training data sets % ne : Max number of eigenvalues % outputs, % Evalues : The eigen values of the data % Evector : The eigen vectors of the data % x_mean : The mean training vector % s=size(x,2); % Calculate the mean x_mean=sum(x,2)/s; % Substract the mean x2=(x-repmat(x_mean,1,s))/ sqrt(s-1); % Do the SVD [U2,S2] = svds(x2,ne,'L',struct('tol',1e-4)); Evalues=diag(S2).^2; Evectors=U2;
github
jacksky64/imageProcessing-master
circ_kuipertest.m
.m
imageProcessing-master/CircularStatistics/circ_kuipertest.m
3,076
utf_8
17975f8427b61f430b01b39bea0a0b92
function [pval, k, K] = circ_kuipertest(alpha1, alpha2, res, vis_on) % [pval, k, K] = circ_kuipertest(sample1, sample2, res, vis_on) % % The Kuiper two-sample test tests whether the two samples differ % significantly.The difference can be in any property, such as mean % location and dispersion. It is a circular analogue of the % Kolmogorov-Smirnov test. % % H0: The two distributions are identical. % HA: The two distributions are different. % % Input: % alpha1 fist sample (in radians) % alpha2 second sample (in radians) % res resolution at which the cdf is evaluated % vis_on display graph % % Output: % pval p-value; the smallest of .10, .05, .02, .01, .005, .002, % .001, for which the test statistic is still higher % than the respective critical value. this is due to % the use of tabulated values. if p>.1, pval is set to 1. % k test statistic % K critical value % % References: % Batschelet, 1980, p. 112 % % Circular Statistics Toolbox for Matlab % Update 2012 % By Marc J. Velasco and Philipp Berens, 2009 % [email protected] if nargin < 3 res = 100; end if nargin < 4 vis_on = 0; end n = length(alpha1(:)); m = length(alpha2(:)); % create cdfs of both samples [phis1 cdf1 phiplot1 cdfplot1] = circ_samplecdf(alpha1, res); [foo, cdf2 phiplot2 cdfplot2] = circ_samplecdf(alpha2, res); %#ok<ASGLU> % maximal difference between sample cdfs [dplus, gdpi] = max([0 cdf1-cdf2]); [dminus, gdmi] = max([0 cdf2-cdf1]); % calculate k-statistic k = n * m * (dplus + dminus); % find p-value [pval K] = kuiperlookup(min(n,m),k/sqrt(n*m*(n+m))); K = K * sqrt(n*m*(n+m)); % visualize if vis_on figure plot(phiplot1, cdfplot1, 'b', phiplot2, cdfplot2, 'r'); hold on plot([phis1(gdpi-1), phis1(gdpi-1)], [cdf1(gdpi-1) cdf2(gdpi-1)], 'o:g'); plot([phis1(gdmi-1), phis1(gdmi-1)], [cdf1(gdmi-1) cdf2(gdmi-1)], 'o:g'); hold off set(gca, 'XLim', [0, 2*pi]); set(gca, 'YLim', [0, 1.1]); xlabel('Circular Location') ylabel('Sample CDF') title('CircStat: Kuiper test') h = legend('Sample 1', 'Sample 2', 'Location', 'Southeast'); set(h,'box','off') set(gca, 'XTick', pi*(0:.25:2)) set(gca, 'XTickLabel', {'0', '', '', '', 'pi', '', '', '', '2pi'}) end end function [p K] = kuiperlookup(n, k) load kuipertable.mat; alpha = [.10, .05, .02, .01, .005, .002, .001]; nn = ktable(:,1); %#ok<NODEF> % find correct row of the table [easy row] = ismember(n, nn); if ~easy % find closest value if no entry is present) row = length(nn) - sum(n<nn); if row == 0 error('N too small.'); else warning('N=%d not found in table, using closest N=%d present.',n,nn(row)) %#ok<WNTAG> end end % find minimal p-value and test-statistic idx = find(ktable(row,2:end)<k,1,'last'); if ~isempty(idx) p = alpha(idx); else p = 1; end K = ktable(row,idx+1); end
github
jacksky64/imageProcessing-master
circ_clust.m
.m
imageProcessing-master/CircularStatistics/circ_clust.m
3,346
utf_8
09f16d972b35b7b7b55b361710748587
function [cid, alpha, mu] = circ_clust(alpha, numclust, disp) % % [cid, alpha, mu] = circClust(alpha, numclust, disp) % Performs a simple agglomerative clustering of angular data. % % Input: % alpha sample of angles % numclust number of clusters desired, default: 2 % disp show plot at each step, default: false % % Output: % cid cluster id for each entry of alpha % alpha sorted angles, matched with cid % mu mean direction of angles in each cluster % % Run without any input arguments for demo mode. % % Circular Statistics Toolbox for Matlab % By Marc J. Velasco and Philipp Berens, 2009 % [email protected] % Distributed under Open Source BSD License if nargin < 2, numclust = 5; end; if nargin < 3, disp = 0; end if nargin < 1 % demo mode n = 20; alpha = 2*pi*rand(n,1)-pi; numclust = 4; disp = 1; end; n = length(alpha); if n < numclust, error('Not enough data for clusters.'), end % prepare data cid = (1:n)'; % main clustering loop num_unique = length(unique(cid)); num_clusters_wanted = numclust; while(num_unique > num_clusters_wanted) % find centroid means... % calculate the means for each putative cluster mu = NaN(n,1); for j=1:n if sum(cid==j)>0 mu(j) = circ_mean(alpha(cid==j)'); end end % find distance between centroids... mudist = abs(circ_dist2(mu)); % find closest pair of clusters/datapoints mindist = min(mudist(tril(ones(size(mudist)),-1)==1)); [row, col] = find(mudist==mindist); % update cluster id's cid(cid==max(row)) = min(col); % update stop criteria num_unique = length(unique(cid)); end % renumber cluster ids (so cids [1 3 7 10] => [1 2 3 4] cid2 = cid; uniquecids = unique(cid); for j=1:length(uniquecids) cid(cid2==uniquecids(j)) = j; end % compute final cluster means mu = NaN(num_unique,1); r = NaN(num_unique,1); for j=1:num_unique if sum(cid==j)>0 mu(j) = circ_mean(alpha(cid==j)'); r(j) = circ_r(alpha(cid==j)'); end end if disp % plot output z2 = exp(1i*alpha); plotColor(real(z2), imag(z2), cid, 2) zmu = r.*exp(1i*mu); plotColor(real(zmu), imag(zmu), 1:num_unique, 2, '*', 10, 1) axis square set(gca, 'XLim', [-1, 1]); set(gca, 'YLim', [-1, 1]); end function plotColor(x, y, c, varargin) % FUNCTION plotColor(x, y, c, [figurenum], [pstring], [markersize], [overlay_tf]); % plots a scatter plot for x, y, using color values in c (c should be % categorical info), with c same size as x and y; % fourth argument can be figure#, otherwise, uses figure(1); % % colors should be positive integes % copyright (c) 2009 Marc J. Velasco if nargin < 4 figurenum = 1; else figurenum = varargin{1}; end if nargin < 5 pstring = '.'; else pstring = varargin{2}; end if nargin < 6 ms = 10; else ms = varargin{3}; end if nargin < 7 overlay = 0; else overlay = varargin{4}; end csmall = unique(c); figure(figurenum); if ~overlay, close(figurenum); end figure(figurenum); colors={'y', 'b', 'r', 'g', 'c', 'k', 'm'}; hold on; for j=1:length(csmall); ci = (c == csmall(j)); plot(x(ci), y(ci), strcat(pstring, colors{mod(j, length(colors))+1}), 'MarkerSize', ms); end if ~overlay, hold off; end figure(figurenum)
github
jacksky64/imageProcessing-master
circ_raotest.m
.m
imageProcessing-master/CircularStatistics/circ_raotest.m
4,132
utf_8
a088b9d557b94032992d192ef76b8fd4
function [p U UC] = circ_raotest(alpha) % [p U UC] = circ_raotest(alpha) % Calculates Rao's spacing test by comparing distances between points on % a circle to those expected from a uniform distribution. % % H0: Data is distributed uniformly around the circle. % H1: Data is not uniformly distributed around the circle. % % Alternative to the Rayleigh test and the Omnibus test. Less powerful % than the Rayleigh test when the distribution is unimodal on a global % scale but uniform locally. % % Due to the complexity of the distributioin of the test statistic, we % resort to the tables published by % Russell, Gerald S. and Levitin, Daniel J.(1995) % 'An expanded table of probability values for rao's spacing test' % Communications in Statistics - Simulation and Computation % Therefore the reported p-value is the smallest alpha level at which the % test would still be significant. If the test is not significant at the % alpha=0.1 level, we return the critical value for alpha = 0.05 and p = % 0.5. % % Input: % alpha sample of angles % % Output: % p smallest p-value at which test would be significant % U computed value of the test-statistic u % UC critical value of the test statistic at sig-level % % % References: % Batschelet, 1981, Sec 4.6 % % Circular Statistics Toolbox for Matlab % By Philipp Berens, 2009 % [email protected] alpha = alpha(:); % for the purpose of the test, convert to angles alpha = circ_rad2ang(alpha); n = length(alpha); alpha = sort(alpha); % compute test statistic U = 0; lambda = 360/n; for j = 1:n-1 ti = alpha(j+1) - alpha(j); U = U + abs(ti - lambda); end tn = (360 - alpha(n) + alpha(1)); U = U + abs(tn-lambda); U = (1/2)*U; % get critical value from table [p UC] = getVal(n,U); function [p UC] = getVal(N, U) % Table II from Russel and Levitin, 1995 alpha = [0.001, .01, .05, .10]; table = [ 4 247.32, 221.14, 186.45, 168.02; 5 245.19, 211.93, 183.44, 168.66; 6 236.81, 206.79, 180.65, 166.30; 7 229.46, 202.55, 177.83, 165.05; 8 224.41, 198.46, 175.68, 163.56; 9 219.52, 195.27, 173.68, 162.36; 10 215.44, 192.37, 171.98, 161.23; 11 211.87, 189.88, 170.45, 160.24; 12 208.69, 187.66, 169.09, 159.33; 13 205.87, 185.68, 167.87, 158.50; 14 203.33, 183.90, 166.76, 157.75; 15 201.04, 182.28, 165.75, 157.06; 16 198.96, 180.81, 164.83, 156.43; 17 197.05, 179.46, 163.98, 155.84; 18 195.29, 178.22, 163.20, 155.29; 19 193.67, 177.08, 162.47, 154.78; 20 192.17, 176.01, 161.79, 154.31; 21 190.78, 175.02, 161.16, 153.86; 22 189.47, 174.10, 160.56, 153.44; 23 188.25, 173.23, 160.01, 153.05; 24 187.11, 172.41, 159.48, 152.68; 25 186.03, 171.64, 158.99, 152.32; 26 185.01, 170.92, 158.52, 151.99; 27 184.05, 170.23, 158.07, 151.67; 28 183.14, 169.58, 157.65, 151.37; 29 182.28, 168.96, 157.25, 151.08; 30 181.45, 168.38, 156.87, 150.80; 35 177.88, 165.81, 155.19, 149.59; 40 174.99, 163.73, 153.82, 148.60; 45 172.58, 162.00, 152.68, 147.76; 50 170.54, 160.53, 151.70, 147.05; 75 163.60, 155.49, 148.34, 144.56; 100 159.45, 152.46, 146.29, 143.03; 150 154.51, 148.84, 143.83, 141.18; 200 151.56, 146.67, 142.35, 140.06; 300 148.06, 144.09, 140.57, 138.71; 400 145.96, 142.54, 139.50, 137.89; 500 144.54, 141.48, 138.77, 137.33; 600 143.48, 140.70, 138.23, 136.91; 700 142.66, 140.09, 137.80, 136.59; 800 142.00, 139.60, 137.46, 136.33; 900 141.45, 139.19, 137.18, 136.11; 1000 140.99, 138.84, 136.94, 135.92 ]; ridx = find(table(:,1)>=N,1); cidx = find(table(ridx,2:end)<U,1); if ~isempty(cidx) UC = table(ridx,cidx+1); p = alpha(cidx); else UC = table(ridx,end-1); p = .5; end
github
jacksky64/imageProcessing-master
circ_cmtest.m
.m
imageProcessing-master/CircularStatistics/circ_cmtest.m
2,127
utf_8
b8057e2fbbbaef56584aa347fe5c81cd
function [pval med P] = circ_cmtest(varargin) % % [pval, med, P] = circ_cmtest(alpha, idx) % [pval, med, P] = circ_cmtest(alpha1, alpha2) % Non parametric multi-sample test for equal medians. Similar to a % Kruskal-Wallis test for linear data. % % H0: the s populations have equal medians % HA: the s populations have unequal medians % % Input: % alpha angles in radians % idx indicates which population the respective angle in alpha % comes from, 1:s % % Output: % pval p-value of the common median multi-sample test. Discard H0 if % pval is small. % med best estimate of shared population median if H0 is not % discarded at the 0.05 level and NaN otherwise. % P test statistic of the common median test. % % % PHB 7/19/2009 % % References: % Fisher NI, 1995 % % Circular Statistics Toolbox for Matlab % By Philipp Berens, 2009 % [email protected] - www.kyb.mpg.de/~berens/circStat.html [alpha, idx] = processInput(varargin{:}); % number of groups u = unique(idx); s = length(u); % number of samples N = length(idx); % total median med = circ_median(alpha); % compute relevant quantitites n = zeros(s,1); m = n; for t=1:s pidx = idx == u(t); n(t) = sum(pidx); d = circ_dist(alpha(pidx),med); m(t) = sum(d<0); end if any(n<10) warning('Test not applicable. Sample size in at least one group to small.') %#ok<WNTAG> end M = sum(m); P = (N^2/(M*(N-M))) * sum(m.^2 ./ n) - N*M/(N-M); pval = 1 - chi2cdf(P,s-1); if pval < 0.05 med = NaN; end function [alpha, idx] = processInput(varargin) if nargin==2 && sum(abs(round(varargin{2})-varargin{2}))>1e-5 alpha1 = varargin{1}(:); alpha2 = varargin{2}(:); alpha = [alpha1; alpha2]; idx = [ones(size(alpha1)); 2*ones(size(alpha2))]; elseif nargin==2 alpha = varargin{1}(:); idx = varargin{2}(:); if ~(size(idx,1)==size(alpha,1)) error('Input dimensions do not match.') end else error('Invalid use of circ_wwtest. Type help circ_wwtest.') end
github
jacksky64/imageProcessing-master
circ_wwtest.m
.m
imageProcessing-master/CircularStatistics/circ_wwtest.m
4,669
utf_8
2fa4cad8c08ca9d37b358392c2a3fa99
function [pval table] = circ_wwtest(varargin) % [pval, table] = circ_wwtest(alpha, idx, [w]) % [pval, table] = circ_wwtest(alpha1, alpha2, [w1, w2]) % Parametric Watson-Williams multi-sample test for equal means. Can be % used as a one-way ANOVA test for circular data. % % H0: the s populations have equal means % HA: the s populations have unequal means % % Note: % Use with binned data is only advisable if binning is finer than 10 deg. % In this case, alpha is assumed to correspond % to bin centers. % % The Watson-Williams two-sample test assumes underlying von-Mises % distributrions. All groups are assumed to have a common concentration % parameter k. % % Input: % alpha angles in radians % idx indicates which population the respective angle in alpha % comes from, 1:s % [w number of incidences in case of binned angle data] % % Output: % pval p-value of the Watson-Williams multi-sample test. Discard H0 if % pval is small. % table cell array containg the ANOVA table % % PHB 3/19/2009 % % References: % Biostatistical Analysis, J. H. Zar % % Circular Statistics Toolbox for Matlab % Update 2012 % By Philipp Berens, 2009 % [email protected] - www.kyb.mpg.de/~berens/circStat.html [alpha, idx, w] = processInput(varargin{:}); % number of groups u = unique(idx); s = length(u); % number of samples n = sum(w); % compute relevant quantitites pn = zeros(s,1); pr = pn; for t=1:s pidx = idx == u(t); pn(t) = sum(pidx.*w); pr(t) = circ_r(alpha(pidx),w(pidx)); end r = circ_r(alpha,w); rw = sum(pn.*pr)/n; % make sure assumptions are satisfied checkAssumption(rw,mean(pn)) % test statistic kk = circ_kappa(rw); beta = 1+3/(8*kk); % correction factor A = sum(pr.*pn) - r*n; B = n - sum(pr.*pn); F = beta * (n-s) * A / (s-1) / B; pval = 1 - fcdf(F,s-1,n-s); na = nargout; if na < 2 printTable; end prepareOutput; function printTable fprintf('\nANALYSIS OF VARIANCE TABLE (WATSON-WILLIAMS TEST)\n\n'); fprintf('%s\t\t\t\t%s\t%s\t\t%s\t\t%s\t\t\t%s\n', ' ' ,'d.f.', 'SS', 'MS', 'F', 'P-Value'); fprintf('--------------------------------------------------------------------\n'); fprintf('%s\t\t\t%u\t\t%.2f\t%.2f\t%.2f\t\t%.4f\n', 'Columns', s-1 , A, A/(s-1), F, pval); fprintf('%s\t\t%u\t\t%.2f\t%.2f\n', 'Residual ', n-s, B, B/(n-s)); fprintf('--------------------------------------------------------------------\n'); fprintf('%s\t\t%u\t\t%.2f', 'Total ',n-1,A+B); fprintf('\n\n') end function prepareOutput if na > 1 table = {'Source','d.f.','SS','MS','F','P-Value'; ... 'Columns', s-1 , A, A/(s-1), F, pval; ... 'Residual ', n-s, B, B/(n-s), [], []; ... 'Total',n-1,A+B,[],[],[]}; end end end function checkAssumption(rw,n) if n >= 11 && rw<.45 warning('Test not applicable. Average resultant vector length < 0.45.') %#ok<WNTAG> elseif n<11 && n>=7 && rw<.5 warning('Test not applicable. Average number of samples per population 6 < x < 11 and average resultant vector length < 0.5.') %#ok<WNTAG> elseif n>=5 && n<7 && rw<.55 warning('Test not applicable. Average number of samples per population 4 < x < 7 and average resultant vector length < 0.55.') %#ok<WNTAG> elseif n < 5 warning('Test not applicable. Average number of samples per population < 5.') %#ok<WNTAG> end end function [alpha, idx, w] = processInput(varargin) if nargin == 4 alpha1 = varargin{1}(:); alpha2 = varargin{2}(:); w1 = varargin{3}(:); w2 = varargin{4}(:); alpha = [alpha1; alpha2]; idx = [ones(size(alpha1)); ones(size(alpha2))]; w = [w1; w2]; elseif nargin==2 && sum(abs(round(varargin{2})-varargin{2}))>1e-5 alpha1 = varargin{1}(:); alpha2 = varargin{2}(:); alpha = [alpha1; alpha2]; idx = [ones(size(alpha1)); 2*ones(size(alpha2))]; w = ones(size(alpha)); elseif nargin==2 alpha = varargin{1}(:); idx = varargin{2}(:); if ~(size(idx,1)==size(alpha,1)) error('Input dimensions do not match.') end w = ones(size(alpha)); elseif nargin==3 alpha = varargin{1}(:); idx = varargin{2}(:); w = varargin{3}(:); if ~(size(idx,1)==size(alpha,1)) error('Input dimensions do not match.') end if ~(size(w,1)==size(alpha,1)) error('Input dimensions do not match.') end else error('Invalid use of circ_wwtest. Type help circ_wwtest.') end end
github
jacksky64/imageProcessing-master
GUI_16.m
.m
imageProcessing-master/Matlab UI Examples/GUI_16.m
3,364
utf_8
0ade8fba8eb8747a729134b3667dbc45
function [] = GUI_16() % Demonstrate display & change a slider's position & limits with edit boxes % This is an extension of GUI_13. Slide the slider and it's position will % be shown in the editbox. Enter a valid number in the editbox and the % slider will be moved to that position. If the number entered is outside % the range of the slider, the number will be reset. The range of the % slider will be shown in two editboxes on either side of the slider. The % user may change the range of the slider, as long as valid entries are % made. % % Suggested exercise: Notice that any number (>min) is acceptable for the % max range number, and that when max is chosen such that max < value, % value is set equal to max. Modify the code to restrict max>=value. Do % similarly for the min. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 390 100],... 'menubar','none',... 'name','GUI_16',... 'numbertitle','off',... 'resize','off'); S.sl = uicontrol('style','slide',... 'unit','pix',... 'position',[60 10 270 30],... 'min',1,'max',100,'val',50); S.ed(1) = uicontrol('style','edit',... 'unit','pix',... 'position',[10 10 40 30],... 'fontsize',12,... 'string','1'); % Displays the min. S.ed(2) = uicontrol('style','edit',... 'unit','pix',... 'position',[60 50 270 30],... 'fontsize',16,... 'string','50'); % Displays the value. S.ed(3) = uicontrol('style','edit',... 'unit','pix',... 'position',[340 10 40 30],... 'fontsize',12,... 'string','100'); % Displays the max. set([S.ed(:);S.sl],'call',{@sl_call,S}); % Shared Callback. function [] = sl_call(varargin) % Callback for the edit box and slider. [h,S] = varargin{[1,3]}; % Get calling handle and structure. SL = get(S.sl,{'min','value','max'}); % Get the slider's info. E = str2double(get(h,'string')); % Numerical edit string. switch h % Who called? case S.ed(1) if E <= SL{2} set(S.sl,'min',E) % E is less than current value. elseif E < SL{3} set(S.sl,'val',E,'min',E) % E is less than max value. set(S.ed(2),'string',E) % Set the current display. else set(h,'string',SL{1}) % Reset the value. end case S.ed(2) if E >= SL{1} && E <= SL{3} set(S.sl,'value',E) % E falls within range of slider. else set(h,'string',SL{2}) % User tried to set slider out of range. end case S.ed(3) if E >= SL{2} set(S.sl,'max',E) % E is less than current value. elseif E > SL{1} set(S.sl,'val',E,'max',E) % E is less than max value. set(S.ed(2),'string',E) % Set the current display. else set(h,'string',SL{3}) % Reset the value. end case S.sl set(S.ed(2),'string',SL{2}) % Set edit to current slider. otherwise % Do nothing end
github
jacksky64/imageProcessing-master
GUI_20.m
.m
imageProcessing-master/Matlab UI Examples/GUI_20.m
1,133
utf_8
baa2b98b80f0e2394082510ae7521e56
function [] = GUI_20() % Demonstrate how to get the chosen string from a popup. % Creates a popup and an editbox. When the user selects a choice from the % popup, this choice will appear in the editbox. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 110],... 'menubar','none',... 'name','GUI_20',... 'numbertitle','off',... 'resize','off'); S.pp = uicontrol('style','pop',... 'units','pixels',... 'position',[20 10 260 40],... 'string',{'one','two','three','four'}); S.ed = uicontrol('style','edit',... 'units','pix',... 'position',[20 60 260 30],... 'fontsize',16,'string','one'); set(S.pp,'callback',{@pp_call,S}); % Set the callback. function [] = pp_call(varargin) % Callback for the popup. S = varargin{3}; % Get the structure. P = get(S.pp,{'string','val'}); % Get the user's choice. set(S.ed,'string',P{1}{P{2}}); % Assign the user's choice to the edit.
github
jacksky64/imageProcessing-master
GUI_38.m
.m
imageProcessing-master/Matlab UI Examples/GUI_38.m
3,702
utf_8
44078247e33ee9a9b11606f99d9272d3
function [] = GUI_38() % Demonstrate bringing the focus to the figure after callback using JAVA. % This is an extension of GUI_5. In this case we have both a keypressfcn % and a buttonpressfcn for the figure. Here the word Keypress is printed % to the command window when a key is pressed while the figure has focus. % Likewise the word ButtonDown is printed to the command window when the % mouse is pressed in an area of the figure which is not over a uicontrol. % When the GUI is first created, the figure has focus, so pressing a key % triggers the keypressfcn of the figure. After pushing the pushbutton, % however, the uicontrol takes focus. In order to make it so the user does % not have to click in the figure window to give focus back to the figure, % we simulate a mouseclick in the figure at the end of the callback for the % pushbutton. In some versions of MATLAB we could do a similar thing % without calling JAVA, but here we use JAVA for the sake of using JAVA. % Note that we must write the buttondownfcn for the figure such that the % JAVA mouseclick doesn't trigger it. % % The JAVA code is taken from a newsgroup post by Jan Simon. % See Yair Altman's website for many more examples. % % Author: Matt Fig % Date: 7/15/2009 S.TF = true; S.ja = java.awt.Robot; % Define the java AWT object. S.fh = figure('units','pixels',... 'position',[300 300 300 100],... 'menubar','none',... 'name','GUI_38',... 'numbertitle','off',... 'resize','off'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[20 10 260 30],... 'string','Deleter'); S.tx = uicontrol('style','text',... 'unit','pix',... 'position',[20 50 260 30],... 'fontsize',16,... 'string','DeleteMe'); set(S.pb,'callback',{@pb_call,S}) set(S.fh,'keypressfcn',{@fh_kpfcn},'buttondownfcn',{@fh_bdfcn,S}) function [] = pb_call(varargin) % Callback for the pushbutton. S = varargin{3}; % Get the structure. T = get(S.tx,'string'); % Get the current string. if isempty(T) set(S.pb,'backgroundcolor',[1 .5 .5],'string','Nothing to Delete!') else set(S.tx,'str',T(1:end-1)); % Delete the last character in string. end pos = get(S.fh, 'Position'); % User might have moved figure. pointpos = get(0,'pointerlocation'); % Current pointer location. set(0, 'PointerLocation', [pos(1),pos(2)]); % Put pointer at corner of figure. % Now we simulate a mouseclick on the figure using the JAVA. S.TF = false; % This tells the fh_bdfcn that it was JAVA clicking. set(S.fh,'buttondownfcn',{@fh_bdfcn,S}) % Update with the new S.TF S.ja.mousePress(java.awt.event.InputEvent.BUTTON1_MASK); % Click down S.ja.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK); % Let up. set(0,'pointerlocation',pointpos); % Put the pointer back. pause(.025) % drawnow does NOT work here. S.TF = true; % So that the user's clicks in figure will work. set(S.fh,'buttondownfcn',{@fh_bdfcn,S}) % Update the structure. function [] = fh_kpfcn(varargin) % Keypressfcn for figure. disp(' Keypress') % Just so we know that it is working. function [] = fh_bdfcn(varargin) % ButtonDownFcn for figure. S = varargin{3}; if S.TF % We use the If Statement because we don't want the buttondownfcn to % execute when the button was pushed by JAVA. All code for the % function should go into here except the structure extraction. disp(' ButtonDown') % Just so we know that it is working. end
github
jacksky64/imageProcessing-master
GUI_1.m
.m
imageProcessing-master/Matlab UI Examples/GUI_1.m
1,627
utf_8
5bb190e41e18f3b455ed103f75ae8309
function [] = GUI_1() % Demonstrate how to delete an entry from a uicontrol string. % Creates a listbox with some strings in it and a pushbutton. When user % pushes the pushbutton, the selected entry in the listbox will be deleted. % % Suggested exercise: Modify the GUI so when the user deletes a certain % string, the 'value' property is set to the previous string instead of to % the first string. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[500 500 200 260],... 'menubar','none',... 'name','GUI_1',... 'numbertitle','off',... 'resize','off'); S.ls = uicontrol('style','list',... 'unit','pix',... 'position',[10 60 180 180],... 'min',0,'max',2,... 'fontsize',14,... 'string',{'one';'two';'three';'four'}); S.pb = uicontrol('style','push',... 'units','pix',... 'position',[10 10 180 40],... 'fontsize',14,... 'string','Delete String',... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for pushbutton, deletes one line from listbox. S = varargin{3}; % Get the structure. L = get(S.ls,{'string','value'}); % Get the users choice. % We need to make sure we don't try to assign an empty string. if ~isempty(L{1}) L{1}(L{2}(:)) = []; % Delete the selected strings. set(S.ls,'string',L{1},'val',1) % Set the new string. end
github
jacksky64/imageProcessing-master
GUI_2.m
.m
imageProcessing-master/Matlab UI Examples/GUI_2.m
1,937
utf_8
ccbe19a7085c9e755fea1e8abe3dbc88
function [] = GUI_2() % Demonstrate how to add a new entry to a uicontrol string. % Creates a listbox with some strings in it, an editbox and a pushbutton. % User types some text into the editbox, then pushes the pushbutton. The % user's text will be added to the top of the listbox. % % Suggested exercise: Modify the code so that hitting return after a % string is typed performs the same task as pushing the pushbutton. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[500 500 200 300],... 'menubar','none',... 'name','GUI_2',... 'numbertitle','off',... 'resize','off'); S.ls = uicontrol('style','list',... 'unit','pix',... 'position',[10 110 180 180],... 'min',0,'max',2,... 'fontsize',14,... 'string',{'one';'two';'three';'four'}); S.ed = uicontrol('style','edit',... 'unit','pix',... 'position',[10 60 180 30],... 'fontsize',14,... 'string','New String'); S.pb = uicontrol('style','push',... 'units','pix',... 'position',[10 10 180 40],... 'fontsize',14,... 'string','Add String',... 'callback',{@ed_call,S}); function [] = ed_call(varargin) % Callback for pushbutton, adds new string from edit box. S = varargin{3}; % Get the structure. oldstr = get(S.ls,'string'); % The string as it is now. addstr = {get(S.ed,'string')}; % The string to add to the stack. % The order of the args to cat puts the new string either on top or bottom. set(S.ls,'str',{addstr{:},oldstr{:}}); % Put the new string on top -OR- % set(S.ls,'str',{oldstr{:},addstr{:}}); % Put the new string on bottom.
github
jacksky64/imageProcessing-master
GUI_6.m
.m
imageProcessing-master/Matlab UI Examples/GUI_6.m
1,609
utf_8
a92f49a5c1519b7de8b0a8f74c5895e9
function [] = GUI_6() % Demonstrate how to update one uicontrol with data from others. % Creates two radiobuttons and a pushbutton. The pushbutton, when clicked % shows which radio button (or both or none) is currently selected. See % GUI_8 for similar radiobuttongroup GUI. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[400 400 120 100],... 'menubar','none',... 'name','GUI_6',... 'numbertitle','off',... 'resize','off'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[10 10 100 20],... 'string','None Selected',... 'tooltip','Push to find out which radio button is selected'); S.rd(1) = uicontrol('style','rad',... 'unit','pix',... 'position',[10 40 100 20],... 'string',' Button A'); S.rd(2) = uicontrol('style','rad',... 'unit','pix',... 'position',[10 70 100 20],... 'string',' Button B'); set(S.pb,'callback',{@pb_call,S}); % Set the callback, pass hands. function [] = pb_call(varargin) % Callback for pushbutton. S = varargin{3}; % Get structure. R = [get(S.rd(1),'val'), get(S.rd(2),'val')]; % Get state of radios. str = 'Both selected'; % Default string. if R(1)==1 && R(2)==0 str = 'A selected'; elseif R(1)==0 && R(2)==1 str = 'B selected'; elseif ~any(R) str = 'None selected'; end set(S.pb,'string',str)
github
jacksky64/imageProcessing-master
GUI_9.m
.m
imageProcessing-master/Matlab UI Examples/GUI_9.m
1,832
utf_8
049a8148696cd0dd87ab8010f5120f23
function [] = GUI_9() % Demonstrate one way to let the user know a process is running. % Creates a pushbutton which, when pushed, simulates some process running % in the background and lets the user know this is happening by a text and % color change. When the process is finished, the button returns to % normal. CAREFULLY READ THE COMMENTS BELOW IF YOU PLAN ON USING THIS % METHOD IN ONE OF YOUR GUIs. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 200 100],... 'menubar','none',... 'name','GUI_9',... 'numbertitle','off',... 'resize','off'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[20 20 160 60],... 'string','Push Me',... 'callback',{@pb_call},... 'backgroundc',[0.94 .94 .94],... 'busyaction','cancel',...% So multiple pushes don't stack. 'interrupt','off'); function [] = pb_call(varargin) % Callback for pushbutton. h = varargin{1}; % Get the caller's handle. col = get(h,'backg'); % Get the background color of the figure. set(h,'str','RUNNING...','backg',[1 .6 .6]) % Change color of button. % The pause (or drawnow) is necessary to make button changes appear. % To see what this means, try doing this with the pause commented out. pause(.01) % FLUSH the event queue, drawnow would work too. % Here is where you put whatever function calls or processes that the % pushbutton is supposed to activate. % Next we simulate some running process. Here just sort a vector. A = rand(3000000,1); A = sort(A); %#ok set(h,'str','Push Me','backg',col) % Now reset the button features.
github
jacksky64/imageProcessing-master
GUI_15.m
.m
imageProcessing-master/Matlab UI Examples/GUI_15.m
1,799
utf_8
db5ef0ce111da9a90faa1acc1583df6e
function [] = GUI_15() % Demonstrate an edit text which has copyable but unchangeable text. % Also creates a pushbutton which will print the contents of the % editbox to the command line. % % Suggested exercise: Notice that the text can be cut (as well as copied). % Alter the keypressfcn to eliminate this. % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 400 120],... 'menubar','none',... 'name','GUI_15',... 'numbertitle','off',... 'resize','off'); S.ed = uicontrol('style','edit',... 'unit','pix',... 'position',[30 70 340 30],... 'string','This text can be copied but not changed'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[30 30 340 30],... 'string','Print to screen'); set([S.ed,S.pb],{'callback'},{{@ed_call,S};{@pb_call,S}}) % Set callbacks. set(S.ed,'keypressfcn',{@ed_kpfcn,S}) % set keypressfcn. function [] = pb_call(varargin) % callback for pushbutton S = varargin{3}; % Get the structure. disp(get(S.ed,'string')) % Print to the command line. function [] = ed_call(varargin) % Callback for edit S = varargin{3}; % Get the structure. set (S.ed,'string','This text can be copied but not changed'); function [] = ed_kpfcn(varargin) % Keypressfcn for edit [K,S] = varargin{[2 3]}; if isempty(K.Modifier) uicontrol(S.pb) set (S.ed,'string','This text can be copied but not changed'); elseif ~strcmp(K.Key,'c') && ~strcmp(K.Modifier{1},'control') uicontrol(S.pb) set (S.ed,'string','This text can be copied but not changed'); end
github
jacksky64/imageProcessing-master
GUI_19.m
.m
imageProcessing-master/Matlab UI Examples/GUI_19.m
2,094
utf_8
586a4c51186bd7847e7c5f59c893935f
function [] = GUI_19() % Demonstrate how to keep track of the number of times an action is taken % and the number of arguments passed. Here pressing both buttons % calls the same function (pb2_call), but pushing button one calls pb2_call % from it's own callback. Thus the number of arguments received in % pb2_call is different depending on how it is called. Pushing either % button prints to the command window both the total number of button % pushes and the number of input arguments used in the latest call. % % % Author: Matt Fig % Date: 7/15/2009 S.CNT = 0; % This keeps track of how many times the buttons are pushed. S.fh = figure('units','pixels',... 'position',[500 500 200 50],... 'menubar','none',... 'numbertitle','off',... 'name','GUI_19',... 'resize','off'); S.pb(1) = uicontrol('style','push',... 'units','pixels',... 'position',[10 10 85 30],... 'fontsize',14,... 'string','PUSH_1'); S.pb(2) = uicontrol('style','push',... 'units','pixels',... 'position',[105 10 85 30],... 'fonts',14,... 'str','PUSH_2'); set(S.pb(:),{'callback'},{{@pb1_call,S};{@pb2_call,S}}) % Set callbacks. function [] = pb1_call(varargin) % Callback for the button labeled PUSH_1. [h,S] = varargin{[1,3]}; % Extract the calling handle and structure. pb2_call(h,S) % call the other button's callback. function [] = pb2_call(varargin) % Callback for PUSH_2, and the function that pb1_call calls. N = numel(varargin); Ns = num2str(N-1); % String representation used with fprintf S = varargin{N}; % Extract the structure. S.CNT = S.CNT + 1; % The call counter. fprintf('\t\t%s%i\n','Call number: ',S.CNT) fprintf('\t\t%s%i%s\n',['PUSH_',Ns,' called me with : '],N,' arguments.') % Now we need to make sure that the new value of CNT is available. set(S.pb(:),{'callback'},{{@pb1_call,S};{@pb2_call,S}})
github
jacksky64/imageProcessing-master
GUI_8.m
.m
imageProcessing-master/Matlab UI Examples/GUI_8.m
2,634
utf_8
1f3059cf182891a1acc2715a22c78418
function [] = GUI_8() % Demonstrate how to tell which button in a uibuttongroup is selected. % Similar to GUI_6 except that a uibuttongroup which enforces exclusivity % is used. % % Suggested exercise: Make the editbox change the selected radiobutton. % Be sure to check that user input is valid. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 250 200],... 'menubar','none',... 'name','GUI_8',... 'numbertitle','off',... 'resize','off'); S.bg = uibuttongroup('units','pix',... 'pos',[20 100 210 90]); S.rd(1) = uicontrol(S.bg,... 'style','rad',... 'unit','pix',... 'position',[20 50 70 30],... 'string','Radio 1'); S.rd(2) = uicontrol(S.bg,... 'style','rad',... 'unit','pix',... 'position',[20 10 70 30],... 'string','Radio 2'); S.rd(3) = uicontrol(S.bg,... 'style','rad',... 'unit','pix',... 'position',[120 50 70 30],... 'string','Radio 3'); S.rd(4) = uicontrol(S.bg,... 'style','rad',... 'unit','pix',... 'position',[120 10 70 30],... 'string','Radio 4'); S.ed = uicontrol('style','edit',... 'unit','pix',... 'position',[100 60 50 30],... 'string','1'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[75 20 100 30],... 'string','Get Current Radio',... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for pushbutton. S = varargin{3}; % Get the structure. % Instead of switch, we could use num2str on: % find(get(S.bg,'selectedobject')==S.rd) (or similar) % Note the use of findobj. This is because of a BUG in MATLAB, whereby if % the user selects the same button twice, the selectedobject property will % not work correctly. switch findobj(get(S.bg,'selectedobject')) case S.rd(1) set(S.ed,'string','1') % Set the editbox string. case S.rd(2) set(S.ed,'string','2') case S.rd(3) set(S.ed,'string','3') case S.rd(4) set(S.ed,'string','4') otherwise set(S.ed,'string','None!') % Very unlikely I think. end
github
jacksky64/imageProcessing-master
GUI_5.m
.m
imageProcessing-master/Matlab UI Examples/GUI_5.m
1,525
utf_8
4ee2461f9de603988c188da542d2e991
function [] = GUI_5() % Demonstrate how to use a pushbutton to delete bits of string and how to % let the user know that their actions are futile. After the string is % deleted completely, the user is informed that there is nothing left to % delete if the delete button is pressed again. A color change accompanies % this announcement. % % Suggested exercise: Add a counter to S that starts incrementing when the % warning is given. If the user clicks again, close the GUI. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[300 300 300 100],... 'menubar','none',... 'name','GUI_5',... 'numbertitle','off',... 'resize','off'); S.pb = uicontrol('style','push',... 'unit','pix',... 'position',[20 10 260 30],... 'string','Deleter'); S.tx = uicontrol('style','text',... 'unit','pix',... 'position',[20 50 260 30],... 'fontsize',16,... 'string','DeleteMe'); set(S.pb,'callback',{@pb_call,S}) % Set the callback for pushbutton. function [] = pb_call(varargin) % Callback for the pushbutton. S = varargin{3}; % Get the structure. T = get(S.tx,'string'); % Get the current string. if isempty(T) set(S.pb,'backgroundcolor',[1 .5 .5],'string','Nothing to Delete!') else set(S.tx,'str',T(1:end-1)); % Delete the last character in string. end
github
jacksky64/imageProcessing-master
GUI_23.m
.m
imageProcessing-master/Matlab UI Examples/GUI_23.m
2,040
utf_8
ac3bb7697141c7d263c367f5cde8a1dd
function [] = GUI_23() % Demonstrate finding which figure was current before callback execution. % Usage: % % Call GUI_23, then create several plots, for example: % % GUI_23 % x = 0:.1:10; % figure;plot(x,x);figure;plot(x,x.^2);figure;plot(x,x.^3) % % Now click on whichever of the figures needs a title. % Enter the title in the GUI_23 editbox, then push the button. % Clicking on a different figure will make it receive the next title. % GUI_23 can also be called AFTER the figures have been created. % % If no figure exists, one will be created with the title found in the edit % box. % % Suggested exercise: Alter the code so that an xlabel and ylabel % also are added. This could be done by making 2 more edits, and having % the pushbutton use the information from all 3 edits to do the job. % % % Author: Matt Fig % Date: 7/15/2009 S.fh = figure('units','pixels',... 'position',[500 500 350 50],... 'menubar','none',... 'numbertitle','off',... 'name','GUI_23',... 'resize','off'); S.ed = uicontrol('style','edit',... 'units','pixels',... 'position',[10 10 220 30],... 'fontsize',14,... 'string','Enter Title'); S.pb = uicontrol('style','push',... 'units','pixels',... 'position',[240 10 100 30],... 'fonts',14,... 'str','Insert Title',... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for the button labeled PUSH_1. S = varargin{3}; % Get the structure. AX = findobj('type','axes'); % Look for existing axes objects. if isempty(AX) % The GUI could popup a message box saying, "No axes to title!" or % something similar, then return from here. figure AX = axes; end title(AX(1),get(S.ed,'string')) % The first one in the list was current!
github
jacksky64/imageProcessing-master
GUI_10.m
.m
imageProcessing-master/Matlab UI Examples/GUI_10.m
1,516
utf_8
991bcbe0ca314951ec2fd784f8592d1e
function [] = GUI_10() % Demonstrate how to make an image visible or invisible by pushbutton. % Pushing the pushbutton makes the image appear and disappear to the user. % Many people have trouble with this because just setting the axes property % does not do the job. % % % Author: Matt Fig % Date: 1/15/2010 S.fh = figure('units','pixels',... 'position',[200 200 200 200],... 'menubar','none',... 'numbertitle','off',... 'name','GUI_10',... 'resize','off'); S.ax = axes('units','pixels',... 'position',[30 50 160 140]); S.im = load('clown'); % This is a built-in ML example. S.R = image(S.im.X); % Display the image on S.ax. colormap(S.im.map); % Set the figure's colormap. set(S.ax,'xtick',[],'ytick',[]) % Get rid of ticks. S.pb = uicontrol('style','push',... 'units','pixels',... 'position',[10 10 180 30],... 'fontsize',14,... 'string','INVISIBLE/VISIBLE',... 'callback',{@pb_call,S}); function [] = pb_call(varargin) % Callback for the pushbutton. S = varargin{3}; % Get the structure. switch get(S.R,'visible') case 'on' st = 'off'; case 'off' st = 'on'; otherwise close(S.fh) % It would be very strange to end up here. error('An unknown error occured in the callback') end set([S.R,S.ax],'visible',st) % Set BOTH the image and axis visibility.