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
|
im_hist_equalize.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_hist_equalize.m
| 888 |
utf_8
|
f3f11d9287d170ff8356974bbc4a06aa
|
%IM_HIST_EQUALIZE Histogram equalization of images stored in a dataset
% (DIP_Image)
%
% B = IM_HIST_EQUALIZE(A)
% B = A*IM_HIST_EQUALIZE
%
% INPUT
% A Dataset with object images dataset (possibly multi-band)
%
% OUTPUT
% B Dataset with filtered images
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE, HIST_EQUALIZE
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_hist_equalize(a)
prtrace(mfilename);
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed');
b = setname(b,'Image hist_equalize');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename);
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = 1.0*dip_image(a);
b = hist_equalize(a);
end
return
|
github
|
jacksky64/imageProcessing-master
|
isvaldset.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isvaldset.m
| 1,837 |
utf_8
|
150731368016a57335890b7883d2442c
|
%ISVALDSET Test whether the argument is a valid dataset
%
% N = ISVALDSET(A);
% N = ISVALDSET(A,M);
% N = ISVALDSET(A,M,C);
%
% INPUT
% A Input argument, to be tested on dataset
% M Minimum number of objects per class in A
% C Minimum number of classes in A
%
% OUTPUT
% N 1/0 if A is / isn't a valid dataset
%
% DESCRIPTION
% Test whether A is a proper dataset with at least C classes.
% For crisp datasets this function tests whether A is a dataset that has
% at least M objects per class and C classes.
% For datasets with soft or targets labels it is tested whether A has at
% least M objects.
%
% SEE ALSO
% ISDATASET, ISMAPPING, ISDATAIM, ISFEATIM, ISCOMDSET
function n = isvaldset(a,m,c)
prtrace(mfilename);
if nargin < 3 | isempty(c), c = 0; end
if nargin < 2 | isempty(m), m = 1; end
if nargout == 0
isdataset(a);
else
n = 1;
if ~isdataset(a)
n = 0;
return
end
end
if c > 0 & getsize(a,3) == 0
if nargout == 0
error([newline 'Labeled dataset expected'])
else
n = 0;
end
elseif getsize(a,3) < c
if nargout == 0
error([newline 'Dataset should have at least ' num2str(c) ' classes'])
else
n = 0;
end
end
if islabtype(a,'crisp') & any(classsizes(a) < m)
if nargout == 0
if m == 1
error([newline 'Classes should have at least one object.' newline ...
'Remove empty classes by A = remclass(A).'])
else
cn = num2str(m);
error([newline 'Classes should have at least ' cn ' objects.' ...
newline 'Remove small classes by A = remclass(A,' cn ')'])
end
else
n = 0;
end
end
if islabtype(a,'soft','targets') & size(a,1) < m
error([newline 'Dataset should have at least ' num2str(m) ' objects'])
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_label.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_label.m
| 1,355 |
utf_8
|
7dbcb468c8d8516bcb86e204f0003626
|
%IM_LABEL Labeling of binary images stored in a dataset (DIP_Image)
%
% B = IM_LABEL(A,CONNECTIVITY,MIN_SIZE,MAX_SIZE)
% B = A*IM_LABEL([],CONNECTIVITY,MIN_SIZE,MAX_SIZE)
%
% INPUT
% A Dataset with binary object images dataset (possibly multi-band)
% N Number of iterations (default 1)
% CONNECTIVITY See LABEL
% MIN_SIZE Minimum size of objects to be labeled (default 0)
% MAX_SIZE Maximum size of objects to be labeled (default 0: all)
%
% OUTPUT
% B Dataset with labeled images
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE, LABEL
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_label(a,connect,minsize,maxsize)
prtrace(mfilename);
if nargin < 4 | isempty(maxsize), maxsize = 0; end
if nargin < 3 | isempty(minsize), minsize = 0; end
if nargin < 2 | isempty(connect), connect = 2; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{connect,minsize,maxsize});
b = setname(b,'Image labeling');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,{connect,minsize,maxsize});
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = dip_image(a,'bin');
b = double(label(a,connect,minsize,maxsize));
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_gaussf.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_gaussf.m
| 1,311 |
utf_8
|
4cc0d1ee779b18cb90b369721be95fa6
|
%IM_GAUSSF Gaussian filter of images stored in a dataset (DIPImage)
%
% B = IM_GAUSSF(A,S)
% B = A*IM_GAUSSF([],S)
%
% INPUT
% A Dataset with object images dataset (possibly multi-band)
% S Desired standard deviation for filter, default S = 1
%
% OUTPUT
% B Dataset with Gaussian filtered images
%
% DESCRIPTION
% All, possibly multi-band, 2D images in A are Gaussian filtered using the
% DIPImage command GAUSSF.
% In case DIPImage is not available, IM_GAUSS may be used.
%
% SEE ALSO
% DATASETS, DATAFILES, DIPIMAGE, GAUSSF, IM_GAUSS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_gaussf(a,s)
prtrace(mfilename);
if ~isdipimage
error('DipImage not available, use im_gauss instead of im_gaussf')
end
if nargin < 2 | isempty(s), s = 1; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',s);
b = setname(b,'Gaussian filter');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,s);
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
n = size(a,3);
b = zeros(size(a));
for j=1:n
aa = 1.0*dip_image(a(:,:,j));
b(:,:,j) = double(gaussf(aa,s));
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
featself.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featself.m
| 2,272 |
utf_8
|
9ae66ecdd6ab7bfbe60e1d20c6df8412
|
%FEATSELF Forward feature selection for classification
%
% [W,R] = FEATSELF(A,CRIT,K,T,FID)
% [W,R] = FEATSELF(A,CRIT,K,N,FID)
%
% INPUT
% A Training dataset
% CRIT Name of the criterion or untrained mapping
% (default: 'NN', i.e. the 1-Nearest Neighbor error)
% K Number of features to select (default: K = 0, return optimal set)
% T Tuning dataset (optional)
% N Number of cross-validations (optional)
% FID File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% W Output feature selection mapping
% R Matrix with step-by-step results
%
% DESCRIPTION
% Forward selection of K features using the dataset A. CRIT sets the
% criterion used by the feature evaluation routine FEATEVAL. If the
% dataset T is given, it is used as test set for FEATEVAL. Alternatvely a
% a number of cross-validation N may be supplied. For K = 0, the optimal
% feature set (corresponding to the maximum value of FEATEVAL) is returned.
% The result W can be used for selecting features using B*W.
% The selected features are stored in W.DATA and can be found by +W.
% In R, the search is reported step by step as:
%
% R(:,1) : number of features
% R(:,2) : criterion value
% R(:,3) : added / deleted feature
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELLR, FEATSEL,
% FEATSELO, FEATSELB, FEATSELI, FEATSELP, FEATSELM, PRPROGRESS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: featself.m,v 1.3 2007/04/21 23:06:46 duin Exp $
function [w,r] = featself(a,crit,ksel,t,fid)
prtrace(mfilename);
if (nargin < 2) | isempty(crit)
prwarning(2,'no criterion specified, assuming NN');
crit = 'NN';
end
if (nargin < 3) | isempty(ksel)
ksel = 0;
end
if (nargin < 4)
prwarning(3,'no tuning set supplied (risk of overfit)');
t = [];
end
if (nargin < 5)
fid = [];
end
if nargin == 0 | isempty(a)
% Create an empty mapping:
w = mapping(mfilename,{crit,ksel,t});
else
prprogress(fid,'\nfeatself : Forward Feature Selection')
[w,r] = featsellr(a,crit,ksel,1,0,t,fid);
prprogress(fid,'featself finished\n')
end
w = setname(w,'Forward FeatSel');
return
|
github
|
jacksky64/imageProcessing-master
|
featseli.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featseli.m
| 2,740 |
utf_8
|
fe8af121437cd0badb3e0fdde5f714d8
|
%FEATSELI Individual feature selection for classification
%
% [W,R] = FEATSELI(A,CRIT,K,T)
%
% INPUT
% A Training dataset
% CRIT Name of the criterion or untrained mapping
% (default: 'NN', i.e. the 1-Nearest Neighbor error)
% K Number of features to select (default: sort all features)
% T Tuning dataset (optional)
%
% OUTPUT
% W Feature selection mapping
% R Matrix with criterion values
%
% DESCRIPTION
% Individual selection of K features using the dataset A. CRIT sets the
% criterion used by the feature evaluation routine FEATEVAL. If the dataset
% T is given, it is used as test set for FEATEVAL. For K = 0 all features are
% selected, but reordered according to the criterion. The result W can be
% used for selecting features using B*W.
% The selected features are stored in W.DATA and can be found by +W.
% In R, the search is reported step by step as:
%
% R(:,1) : number of features
% R(:,2) : criterion value
% R(:,3) : added / deleted feature
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELF,
% FEATSEL, FEATSELP, FEATSELM
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: featseli.m,v 1.5 2009/07/01 07:48:05 davidt Exp $
function [w,r] = featseli(a,crit,ksel,t)
prtrace(mfilename);
if (nargin < 2) | isempty(crit)
prwarning(2,'no criterion specified, assuming NN');
crit = 'NN';
end
if (nargin < 3 | isempty(ksel))
ksel = 0;
end
if (nargin < 4)
prwarning(3,'no tuning set supplied (risk of overfit)');
t = [];
end
% If no arguments are supplied, return an untrained mapping.
if (nargin == 0) | (isempty(a))
w = mapping('featseli',{crit,ksel,t});
w = setname(w,'Individual FeatSel');
return
end
[m,k,c] = getsize(a); featlist = getfeatlab(a);
% If KSEL is not given, return all features.
if (ksel == 0), ksel = k; end
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a);
iscomdset(a,t);
critval = zeros(k,1);
% Evaluate each feature in turn.
s = sprintf('Evaluation of %i features: ',k);
prwaitbar(k,s);
if (isempty(t))
for j = 1:k
prwaitbar(k,j,[s int2str(j)]);
critval(j) = feateval(a(:,j),crit);
end
else
for j = 1:k
prwaitbar(k,j,[s int2str(j)]);
critval(j) = feateval(a(:,j),crit,t(:,j));
end
end
prwaitbar(0);
% Sort the features by criterion value (maximum first).
[critval_sorted,J] = sort(-critval);
r = [[1:k]', -critval_sorted, J];
J = J(1:ksel)';
% Return the mapping found.
w = featsel(k,J);
if ~isempty(featlist)
w = setlabels(w,featlist(J,:));
end
w = setname(w,'Individual FeatSel');
return
|
github
|
jacksky64/imageProcessing-master
|
typp.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/typp.m
| 1,043 |
utf_8
|
8d294b9b1229f66b0f727b0811f2242d
|
%TYPP list M-File of PRTools
% TYPE foo.bar lists the ascii file called 'foo.bar'.
%
% TYPE foo lists the ascii file called 'foo.m'.
%
% If files called foo and foo.m both exist, then
% TYPE foo lists the file 'foo', and
% TYPE foo.m list the file 'foo.m'.
%
% TYPE FILENAME lists the contents of the file given a full pathname
% or a MATLABPATH relative partial pathname (see PARTIALPATH).
%
% See also DBTYPE, WHICH, HELP, PARTIALPATH.
%
% This routine is overloaded by PRTools replacing tabs by two spaces
function typp(file)
[pp,prtools_dir,ext] =fileparts(fileparts(which('typp')));
[pp,file_dir,ext] =fileparts(fileparts(which(file)));
if strcmp(prtools_dir,file_dir) & exist(file)==2
fid = fopen([deblank(file),'.m'],'r');
if fid < 0
builtin('type',file);
else
s = fscanf(fid,'%c');
r = [];
w = [0,find(s==9)];
for j = 1:length(w)-1
r = [r,s(w(j)+1:w(j+1)-1),32,32];
end
r = [r,s(w(end)+1:end)];
r = setstr(r);
disp(r)
fclose(fid);
end
else
builtin('type',file);
end
|
github
|
jacksky64/imageProcessing-master
|
meanc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/meanc.m
| 1,652 |
utf_8
|
484801a53d01ab23a3259fb7ea43a1d8
|
%MEANC Mean combining classifier
%
% W = MEANC(V)
% W = V*MEANC
%
% INPUT
% V Set of classifiers (optional)
%
% OUTPUT
% W Mean combiner
%
% DESCRIPTION
% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the same
% classes and W is the mean combiner: it selects the class with the mean of
% the outputs of the input classifiers. This might also be used as
% A*[V1,V2,V3]*MEANC in which A is a dataset to be classified.
%
% If it is desired to operate on posterior probabilities then the input
% classifiers should be extended like V = V*CLASSC;
%
% For affine mappings the coefficients may be averaged instead of the
% classifier results by using AVERAGEC.
%
% The base classifiers may be combined in a stacked way (operating in the
% same feature space by V = [V1,V2,V3, ... ] or in a parallel way
% (operating in different feature spaces) by V = [V1;V2;V3; ... ]
%
% EXAMPLES
% PREX_COMBINING
%
% SEE ALSO
% MAPPINGS, DATASETS, VOTEC, MAXC, MINC, MEDIANC, PRODC,
% AVERAGEC, STACKED, PARALLEL
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: meanc.m,v 1.3 2010/06/01 08:48:55 duin Exp $
function w = meanc(p1)
type = 'mean'; % define the operation processed by FIXEDCC.
name = 'Mean combiner'; % define the name of the combiner.
% this is the general procedure for all possible
% calls of fixed combiners handled by FIXEDCC
if nargin == 0
w = mapping('fixedcc','combiner',{[],type,name});
else
w = fixedcc(p1,[],type,name);
end
if isa(w,'mapping')
w = setname(w,name);
end
return
|
github
|
jacksky64/imageProcessing-master
|
adaboostc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/adaboostc.m
| 3,756 |
utf_8
|
622ed5621261168b9796ffdf4e57b129
|
%ADABOOSTC
%
% [W,V,ALF] = ADABOOSTC(A,CLASSF,N,RULE,VERBOSE);
%
% INPUT
% A Dataset
% CLASSF Untrained weak classifier
% N Number of classifiers to be trained
% RULE Combining rule (default: weighted voting)
% VERBOSE Suppress progress report if 0 (default)
%
% OUTPUT
% W Combined trained classifier
% V Cell array of all classifiers
% Use VC = stacked(V) for combining
% ALF Weights
%
% DESCRIPTION
%
% Computation of a combined classifier according to adaboost.
%
% In total N weighted versions of the training set A are generated
% iteratevely and used for the training of the specified classifier.
% Weights, to be used for the probabilities of the objects in the training
% set to be selected, are updated according to the Adaboost rule.
%
% The entire set of generated classifiers is given in V.
% The set of classifier weigths, according to Adaboost is returned in ALF
%
% Various aggregating possibilities can be given in
% the final parameter rule:
% []: WVOTEC, weighted voting.
% VOTEC voting
% MEANC sum rule
% AVERAGEC averaging of coeffients (for linear combiners)
% PRODC product rule
% MAXC maximum rule
% MINC minimum rule
% MEDIANC median rule
%
% REFERENCE
% Ji Zhu, Saharon Rosset, Hui Zhou and Trevor Hastie,
% Multiclass Adaboost. A multiclass generalization of the Adaboost
% algorithm, based on a generalization of the exponential loss.
% http://www-stat.stanford.edu/~hastie/Papers/samme.pdf
%
% SEE ALSO
% MAPPINGS, DATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% (Multiclass correction by Marcin Budka, Bournemouth Univ., UK)
function [W,V,alf] = adaboostc(a,clasf,n,rule,verbose)
prtrace(mfilename);
%%INITIALISATION
if nargin < 5, verbose = 0; end
if nargin < 4, rule = []; end
if nargin < 3, n = 100; end
if nargin < 2 || isempty(clasf), clasf = nmc; end
if nargin < 1 || isempty(a)
W = mapping(mfilename,{clasf,n,rule,verbose});
W = setname(W,'Adaboost');
return
end
[m,k,c] = getsize(a);
V = [];
laba = getlab(a);
%lablist = getlablist(a);
%laba = getnlab(a);
%p = getprior(a);
%a = dataset(a,laba); % use numeric labels for speed
%a = setprior(a,p);
u = ones(m,1)/m; % initialise object weights
alf = zeros(1,n); % space for classifier weights
if verbose > 0 && k == 2
figure(verbose);
scatterd(a);
end
%% generate n classifiers
for i = 1:n
b = gendatw(a,u,m); % sample training set
b = setprior(b,getprior(a)); % use original priors
w = b*clasf; % train weak classifier
ra = a*w; % test weak classifier
if verbose && k == 2
plotc(w,1); drawnow
end
labc = labeld(ra);
diff = sum(labc~=laba,2)~=0; % objects erroneously classified
erra = sum((diff).*u); % weighted error on original dataset
if (erra < (1-1/c)) % if classifier better then random guessing...
alf(i) = 0.5*(log((1-erra)/erra) + log(c-1));
correct = find(diff==0); % find correctly classified objects
wrong = find(diff==1); % find incorrectly classified objects
u(correct) = u(correct)*exp(-alf(i)); % give them the ...
u(wrong) = u(wrong)*exp(alf(i)); % proper weights
u = u./sum(u); % normalize weights
else
alf(i) = 0;
end
%w = setlabels(w,lablist); % restore original labels
if verbose
disp([erra alf(i) sum(alf)])
end
V = [V w]; % store all classifiers
end
%% combine and return
if isempty(rule)
W = wvotec(V,alf); % default is weighted combiner
else
W = traincc(a,V,rule); % otherwise, use user supplied combiner
end
if verbose > 0 && k == 2
plotc(W,'r',3)
ee = a*W*testc;
title(['Error: ', num2str(ee)]);
end
return
|
github
|
jacksky64/imageProcessing-master
|
cmapm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/cmapm.m
| 5,624 |
utf_8
|
7d0c1c3f05b31ca8840e7529ff33c3c6
|
%CMAPM Compute some special maps
%
% INPUT
% Various
%
% OUTPUT
% W Mapping
%
% DESCRIPTION
% CMAPM computes some special data-independent maps for scaling, selecting or
% rotating K-dimensional feature spaces.
%
% W = CMAPM(K,N) Selects the features listed in the vector N
% W = CMAPM(K,P) Polynomial feature map. P should be an N*K matrix
% in which each row defines the exponents for the
% original features in a polynomial term. Note: for
% N = 1 and/or K = 1, feature selection is applied!
% W = CMAPM(K,'EXP') Exponential, negative exponential and logarithmic
% W = CMAPM(K,'NEXP') mappings.
% W = CMAPM(K,'LOG')
% W = CMAPM(K,'RANDROT') Defines a random K-dimensional rotation.
% W = CMAPM(F,'ROT') The N*K matrix F defines N linear combinations
% to be computed by X*F'.
% W = CMAPM(X,'SHIFT') Defines a shift of the origin by X.
% W = CMAPM(S,'SCALE') Divides the features by the components of the
% vector S.
% W = CMAPM({X,S},'SCALE') Shift by X and scale by S.
%
% EXAMPLES
% For the polynomial feature map, CMAPM(K,P), P defines exponents for each
% feature. So P = [1 0; 0 1; 1 1; 2 0; 0 2; 3 0; 0 3] defines 7 features,
% the original 2 (e.g. x and y), a mixture (xy) and all powers of the second
% (x^2,y^2) and third (x^3,y^3) order. Another example is P = diag([0.5 0.5
% 0.5]), defining 3 features to be the square roots of the original ones.
%
% SEE ALSO
% MAPPINGS, SCALEM, FEATSELM, KLM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: cmapm.m,v 1.5 2010/02/08 15:31:48 duin Exp $
function w = cmapm(arg1,arg2,par1,par2,par3)
prtrace(mfilename);
if (nargin < 2)
error('insufficient arguments');
end
if (~isa(arg1,'dataset'))
% First form: ARG1 is a matrix, construct a mapping.
data = arg1;
if (isstr(arg2))
type = arg2;
switch (type)
case {'exp','nexp','log'} % Function mappings.
w = mapping(mfilename,'fixed',{type},[],data,data);
w = setname(w,type);
case 'randrot' % Random rotation matrix.
[F,V] = preig(covm(randn(100*data,data)));
w = affine(F,zeros(1,data));
w = setname(w,'Random Rotation');
case 'rot' % Rotation by given matrix.
[n,k] = size(data);
w = affine(data',zeros(1,n));
w = setname(w,'Rotation');
case 'shift' % Shift by given vector.
k = length(data);
w = affine(eye(k),-data);
w = setname(w,'Shift');
case 'scale' % Shift, scale & (optionally) clip.
if (iscell(data))
% Extract and check parameters.
shift = data{1}; scale = data{2};
if (length(data) == 3), clip = data{3}; else, clip = 0; end
k = length(scale);
if (~isempty(scale)) & (length(shift) ~= k)
error('shift and scale should have same dimension')
end
else
% Only a scale is specified; set shift and clip to 0.
scale = data; k = length(scale);
shift = zeros(1,k); clip = 0;
end
% Create mapping
if (clip)
w = mapping(mfilename,'fixed',{'normalize',shift,ones(1,k)./scale,clip},[],k,k);
w = setname(w,'Scaling');
else
w = affine(1./scale,-shift./scale);
end
otherwise
error(['unknown option ' arg2])
end
else
% ARG2 is not a string: feature selection or polynomial mapping.
if (min(size(arg2)) == 1)
% ARG2 is a vector: feature selection, DATA is input feature size
prwarning(4,'second input argument is a vector: performing feature selection');
if (min(arg2) < 1) | (max(arg2) > data)
error('Selected features out of range')
end
w = mapping(mfilename,'fixed',{'featsel',arg2},[],data,length(arg2));
w = setname(w,'Feature Selection');
else
% ARG2 is a matrix: polynomial mapping.
prwarning(4,'second input argument is a matrix: performing polynomial mapping');
[n,k] = size(arg2);
if (data ~= k)
error('matrix has wrong size')
else
w = mapping(mfilename,'fixed',{'polynomial',arg2},[],k,n);
w = setname(w,'Polynomial');
end
end
end
else
% Second form: ARG1 is a dataset, execute some fixed mappings
a = +arg1; [m,k] = size(a); % Extract dataset.
featlist = getfeatlab(arg1);
type = arg2;
switch (type)
case 'exp'
b = exp(a);
case 'nexp'
b = exp(-a);
case 'log'
b = log(a);
case 'normalize'
b = a - repmat(par1,m,1); % Subtract mean (par1).
% Multiply by scale; use different ways of looping for small and
% P = diag([0.5 0.5 0.5])
% large feature sizes
if (m > k), for j = 1:k, b(:,j) = b(:,j)*par2(j); end
else, for i = 1:m, b(i,:) = b(i,:).*par2; end
end
% Clip, if necessary (par3 ~= 0, see SCALEM).
if (exist('par3')) & (par3)
J = find(b < 0); b(J) = zeros(size(J)); % Set values < 0 to 0...
J = find(b > 1); b(J) = ones(size(J)); % ...and values > 1 to 1.
end
case 'featsel'
b = a(:,par1); % Select feature indices (par1).
if ~isempty(featlist)
featlist = featlist(par1,:);
end
case 'polynomial'
[n,k] = size(par1); % Create polynomial features.
b = zeros(m,n);
for i = 1:n
b(:,i) = prod((a .^ (repmat(par1(i,:),m,1))),2);
end
featlist = [1:n]';
otherwise
error('unknown mapping')
end
w = setdata(arg1,b,featlist);
end
return
|
github
|
jacksky64/imageProcessing-master
|
knnm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/knnm.m
| 2,438 |
utf_8
|
e61eb7d473cd279fa7c748f9ad089245
|
%KNNM K-Nearest Neighbour based density estimate
%
% W = KNNM(A,KNN)
%
% D = B*W
%
% INPUT
% A Dataset
% KNN Number of nearest neighbours
%
% OUTPUT
% W Density estimate
%
% DESCRIPTION
% A density estimator is constructed based on the k-Nearest Neighbour rule
% using the labeled objects in A. All objects, however, are used if the
% entire dataset is unlabeled or if A is not a dataset, but a double.
% In all cases, just single density estimator W is computed.
% Class priors in A are neglected.
%
% The mapping W may be applied to a new dataset B using DENSITY = B*W.
%
% SEE ALSO
% DATASETS, MAPPINGS, KNNC, QDC, PARZENM, GAUSSM
% $Id: knnm.m,v 1.6 2009/02/02 22:11:27 duin Exp $
function w = knnm(a,arg2)
prtrace(mfilename);
if (nargin < 2)
prwarning(2,'number of neighbours to use not specified, assuming 1');
arg2 = 1;
end
mapname = 'KNN Density Estimation';
if (nargin < 1) | (isempty(a)) % No arguments given: return empty mapping.
w = mapping(mfilename,arg2);
w = setname(w,mapname);
elseif (~isa(arg2,'mapping')) % Train a mapping.
knn = arg2;
if isa(a,'dataset')
labname = getname(a);
else
labname = '';
end
if (~isdataset(a) & ~isdatafile(a)) | getsize(a,3) ~= 1
w = mclassm(a,mapping(mfilename,knn),'weight');
w = setlabels(w,labname);
w = setname(w,mapname);
return
return
end
islabtype(a,'crisp');
isvaldfile(a,1);
a = testdatasize(a,'objects');
a = remclass(a);
[m,k] = size(a);
w = mapping(mfilename,'trained',{a,knn},labname,k,1);
w = setname(w,mapname);
else % Execute a trained mapping V.
v = arg2;
b = v.data{1}; % B is the original training data.
knn = v.data{2};
%iscomdset(a,b,0);
[m,k] = size(b);
u = scalem(b,'variance');
a = a*u;
b = b*u;
d = sqrt(distm(+a,+b)); % Calculate squared distances
[s,J] = sort(d,2); % and find nearest neighbours.
ss = s(:,knn); % Find furthest neighbour
ss(find(ss==0)) = realmin.^(1/k); % Avoid zero distances
f = knn./(m*nsphere(k)*(ss.^k)); % Normalize by the volume of sphere
% defined by the furthest neighbour.
f = f*prod(u.data.rot); % Correct for scaling
w = setdat(a,f,v); % proper normalisation has still to be done.
end
return
function v = nsphere(k)
% Volume k-dimensional sphere
v = (2*(pi^(k/2))) / (k*gamma(k/2));
return
|
github
|
jacksky64/imageProcessing-master
|
polyc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/polyc.m
| 2,421 |
utf_8
|
044939bf2b4794fc73056fb724c2ac1f
|
%POLYC Polynomial Classification
%
% W = polyc(A,CLASSF,N,S)
%
% INPUT
% A Dataset
% CLASSF Untrained classifier (optional; default: FISHERC)
% N Degree of polynomial (optional; default: 1)
% S 1/0, 1 indicates that 2nd order combination terms should be used
% (optional; default: 0)
%
% OUTPUT
% W Trained classifier
%
% DESCRIPTION
% Adds polynomial features to the dataset A and runs the untrained
% classifier CLASSF. Combinations of 2nd order terms may be constructed.
% For higher order terms no combinations are generated.
%
% SEE ALSO
% DATASETS, MAPPINGS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: polyc.m,v 1.3 2007/04/13 09:30:54 duin Exp $
function W = polyc(a,classf,n,s)
prtrace(mfilename);
if nargin < 4,
prwarning(4,'S is not specified, assuming 0, i.e. no higher order terms.');
s = 0;
end
if nargin < 3 | isempty(n),
prwarning(4,'N, the degree of polynomial is not specified, assuming 1.');
n = 1;
end
if (nargin < 2) | (isempty(classf)),
prwarning(4,'CLASSF is not specified, assuming FISHERC.');
classf = fisherc;
end
% No data, return an untrained mapping.
if nargin < 1 | isempty(a)
W = mapping('polyc',{classf,n,s});
W = setname(W,'Polynomial classifier');
return;
end
% Checks for the classifier.
ismapping(classf);
isuntrained(classf);
% Construct the 'feature-construction'-matrix such that:
% x_new = x*cmapm(k,P);
% See CMAPM.
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a,'features');
a = setprior(a,getprior(a));
[m,k] = size(a);
% First all the terms involving the same degree are defined.
% Degree 1
P = eye(k);
% Degree 2 and higher.
for j = 2:n
P = [P; j*eye(k)];
end
% On request, all the terms involving combinations of different degrees.
if s & (k > 1) & n > 1
% All pairs of features (including their higher degree variants) have
% to be included.
Q = zeros(k*(k-1)/2,k);
n = 0;
for j1 = 1:k
for j2 = j1+1:k
n = n+1;
Q(n,j2) = Q(n,j2)+1;
Q(n,j1) = Q(n,j1)+1;
end
end
P = [P;Q];
end
% Define the mapping from P, apply it to A and train the classifier.
v = cmapm(k,P);
w = a*v*classf;
W = v*w;
W = setname(W,'Polynomial classifier');
W = setcost(W,a);
return;
|
github
|
jacksky64/imageProcessing-master
|
confmat.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/confmat.m
| 7,695 |
utf_8
|
0d64b6fb4a10caf99417d1eda2878c7a
|
%CONFMAT Construct confusion matrix
%
% [C,NE,LABLIST] = CONFMAT(LAB1,LAB2,METHOD,FID)
%
% INPUT
% LAB1 Set of labels
% LAB2 Set of labels
% METHOD 'count' (default) to count number of co-occurences in
% LAB1 and LAB2, 'disagreement' to count relative
% non-co-occurrence.
% FID Write text result to file
%
% OUTPUT
% C Confusion matrix
% NE Total number of errors (empty labels are neglected)
% LABLIST Unique labels in LAB1 and LAB2
%
% DESCRIPTION
% Constructs a confusion matrix C between two sets of labels LAB1
% (corresponding to the rows in C) and LAB2 (the columns in C). The order of
% the rows and columns is returned in LABLIST. NE is the total number of
% errors (sum of non-diagonal elements in C).
%
% When METHOD = 'count' (default), co-occurences in LAB1 and LAB2 are counted
% and returned in C. When METHOD = 'disagreement', the relative disagreement
% is returned in NE, and is split over all combinations of labels in C
% (such that the rows sum to 1). (The total disagreement for a class equals
% one minus the sensitivity for that class as computed by TESTC).
%
% [C,NE,LABLIST] = CONFMAT(D,METHOD)
%
% If D is a classification result D = A*W, the labels LAB1 and LAB2 are
% internally retrieved by CONFMAT before computing the confusion matrix.
%
% C = CONFMAT(D)
%
% This call also applies in case in D = A*W the dataset A has soft labels
% W is trained by a soft labeld classifier.
%
% When no output argument is specified, or when FID is given, the
% confusion matrix is displayed or written a to a text file. It is assumed
% that LAB1 contains true labels and LAB2 stores estimated labels.
%
% EXAMPLE
% Typical use of CONFMAT is the comparison of true and and estimated labels
% of a testset A by application to a trained classifier W:
% LAB1 = GETLABELS(A); LAB2 = A*W*LABELD.
% More examples can be found in PREX_CONFMAT, PREX_MATCHLAB.
%
% SEE ALSO
% MAPPINGS, DATASETS, GETLABELS, LABELD
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: confmat.m,v 1.8 2010/06/01 08:45:31 duin Exp $
function [CC,ne,lablist1,lablist2] = confmat (arg1,arg2,arg3,fid)
prtrace(mfilename);
% Check arguments.
if nargin < 4, fid = 1; end
if nargin < 3 | isempty(arg3)
if isdataset(arg1)
if islabtype(arg1,'crisp')
lablist1 = getlablist(arg1);
nlab1 = getnlab(arg1);
lab2 = arg1*labeld;
nlab2 = renumlab(lab2,lablist1); % try to fit on original lablist
if any(nlab2==0) % doesn't fit: contruct its own one
[nlab2,lablist2] = renumlab(lab2);
else
lablist2 = lablist1;
end
if nargin < 2| isempty(arg2)
method = 'count';
prwarning(4,'no method supplied, assuming count');
else
method = arg2;
end
elseif islabtype(arg1,'soft')
true_labs = gettargets(arg1);
if any(true_labs > 1 | true_labs < 0)
error('True soft labels should be between 0 and 1')
end
est_labs = +arg1;
if any(est_labs > 1 | est_labs < 0)
error('Estimated soft labels should be between 0 and 1')
end
C = true_labs'*est_labs;
output(C,getlablist(arg1),getfeatlab(arg1),'soft',fid);
return
else
error('Confusion matrix can only be computed for crisp and soft labeld datasets')
end
else
method = 'count';
prwarning(4,'no method supplied, assuming count');
if (nargin < 2 | isempty(arg2))
error('Second label list not supplied')
end
[nlab1,lablist1] = renumlab(arg1);
[nlab2,lablist2] = renumlab(arg2);
end
else
[nlab1,lablist1] = renumlab(arg1);
[nlab2,lablist2] = renumlab(arg2);
%lab1 = arg1;
%lab2 = arg2;
method = arg3;
end
if nargin < 2
if ~isdataset(arg1)
error('two labellists or one dataset should be supplied')
end
end
% Renumber LAB1 and LAB2 and find number of unique labels.
m = size(nlab1,1);
if (m~=size(nlab2,1))
error('LAB1 and LAB2 have to have the same lengths.');
end
n1 = size(lablist1,1);
n2 = size(lablist2,1);
n = max(n1,n2);
% Construct matrix of co-occurences (confusion matrix).
C = zeros(n1+1,n2+1);
for i = 0:n1
K = find(nlab1==i);
if (isempty(K))
C(i+1,:) = zeros(1,n2+1);
else
for j = 0:n2
C(i+1,j+1) = length(find(nlab2(K)==j));
end
end
end
% position rejects and unlabeled object at the end of the matrix
D = C;
D(1:end-1,1:end-1) = C(2:end,2:end);
D(end,:) = [C(1,2:end) C(1,1)];
D(1:end-1,end) = C(2:end,1);
C = D;
D = D(1:end-1,1:end-1);
DD = D(1:min(n1,n2),1:min(n1,n2));
% Calculate number of errors ('count') or disagreement ('disagreement').
% Neglect rejects
switch (method)
case 'count'
J = find(nlab1~=0 & nlab2~=0);
ne = nlabcmp(lablist1(nlab1(J),:),lablist2(nlab2(J),:));
case 'disagreement'
ne = (sum(sum(D)) - sum(diag(DD)))/m; % Relative sum of off-diagonal
ne = ne/m; % entries.
E = repmat(sum(D,2),1,n2); % Disagreement = 1 -
D = ones(n1,n2)-D./E; % relative co-occurence.
D = D / (n-1);
otherwise
error('unknown method');
end
%Distinguish 'rejects / no_labels' from 'non_rejects / fully labeled'
if (any(C(:,end) ~= 0) | any(C(end,:)~=0)) & strcmp(method,'count')
n1 = n1+1; n2 = n2+1;
labch = char(strlab(lablist2),'reject');
labcv = char(strlab(lablist1),'No');
else
labch = strlab(lablist2);
labcv = strlab(lablist1);
%labcv = labch;
C = D;
end
% If no output argument is specified, pretty-print C.
if (nargout == 0) | nargin == 4
output(C,labcv,labch,method,fid)
end
if nargout > 0
CC = C;
end
return
function output(C,labcv,labch,method,fid)
n1 = size(labcv,1);
n2 = size(labch,1);
% Make sure labels are stored in LABC as matrix of characters,
% max. 6 per label.
if (size(labch,2) > 6)
labch = labch(:,1:6);
%labcv = labcv(:,1:6);
end
if (size(labch,2) < 5)
labch = [labch repmat(' ',n2,ceil((5-size(labch,2))/2))];
labcv = [labcv repmat(' ',n1,ceil((5-size(labcv,2))/2))];
end
%C = round(1000*C./repmat(sum(C,2),1,size(C,2)));
nspace = max(size(labcv,2)-7,0);
cspace = repmat(' ',1,nspace);
%fprintf(fid,['\n' cspace ' | Estimated Labels']);
fprintf(fid,['\n True ' cspace '| Estimated Labels']);
fprintf(fid,['\n Labels ' cspace '|']);
for j = 1:n2, fprintf(fid,'%7s',labch(j,:)); end
fprintf(fid,'|');
fprintf(fid,' Totals');
fprintf(fid,'\n ');
fprintf(fid,repmat('-',1,8+nspace));
fprintf(fid,'|%s',repmat('-',1,7*n2));
fprintf(fid,'|-------');
fprintf(fid,'\n ');
for j = 1:n1
fprintf(fid,' %-7s|',labcv(j,:));
switch (method)
case 'count'
fprintf(fid,'%5i ',C(j,:)');
fprintf(fid,'|');
fprintf(fid,'%5i',sum(C(j,:)));
case 'disagreement'
fprintf(fid,' %5.3f ',C(j,:)');
fprintf(fid,'|');
fprintf(fid,' %5.3f ',sum(C(j,:)));
case 'soft'
fprintf(fid,' %5.2f ',C(j,:)');
fprintf(fid,'|');
fprintf(fid,' %5.2f ',sum(C(j,:)));
end
fprintf(fid,'\n ');
end
fprintf(fid,repmat('-',1,8+nspace));
fprintf(fid,'|%s',repmat('-',1,7*n2));
fprintf(fid,'|-------');
fprintf(fid,['\n Totals ' cspace '|']);
switch (method)
case 'count'
fprintf(fid,'%5i ',sum(C));
fprintf(fid,'|');
fprintf(fid,'%5i',sum(C(:)));
case 'disagreement'
fprintf(fid,' %5.3f ',sum(C));
fprintf(fid,'|');
fprintf(fid,' %5.3f ',sum(C));
case 'soft'
fprintf(fid,' %5.2f ',C(j,:)');
fprintf(fid,'|');
fprintf(fid,' %5.2f ',sum(C(:)));
end
fprintf(fid,'\n\n');
return
|
github
|
jacksky64/imageProcessing-master
|
dps.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/dps.m
| 3,849 |
utf_8
|
940a25b59ab5d19f49a72df1b888cd6a
|
% DPS Correntropy based, hierarchical density preserving data split
%
% R = DPS(A,LEVELS,CLASSWISE)
% [R H] = DPS(A,LEVELS,CLASSWISE)
%
% INPUT
% A Input dataset
% LEVELS Number of split levels, default: 3
% CLASSWISE Use (1, default) or ignore (0) label information
%
% OUTPUT
% R Index array with rotation set with 2^LEVELS folds
% H Hierarchy of splits
%
% DESCRIPTION
% Density Preserving Sampling (DPS) divides the input dataset into a given
% number of folds (2^LEVELS) by maximizing the correntropy between the folds
% and can be used as an alternative for cross-validation. The procedure is
% deterministic, so unlike cross-validation it does not need to be repeated.
%
% REFERENCE
% Budka, M., Gabrys, B., 2010. Correntropy-based density-preserving data
% sampling as an alternative to standard cross-validation. (Accepted for
% publication in Proceedings of the International Joint Conference on
% Neural Networks, IJCNN 2010, part of the IEEE World Congress on Computational
% Intelligence, WCCI 2010, Barcelona, Spain, July 18-23, 2010)
% http://www.budka.co.uk/
function [R H] = dps(A,levels,classwise)
if (nargin<3) || isempty(classwise), classwise = 1; end
if (nargin<2) || isempty(levels), levels = 3; end
islabtype(A,'crisp');
H = zeros(levels,size(A,1));
idxs = cell(1,levels+1);
idxs{1} = {1:size(A,1)};
for i = 1:levels
for j = 1:2^(i-1)
t = helper(A(idxs{i}{j},:),classwise);
idxs{i+1}{2*j-1} = idxs{i}{j}(t{1});
idxs{i+1}{2*j} = idxs{i}{j}(t{2});
end
for j = 1:length(idxs{i+1})
H(i,idxs{i+1}{j}) = j;
end
end
R = H(end,:);
end
function idxs = helper(A,classwise)
% if the classes aro too small to be divided further, switch to classless mode
if classwise && all(classsizes(A)>2), c = getsize(A,3);
else classwise = 0; c = 1;
end
siz = zeros(2,1);
idx = cell(1,c);
for i = 1:c
if classwise, [B BI] = seldat(A,i); % select i-th class
else B = A; BI = (1:size(A,1));
end
m = length(BI);
mask = true(1,m); % mask is used for counting remaining objects
D = +distm(B) + diag(inf(m,1)); % working distance matrix
Dorg = D; % original distance matrix
idx{i} = nan(2,ceil(m/2));
for j = 1:floor(m/2)
[mD,I] = min(D,[],1); % \
[mmD,J] = min(mD); % find two closest objects
I = I(J(1)); J = J(1); % /
mask(I) = 0; mask(J) = 0; % mark them as used
% split the objects to maximally increase coverage of both subsets
if (mean(Dorg(I,idx{i}(1,1:j-1))) + mean(Dorg(J,idx{i}(2,1:j-1))) < ...
mean(Dorg(I,idx{i}(2,1:j-1))) + mean(Dorg(J,idx{i}(1,1:j-1))))
idx{i}(1,j) = J;
idx{i}(2,j) = I;
else
idx{i}(1,j) = I;
idx{i}(2,j) = J;
end
% remove used objects from the distance matrix
D(I,:) = inf; D(:,I) = inf;
D(J,:) = inf; D(:,J) = inf;
end
if isempty(j), j = 0; end % in case the loop is not entered at all
% odd number of points in class
if sum(mask)>0
I = find(mask);
if siz(1)<siz(2)
idx{i}(1,end) = I;
elseif siz(1)>siz(2)
idx{i}(2,end) = I;
else
if (mean(Dorg(I,idx{i}(1,1:j))) < mean(Dorg(I,idx{i}(2,1:j))))
idx{i}(2,j+1) = I;
else
idx{i}(1,j+1) = I;
end
end
end
% convert indexes from class-specific to dataset-specific
idx{i}(1,~isnan(idx{i}(1,:))) = BI(idx{i}(1,~isnan(idx{i}(1,:))));
idx{i}(2,~isnan(idx{i}(2,:))) = BI(idx{i}(2,~isnan(idx{i}(2,:))));
% update fold sizes
siz(1) = siz(1) + sum(~isnan(idx{i}(1,:)));
siz(2) = siz(2) + sum(~isnan(idx{i}(2,:)));
end
idx = cell2mat(idx);
idxs = cell(1,2);
idxs{1} = idx(1,~isnan(idx(1,:)));
idxs{2} = idx(2,~isnan(idx(2,:)));
end
|
github
|
jacksky64/imageProcessing-master
|
reorderclasses.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/reorderclasses.m
| 3,660 |
utf_8
|
0f7203be264e07c19eb91ce888d8c812
|
%REORDERCLASSES Reorder the lablist
%
% X = REORDERCLASSES(X,LABLIST)
% X = REORDERCLASSES(X,I)
%
% INPUT
% X (labeled) dataset
% LABLIST correctly ordered lablist
% I permutation vector
%
% OUTPUT
% X dataset with reordered classes
%
% DESCRIPTION
% Change the order of the classes in dataset X to the one defined in
% LABLIST. When only a single class label is given in LABLIST, this
% class is put in the first position, and the others are just kept in
% the order they already were.
%
% For example, when I have a dataset A with a labellist {'apple'
% 'banana' 'pear'} and I perform B=REORDERCLASS(A,3) (or identically
% B=REORDERCLASS(A,[3 1 2])), I will get a dataset B with a new
% labellist of {'pear' 'apple' 'banana'}.
%
% SEE ALSO
% RENUMLAB
% Copyright: D.M.J. Tax, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function x = reorderclasses(x,lablist)
% First deal with the situation that lablist is a cellarray:
if isa(lablist,'cell')
if isa(lablist{1},'char')
lablist = strvcat(lablist);
else % it should be a double...
if ~isa(lablist,'double')
error('Only stringlabels or numeric labels are allowed.');
end
lablist = cell2mat(lablist);
end
end
% ... and make sure numerical labels are column vectors
if isa(lablist,'double')
lablist = lablist(:);
end
ll = getlablist(x);
c = size(ll,1);
% Second deal with the situation that we only supplied a single 'target
% class':
if size(lablist,1)==1
if isa(lablist,'char') % the single label is a string:
matchnr = strmatch(lablist,ll);
if isempty(matchnr)
error('Cannot find %s in the dataset.',lablist);
end
else % the single label is a number:
% is this number a class label, or the index in the lablist??
if (lablist<1) | (lablist>c)
% probably a class label
matchnr = find(lablist==ll);
if isempty(matchnr)
error('Cannot find %d in the dataset.',lablist);
end
else
matchnr = lablist;
end
end
% make a complete permutation matrix:
lablist = (1:c)';
lablist(matchnr) = [];
lablist = [matchnr; lablist];
end
% test to see if lablist has at least enough elements:
if size(lablist,1)~=c
error('New lablist or permutation vector does not match with number of classes.');
end
% Do the matching and reordering, depending if the class labels in X are
% string or numerical
if isa(ll,'char') % X has string labels
if isa(lablist,'char') % we have to match 2 string labels
I = zeros(c,1);
for i=1:c
matchnr = strmatch(lablist(i,:),ll);
if isempty(matchnr)
error('Label %s cannot be found in the dataset.',lablist(i,:));
end
I(i) = matchnr;
end
else % we have to apply a simple permutation on strings in X
if ~isa(lablist,'double')
error('Expecting a permutation label or a new lablist.');
end
I = lablist;
if (min(I)<1) | (max(I)>c)
error('Not a valid permutation vector is supplied.');
end
lablist = ll(I,:);
end
else % dataset X has numeric labels
if (min(lablist)<1) | (max(lablist)>c)
% we are probably NOT dealing with a permutation vector
I = zeros(c,1);
for i=1:c
matchnr = find(lablist(i)==ll);
if isempty(matchnr)
error('Label %d cannot be found in the dataset.',lablist(i));
end
I(i) = matchnr;
end
else % just a permutation on the numeric labels
I = lablist;
lablist = ll(I,:);
end
end
% So finally perform the transformation:
x = setlablist(x, lablist);
[sortedI,I] = sort(I); %kind of inverse the I
% and be careful with unlabeled data
nlab = getnlab(x);
J = find(nlab>0);
nlab(J) = I(nlab(J));
x = setnlab(x, nlab);
return
|
github
|
jacksky64/imageProcessing-master
|
bayesc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/bayesc.m
| 2,709 |
utf_8
|
64ea328a92377d3fd78dcef88ed92b12
|
%BAYESC Bayes classifier
%
% W = BAYESC(WA,WB, ... ,P,LABLIST)
%
% INPUT
% WA, WB, ... Trained mappings for supplying class density estimates
% P Vector with class prior probabilities
% Default: equal priors
% LABLIST List of class names (labels)
%
% OUTPUT
% W Bayes classifier.
%
% DESCRIPTION
% The trained mappings WA,WB, ... should supply proper densities estimates
% D for a dataset X by D = X*WA, etcetera. E.g. they should be trained by
% commands like GAUSSM(A), PARZENM(A), KNNM(A). Consequently, they should
% have a size of K x 1 (assuming that X and A are K-dimensional). Also
% sizes of K x N are supported, assuming a combined density estimate for N
% classes simultaneously. BAYESC weighs the class densitites by the class
% priors in P and names the classes by LABLIST. If LABLIST is not supplied,
% the labels stored in the mappings are used.
%
% REFERENCES
% 1. R.O. Duda, P.E. Hart, and D.G. Stork, Pattern classification, 2nd edition,
% John Wiley and Sons, New York, 2001.
% 2. A. Webb, Statistical Pattern Recognition, John Wiley & Sons, New York, 2002.
%
% SEE ALSO
% DATASETS, MAPPINGS, GAUSSM, PARZENM, KNNM
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function w = bayesc(varargin)
prtrace(mfilename);
n = nargin;
p = [];
lablist = [];
if (nargin > 1)
if nargin > 2 & (~ismapping(varargin{end-1}))
p = varargin{end-1};
lablist = varargin{end};
n = n-2;
elseif (~ismapping(varargin{end}))
p = varargin{end};
n = n-1;
end
end
if (nargin < 1 | isempty(varargin{1}))
% Definition
w = mapping(mfilename,'combiner',{p,lablist});
w = setname(w,'Bayes Classifier');
elseif ismapping(varargin{1})
% Construction of the trained Bayes Classifier
w = [];
k = size(varargin{1},1);
for j=1:n
v = varargin{j};
if ~ismapping(v) | getout_conv(v) ~= 0
error('Density estimating mapping expected and not found')
end
if size(v,1) ~= k
error('Mappings / density estimators should be defined for the same dimensionality')
end
w = [w v];
end
c = size(w,2);
if isempty(p), p = ones(1,c)/c; end
if length(p) ~= c
error('Vector with prior probabilities has wrong length')
end
if isempty(lablist)
lablist = getlabels(w);
end
if size(lablist,1) ~= c
error('Label list has wrong size')
end
w = w*affine(p(:)');
w = setlabels(w,lablist);
w = setname(w,'Bayes Classifier');
else
error('Wrong input')
end
|
github
|
jacksky64/imageProcessing-master
|
traincc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/traincc.m
| 1,575 |
utf_8
|
ce1e8f1e40fd17a4139ac4d705643c2d
|
%TRAINCC Train combining classifier if needed
%
% W = TRAINCC(A,W,CCLASSF)
%
% INPUT
% A Training dataset
% W A set of classifiers to be combined
% CCLASSF Combining classifier
%
% OUTPUT
% B Combined classifier mapping
%
% DESCRIPTION
% The combining classifier CCLASSF is trained by the dataset A*W, if
% training is needed. W is typically a set of stacked (operating in the same
% feature space) or parallel (operating in different feature spaces;
% performed one after another) classifiers to be combined. E.g. if V1, V2
% and V3 are base classifiers, then V = [V1,V2,V3,...] is a stacked
% classifier and V = [V1;V2;V3;...] is a parallel one. If CCLASSF is one of
% the fixed combining rules like MAXC, then training is skipped.
%
% This routine is typically called by combining classifier schemes like
% BAGGINGC and BOOSTINGC.
%
% SEE ALSO
% DATASETS, MAPPINGS, STACKED, PARALLEL, BAGGINGC, BOOSTINGC
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: traincc.m,v 1.4 2010/06/25 07:55:34 duin Exp $
function w = traincc(a,w,cclassf)
prtrace(mfilename);
if (~ismapping(cclassf))
error('Combining classifier is an unknown mapping.')
end
% If CCLASSF is already a combining classifier, just apply it. Otherwise,
% train it using A*W.
if isuntrained(w)
w = a*w; % train base classifiers
end
w = w*cclassf;
if isuntrained(w)
w = a*w; % train combiner when needed
end
w = setcost(w,a);
return
|
github
|
jacksky64/imageProcessing-master
|
plotr.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/plotr.m
| 1,058 |
utf_8
|
e922a00d48d26055bff39c4243bfad90
|
%PLOTR Plot regression
%
% PLOTR(W)
% PLOTR(W,CLR)
%
% Plot the regression function W, optionally using plot string CLR.
% This plot string can be anything that is defined in plot.m.
% For the best results (concerning the definition of the axis for
% instance) it is wise to first scatter the regression data using
% SCATTERR(A).
%
% The resolution of the plot is determined by the global parameter
% GRIDSIZE.
%
% SEE ALSO
% SCATTERR, PLOTC
% Copyright: D.M.J. Tax, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function h = plotr(w,clrs)
if nargin<2
clrs = 'k-';
end
if ~isa(w,'mapping')
error('Mapping expected. Old PLOTR has been renamed in PLOTE.');
end
% define the input on a grid:
V = axis;
g = gridsize;
%because we are plotting 1D, we can affort many more points compared to
%2D:
g = g*g;
x = linspace(V(1),V(2),g)';
% find the regression outputs:
y = x*w;
% and plot:
hold on; h = plot(x,+y,clrs);
% avoid unnecessary output:
if nargout<1, clear h; end
return
|
github
|
jacksky64/imageProcessing-master
|
matchcost.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/matchcost.m
| 1,233 |
utf_8
|
7f0b9c4e4003b50b936ad26092ce9e5c
|
% Matchcost
% Copyright: D.M.J. Tax, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: matchcost.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function [cost,lablist] = matchcost(orglablist,cost,lablist)
prtrace(mfilename,2);
k = size(orglablist,1);
if (size(cost,1) ~= k)
error([newline 'The number of rows in the cost matrix should match the number' ...
newline 'of features'])
end
k = size(lablist,1);
if (size(cost,2) ~= k)
error([newline 'The number of columns in the cost matrix should match the length' ...
newline 'of the lablist'])
end
if size(cost,2) < size(cost,1)
error([newline 'Number of columns in cost matrix should be at least number of rows'])
end
if (nargin > 2) & (~isempty(lablist))
if size(lablist,1) ~= size(cost,2)
error('Wrong number of labels supplied')
end
I = matchlablist(orglablist,lablist); %DXD that was a bug.
if any(I==0)
error('Supplied label list should match feature labels')
end
J = [1:size(lablist,1)];
J(I) = []; % find label in lablist not in dataset
cost = [cost(I,I) cost(:,J)];
lablist = lablist([I;J],:);
end
return
|
github
|
jacksky64/imageProcessing-master
|
txtread.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/txtread.m
| 696 |
utf_8
|
6ebf9789d35e41ef629a89899cc6de7a
|
%TXTREAD Read text file
%
% A = TXTREAD(FILENAME,N,START)
%
% INPUT
% FILENAME Name of delimited ASCII file
% N Number of elements to be read (default all)
% START First element to be read (default 1)
%
% OUTPUT
% A String
%
% DESCRIPTION
% Reads the total file as text string into A
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function a = txtread(file,n,nstart)
if nargin < 3, nstart = 1; end
if nargin < 2 | isempty(n), n = inf; end
fid = fopen(file);
if (fid < 0)
error('Error in opening file.')
end
a = fscanf(fid,'%c',n);
fclose(fid);
return
|
github
|
jacksky64/imageProcessing-master
|
featsel.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featsel.m
| 1,825 |
utf_8
|
a8189a42fced472d3e1bb2f9f56f3b4e
|
%FEATSEL Selection of known features
%
% W = FEATSEL(K,J)
%
% INPUT
% K Input dimensionality
% J Index vector of features to be selected
%
% OUTPUT
% W Mapping performing the feature selection
%
% DESCRIPTION
% This is a simple support routine that writes feature selection
% in terms of a mapping. If A is a K-dimensional dataset and J are
% the feature indices to be selected, then B = A*W does the same as
% B = A(:,J).
%
% The use of this routine is a mapping V computed for a lower dimensional
% subspace defined by J can now be defined by W = FEATSEL(K,J)*V as a
% mapping in the original K-dimensional space.
%
% The selected features can be retrieved by W.DATA or by +W.
% See below for various methods to perform feature selection.
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELF, FEATSELLR,
% FEATSELO, FEATSELB, FEATSELI, FEATSELP, FEATSELM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = featsel(k,j)
if isa(k,'dataset')
%if isa(k,'dataset') & ismapping(j)
nodatafile(k);
w = k(:,j);
elseif isa(k,'mapping')
w = k(:,j);
else
if (any(j) > k | any(j) < 1)
error('Features to be selected are not in proper range')
end
% w = mapping(mfilename,'trained',j(:)',[],k,length(j));
% There seems to be no need to make this mapping 'trained'.
% A fixed mapping could be used more easily.
% For historical consistency it is left like this (RD)
% On second sight a fixed mapping is needed for handling datafiles
% w = mapping(mfilename,'trained',j(:)',[],k,length(j));
w = mapping(mfilename,'fixed',j(:)',[],k,length(j));
% w = mapping(mfilename,'combiner',j(:)',[],k,length(j));
w = setname(w,'Feature Selection');
end
|
github
|
jacksky64/imageProcessing-master
|
gaussm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gaussm.m
| 2,736 |
utf_8
|
a025a61e12fe6c77f953ebdd347f1cd5
|
%GAUSSM Mixture of Gaussians density estimate
%
% W = GAUSSM(A,K,R,S,M)
% W = A*GAUSSM([],K,R,S,M);
%
% INPUT
% A Dataset
% K Number of Gaussians to use (default: 1)
% R,S,M Regularization parameters, 0 <= R,S <= 1, see QDC
%
% OUTPUT
% W Mixture of Gaussians density estimate
%
% DESCRIPTION
% Estimation of a PDF for the dataset A by a Mixture of Gaussians
% procedure. Use is made of EMCLUST(A,QDC,K). Unlabeled objects are
% neglected, unless A is entirely unlabeled or double. Then all objects
% are used. If A is a multi-class crisp labeled dataset the densities are
% estimated class by class and then weighted and combined according their
% prior probabilities. In all cases, just single density estimator W is
% computed.
%
% Note that it is necessary to set the label type of A to soft labels
% (A = LABTYPE(A,'soft') in order to use the traditional EM algorithm
% based on posterior probabilities instead of using crisp labels.
%
% The mapping W may be applied to a new dataset B using DENSITY = B*W.
%
% SEE ALSO
% DATASETS, MAPPINGS, QDC, MOGC, EMCLUST, PLOTM, TESTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: gaussm.m,v 1.8 2009/02/02 21:57:39 duin Exp $
function w = gaussm(a,n,r,s,dim)
prtrace(mfilename)
if nargin < 5, dim = []; end
if nargin < 4, s = 0; end
if nargin < 3, r = 0; end
if (nargin < 2)
prwarning (2,'number of Gaussians not specified, assuming 1.');
n = 1;
end
% No arguments specified: return an empty mapping.
mapname = 'Mixture of Gaussians';
if (nargin < 1) | (isempty(a))
w = mapping(mfilename,{n,r,s,dim});
w = setname(w,mapname);
return
end
if isa(a,'dataset')
labname = getname(a);
else
labname = '';
end
if ((~isdataset(a) & ~isdatafile(a)) | (getsize(a,3) ~= 1 & islabtype(a,'crisp')))
w = mclassm(a,mapping(mfilename,n),'weight');
w = setlabels(w,labname);
w = setname(w,mapname);
return
end
[m,k] = getsize(a);
if n == 1
[U,G] = meancov(a);
res.mean = +U;
res.cov = G;
res.prior= 1;
w = normal_map(res,labname,k,1);
else
[e,v] = emclust(a,qdc([],r,s,dim),n);
ncomp0 = size(v.data.mean,1);
iter = 0;
while (ncomp0 ~= n & iter < 5) % repeat until exactly n components are found
[e,v1] = emclust(a,qdc([],r,s,m),n);
ncomp1 = size(v1.data.mean,1);
if ncomp1 > ncomp0
v = v1;
ncomp0 = ncomp1;
end
iter = iter + 1;
end
res = v.data;
res.nlab = ones(n,1); % defines that all Gaussian components have to be
% combined into a single class.
w = mapping('normal_map','trained',res,labname,k,1);
end
w = setname(w,mapname);
return
|
github
|
jacksky64/imageProcessing-master
|
prwaitbarinit.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prwaitbarinit.m
| 1,294 |
utf_8
|
15265af6113db7d793f5a56b190e02a0
|
%PRWAITBARINIT Low level routine to simplify PRWAITBAR init
%
% [N,S,COUNT] = PRWAITBARINIT(STRING,N)
%
% INPUT
% STRING - String with text to be written in every waitbar,
% e.g. 'Processing %i items: '. This will be parsed
% by S = SPRINTF(STRING,N);
% N - Total number of items to be processed
%
% OUTPUT
% N - Resulting N (Input N may be expression)
% S - Resulting STRING (see above)
% COUNT - Counter initialisation, COUNT = 0
%
% This routine has to be used in combination with PRWAITBARNEXT, e.g.:
%
% [n,s,count] = prwaitbarinit('Processing %i items:',size(a,1)*size(a,2));
% for i=1:size(a,1)
% for j=1:size(a,2)
% < process a(i,j) >
% count = prwaitbarnext(n,s,count);
% end
% end
%
% PRWAITBARINIT and PRWAITBARNEXT are written on top of PRWAITBAR. If it
% is possible that loops like the above are not fully processed, it is
% necessary to include as a final call PRWAITBAR(0)
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [n,s,count] = prwaitbarinit(ss,n)
s = sprintf(ss,n);
if n > 1
prwaitbar(n,s);
prwaitbar(n,1,[s int2str(1)]);
end
count = 0;
return
|
github
|
jacksky64/imageProcessing-master
|
prpinv.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prpinv.m
| 315 |
utf_8
|
e3f9437aff6d34596fe94d4b990b2562
|
%PRPINV Call to PINV() including PRWAITBAR
%
% B = PRPINV(A)
%
% This calls B = PINV(A) and includes a message to PRWAITBAR
% in case of a large A
function B = prpinv(A)
[m,n] = size(A);
if min([m,n]) > 250
prwaitbaronce('Inverting %i x %i matrix ...',[m,n]);
B = pinv(A);
prwaitbar(0);
else
B = pinv(A);
end
|
github
|
jacksky64/imageProcessing-master
|
maxc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/maxc.m
| 1,900 |
utf_8
|
27971a25a4f95b74f121b8713b358fb2
|
%MAXC Maximum combining classifier
%
% W = MAXC(V)
% W = V*MAXC
%
% INPUT
% V Stacked set of classifiers
%
% OUTPUT
% W Combined classifier using max-rule
%
% DESCRIPTION
% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the same
% classes, then W is the maximum combiner: it selects the class that gives
% the maximal output of the input classifiers. This might also be used as
% A*[V1,V2,V3]*MAXC in which A is a dataset to be classified. Consequently,
% if S is a similarity matrix with class feature labels (e.g. S =
% A*PROXM(A,'r')), then S*MAXC*LABELD is the nearest neighbor classifier.
%
% If it is desired to operate on posterior probabilities then the input
% classifiers should be extended to output these, using V = V*CLASSC.
%
% The base classifiers may be combined in a stacked way (operating in the
% same feature space by V = [V1,V2,V3, ... ] or in a parallel way (operating
% in different feature spaces) by V = [V1;V2;V3; ... ].
%
% EXAMPLES
% see PREX_COMBINING
%
% SEE ALSO
% MAPPINGS, DATASETS, VOTEC, MINC, MEANC, MEDIANC, PRODC, AVERAGEC,
% STACKED, PARALLEL
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: maxc.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function w = maxc(p1)
% This is the general procedure for all possible calls of fixed combiners:
% they are handled by FIXEDCC.
type = 'max'; % Define the operation processed by FIXEDCC.
name = 'Maximum combiner'; % Define the name of the combiner.
% Possible calls: MAXC, MAXC(W) or MAXC(A,W).
if (nargin == 0) % No arguments given: return untrained mapping.
w = mapping('fixedcc','combiner',{[],type,name});
else
w = fixedcc(p1,[],type,name);
end
if (isa(w,'mapping'))
w = setname(w,name);
end
return
|
github
|
jacksky64/imageProcessing-master
|
kernelc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/kernelc.m
| 2,552 |
utf_8
|
88c72b7bff0916c5ead2b42ec0be0f1b
|
%KERNELC Arbitrary kernel/dissimilarity based classifier
%
% W = KERNELC(A,KERNEL,CLASSF)
% W = A*KERNELC([],KERNEL,CLASSF)
%
% INPUT
% A Dateset used for training
% KERNEL - untrained mapping to compute kernel by A*(A*KERNEL) for
% training CLASSF or B*(A*KERNEL) for testing with dataset B, or
% - trained mapping to compute a kernel A*KERNEL for training
% CLASSF or B*KERNEL for testing with a dataset B
% KERNEL should be a functions like PROXM, KERNELM or USERKERNEL.
% Default: reduced dissimilarity representation:
% KERNELM([],[],'random',0.1,100);
% CLASSF Classifier used in kernel space, default LOGLC.
%
% OUTPUT
% W Resulting, trained classifier
%
% DESCRIPTION
% This routine defines a classifier W in the input feature space based
% on a kernel or dissimilarity representation defined by KERNEL and a
% classifier CLASSF to be trained in the kernel space.
%
% In case KERNEL is defined by V = KERNELM( ... ) this routine
% is identical to W = A*(V*CLASSF), Note that if KERNEL is a mapping, it
% may be trained as well as untrained. In the latter case A is used to
% build the kernel space as well as to optimize the classifier (like in SVC).
%
% EXAMPLE
% A = GENDATB([100 100]); % Training set of 200 objects
% R = GENDATB([10 10]); % Representation set of 20 objects
% V = KERNELM(R,'p',3); % Compute kernel
% W = KERNELC(A,V,FISHERC) % compute classifier
% SCATTERD(A); % Scatterplot of trainingset
% HOLD ON; SCATTERD(R,'ko'); % Add representation set to scatterplot
% PLOTC(W); % Plot classifier
%
% SEE ALSO
% DATASETS, MAPPINGS, KERNELM, PROXM, USERKERNEL
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = kernelc(a,kernel,classf)
prtrace(mfilename);
if nargin < 3 | isempty(classf), classf = fisherc; end
if nargin < 2 | isempty(kernel)
kernel = kernelm([],[],'random',0.7,100);
end
if nargin < 1 | isempty(a)
w = mapping(mfilename,'untrained',{kernel,classf});
else % training
islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a,'objects');
isuntrained(classf);
ismapping(kernel);
if isuntrained(kernel)
kernel = a*kernel;
end
K = a*kernel;
w = kernel*(K*classf);
end
w = setname(w,'Kernel Classifier');
return
|
github
|
jacksky64/imageProcessing-master
|
ismapping.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/ismapping.m
| 493 |
utf_8
|
9616ca5d38d4cc8ea4813f5dcdc0ecac
|
%ISMAPPING Test whether the argument is a mapping
%
% N = ISMAPPING(W);
%
% INPUT
% W Input argument
%
% OUTPUT
% N 1/0 if W is/isn't a mapping object
%
% DESCRIPTION
% True (1) if W is a mapping object and false (0), otherwise.
%
% SEE ALSO
% ISDATASET, ISFEATIM, ISDATAIM
% $Id: ismapping.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function n = ismapping(w)
prtrace(mfilename);
n = isa(w,'mapping');
if (nargout == 0) & (n == 0)
error([newline 'Mapping expected.'])
end
return;
|
github
|
jacksky64/imageProcessing-master
|
pls_train.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/pls_train.m
| 9,379 |
utf_8
|
2dc7ca5aaf1d9bcc741e7182373df635
|
%pls_train Partial Least Squares (training)
%
% [B,XRes,YRes,Options] = pls_train(X,Y)
% [B,XRes,YRes,Options] = pls_train(X,Y,Options)
%
% INPUT
% X [N -by- d_X] the training (input) data matrix, N samples, d_X variables
% Y [N -by- d_Y] the training (output) data matrix, N samples, d_Y variables
%
% Options.
% maxLV maximal number of latent variables (will be corrected
% if > rank(X));
% maxLV=inf means maxLV=min(N,d_X) -- theoretical maximum
% number of LV;
% by default =inf
% method 'NIPALS' or 'SIMPLS'; by default ='SIMPLS'
%
% X_centering do nothing (=[] or 0), do mean centering (=nan), center
% around some vaue v (=v);
% by default =[]
% Y_centering do nothing (=[] or 0), do mean centering (=nan), center
% around some vaue v (=v);
% by default =[]
% X_scaling do nothing (=[] or 1), divide each col by std (=nan),
% divide by some v (=v);
% by default =[]
% Y_scaling do nothing (=[] or 1), divide each col by std (=nan),
% divide by some v (=v);
% by default =[]
%
% OUTPUT
% B [d_X -by- d_Y -by- nLV] collection of regression matrices:
% Y_new = X_new*B(:,:,n) represents regression on the first n
% latent variables (X_new here after preprocessing, Y_new before
% un-preprocessing)
% XRes.
% ssq [1 -by- nLV] the part of explaind sum of squares of
% (preprocessed) X matrix
% T [N -by- nLV] scores (transformed (preprocessed) X)
% R [d_X -by- nLV] weights (transformation matrix)
% P [d_X -by- nLV] loadings (back-transformation matrix)
% P(:,k) are the regression coef of
% (preprocessed) X on T(:,k)
% W [d_X -by- nLV] local weights (local transformation matrix);
% ONLY FOR NIPALS
% V [d_X -by- nLV] first k columns of this matrix are the
% orthornormal basis of the space spanned by k
% first columns of P; ONLY FOR SIMPLS
% YRes.
% ssq [1 -by- nLV] the part of explained sum of squares of
% (preprocessed) Y matrix
% U [N -by- nLV] scores (transformed (preprocessed) Y)
% Q [d_Y -by- nLV] weights (transformation matrix)
% C [d_Y -by- nLV] C(:,k) are the regression coeff of
% (preprocessed) Y on T(:,k)
% bin [1 -by- nLV] bin(k) is the regression coeff of U(:,k) on T(:,k)
%
% Options. contains the same fields as in input, but the values can be changed
% (e.g. after mean centering X_centering = mean(X,1))
%
%
% DESCRIPTION
% Trains PLS (Partial Least Squares) regression model
%
% Relations between matrices (X end Y are assumed to be preprocessed):
% NIPALS:
% T = X*R (columns of T are orthogonal)
% R = W*prinv(P'*W)
% P = X'*T*prinv(T'*T)
% U = Y*Q - T*(C'*Q-tril(C'*Q))
% C = Y'*T*prinv(T'*T) = Q*diag(bin)
% bin = sqrt(diag(T'*Y*Y'*T))'*prinv(T'*T))
% B = R*C' = W*prinv(P'*W)*C'
%
% SIMPLS:
% T = X*R (columns of T are orthonormal)
% P = X'*T
% U = Y*Q
% C = Y'*T = Q*diag(bin)
% bin = sqrt(diag(T'*Y*Y'*T))'
% B = R*C'
%
% BOTH:
% T_new = X_new*R
% Y_new = X_new*B
%
% SEE ALSO
% pls_apply, pls_transform
% Copyright: S.Verzakov, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: pls_train.m,v 1.2 2010/02/08 15:29:48 duin Exp $
function [B, XRes, YRes, Options] = pls_train(X,Y,Options)
[N_X, d_X] = size(X);
[N_Y, d_Y] = size(Y);
if N_X ~= N_Y
error('size(X,1) must be equal to size(Y,1)');
else
N = N_X;
end
if nargin < 3
Options = [];
end
DefaultOptions.X_centering = [];
DefaultOptions.Y_centering = [];
DefaultOptions.X_scaling = [];
DefaultOptions.Y_scaling = [];
DefaultOptions.maxLV = inf;
DefaultOptions.method = 'SIMPLS';
Options = pls_updstruct(DefaultOptions, Options);
if isinf(Options.maxLV)
Options.maxLV = min(N,d_X);
elseif Options.maxLV > min(N,d_X)
error('PLS: The number of LV(s) cannot be greater then min(N,d_X)');
end
[X, Options.X_centering, Options.X_scaling] = pls_prepro(X, Options.X_centering, Options.X_scaling);
[Y, Options.Y_centering, Options.Y_scaling] = pls_prepro(Y, Options.Y_centering, Options.Y_scaling);
ssq_X = sum(X(:).^2);
ssq_Y = sum(Y(:).^2);
B = zeros(d_X,d_Y,Options.maxLV);
XRes.ssq = zeros(1,Options.maxLV);
XRes.T = zeros(N,Options.maxLV);
XRes.R = zeros(d_X,Options.maxLV);
XRes.P = zeros(d_X,Options.maxLV);
XRes.W = [];
XRes.V = [];
YRes.ssq = zeros(1,Options.maxLV);
YRes.U = zeros(N,Options.maxLV);
YRes.Q = zeros(d_Y,Options.maxLV);
YRes.C = zeros(d_Y,Options.maxLV);
YRes.bin = zeros(1,Options.maxLV);
ev = zeros(1,Options.maxLV);
nLV = Options.maxLV;
opts.disp = 0;
opts.issym = 1;
opts.isreal = 1;
switch upper(Options.method)
case 'NIPALS'
XRes.W = zeros(d_X,Options.maxLV);
for LV = 1:Options.maxLV
S = X'*Y;
if d_X <= d_Y
if d_X > 1
[w, ev(LV)] = eigs(S*S',1,'LA',opts);
else
w = 1;
ev(LV) = S*S';
end
t = X*w;
t2 = (t'*t);
proj = t/t2;
p = X'*proj;
c = Y'*proj;
bin = norm(c); %bin = sqrt(ev)/t2:
q = c/bin;
u = Y*q;
else
if d_Y > 1
[q, ev(LV)] = eigs(S'*S,1,'LA',opts);
else
q = 1;
ev(LV) = S'*S;
end
u = Y*q;
w = X'*u;
w = w/norm(w);
t = X*w;
t2 = (t'*t);
proj = t/t2;
p = X'*proj;
bin = u'*proj; %bin = sqrt(ev)/t2:
c = q*bin;
end
if LV == 1
if ev(LV) == 0
error('PLS: Rank of the covariation matrix X''*Y is zero.');
end
elseif ev(LV) <= 1e-16*ev(1)
nLV = LV-1;
WarnMsg = sprintf(['\nPLS: Rank of the covariation matrix X''*Y is exausted ' ...
'after removing %d Latent Variable(s).\n'...
'Results only for the %d LV(s) will be returned'],nLV,nLV);
if exist('prwarning')
prwarning(1, WarnMsg);
else
warning(WarnMsg);
end
break;
end
%R = W*prinv(P'*W)
%the next portion of the code makes use of the fact taht P'*W is the upper triangle matrix:
%
%if LV == 1
% InvPTW(1,1) = 1/(p'*w);
% r = w*InvPTW(1,1);
%else
% InvPTW(1:LV,LV) = [(-InvPTW(1:LV-1,1:LV-1)*(XRes.P(:,1:LV-1)'*w)); 1]/(p'*w);
% r = [XRes.W(:,1:LV-1), w] * InvPTW(1:LV,LV);
%end
%
%some optimization of the above code (notice that ones(m,0)*ones(0,n) == zeros(m,n)):
%
r = (w - (XRes.R(:,1:LV-1)*(XRes.P(:,1:LV-1)'*w)))/(p'*w);
B(:,:,LV) = r*c';
XRes.ssq(:,LV) = t2*(p'*p)/ssq_X;
XRes.T(:,LV) = t;
XRes.R(:,LV) = r;
XRes.P(:,LV) = p;
XRes.W(:,LV) = w;
YRes.ssq(:,LV) = t2*(bin.^2)/ssq_Y;
YRes.U(:,LV) = u;
YRes.Q(:,LV) = q;
YRes.C(:,LV) = c;
YRes.bin(:,LV) = bin;
X = X - t*p';
Y = Y - t*c';
end
if nLV < Options.maxLV
XRes.W = XRes.W(:,1:nLV);
end
case 'SIMPLS'
XRes.V = zeros(d_X,Options.maxLV);
S = X'*Y;
for LV = 1:Options.maxLV
if d_X <= d_Y
if d_X > 1
[r, ev(LV)] = eigs(S*S',1,'LA',opts);
else
r = 1;
ev(LV) = S*S';
end
t = X*r;
norm_t = norm(t);
r = r/norm_t;
t = t/norm_t;
p = X'*t;
c = Y'*t; %c = S'*r;
bin = norm(c); %bin = sqrt(ev)/norm_t:
q = c/bin;
u = Y*q;
else
if d_Y > 1
[q, ev(LV)] = eigs(S'*S,1,'LA',opts);
else
q = 1;
ev(LV) = S'*S;
end
r = S*q;
t = X*r;
norm_t = norm(t);
r = r/norm_t;
t = t/norm_t;
p = X'*t;
u = Y*q;
bin = u'*t; %bin = ev/norm_t:
c = q*bin;
end
if LV == 1
if ev(LV) == 0
error('PLS: Rank of the covariation matrix X''*Y is zero.');
else
v = p;
end
elseif ev(LV) <= 1e-16*ev(1)
nLV = LV-1;
WarnMsg = sprintf(['\nPLS: Rank of the covariation matrix X''*Y is exausted ' ...
'after removing %d Latent Variable(s).\n'...
'Results only for the %d LV(s) will be returned'],nLV,nLV);
if exist('prwarning')
prwarning(1, WarnMsg);
else
warning(WarnMsg);
end
break;
else
v = p - XRes.V(:,1:LV-1)*(XRes.V(:,1:LV-1)'*p);
end
v = v/norm(v);
B(:,:,LV) = r*c';
XRes.ssq(:,LV) = (p'*p)/ssq_X;
XRes.T(:,LV) = t;
XRes.R(:,LV) = r;
XRes.P(:,LV) = p;
XRes.V(:,LV) = v;
YRes.ssq(:,LV) = (bin.^2)/ssq_Y;
YRes.U(:,LV) = u;
YRes.Q(:,LV) = q;
YRes.C(:,LV) = c;
YRes.bin(:,LV) = bin;
S = S - v*(v'*S);
end
if nLV < Options.maxLV
XRes.V = XRes.V(:,1:nLV);
end
end
if nLV < Options.maxLV
B = B(:,:,1:nLV);
XRes.ssq = XRes.ssq(:,1:nLV);
XRes.T = XRes.T(:,1:nLV);
XRes.R = XRes.R(:,1:nLV);
XRes.P = XRes.P(:,1:nLV);
YRes.ssq = YRes.ssq(:,1:nLV);
YRes.U = YRes.U(:,1:nLV);
YRes.Q = YRes.Q(:,1:nLV);
YRes.C = YRes.C(:,1:nLV);
YRes.bin = YRes.bin(:,1:nLV);
Options.maxLV = nLV;
end
B = cumsum(B,3);
return;
function A = MakeSym(A)
A = 0.5*(A+A');
%A = max(A,A');
return
|
github
|
jacksky64/imageProcessing-master
|
featselo.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featselo.m
| 4,290 |
utf_8
|
4603fe51a9b83f13a1277d846ea96f4d
|
%FEATSELO Branch and bound feature selection
%
% W = featselo(A,CRIT,K,T,FID)
%
% INPUT
% A input dataset
% CRIT string name of the criterion or untrained mapping
% (optional, def= 'NN' 1-Nearest Neighbor error)
% K numner of features to select (optional, def: K=2)
% T validation set (optional)
% N Number of cross-validations (optional)
% FID File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% W output feature selection mapping
%
% DESCRIPTION
% Backward selection of K features by baktracking using the branch
% and bound procedure on the data set A. CRIT sets the criterion
% used by the feature evaluation routine FEATEVAL. If the data set T
% is given, it is used as test set for FEATEVAL. Alternatively a number
% of cross-validations N may be supplied. The resulting W can be used for
% the selecting features of a dataset B by B*W.
% The selected features are stored in W.DATA and can be found by +W.
%
% This procedure finds the optimum feature set if a monotoneous
% criterion is used. The use of a testset does not guarantee that.
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELF, FEATSELB, FEATSELI,
% FEATSEL, FEATSELP, FEATSELM, PRPROGRESS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: featselo.m,v 1.7 2009/07/01 09:33:23 duin Exp $
function [W,R] = featselo(A,crit,kmin,T,fid)
prtrace(mfilename);
if nargin < 2 | isempty(crit), crit = 'NN'; end
if nargin < 3 | isempty(kmin), kmin = 2; end
if nargin < 4, T = []; end
if (nargin < 5)
fid = [];
end
if nargin == 0 | isempty(A)
% Create an empty mapping:
W = mapping('featselo',{crit,kmin,T});
W = setname(W,'B&B FeatSel');
return
end
isvaldfile(A,1,2); % at least 1 object per class, 2 classes
A = testdatasize(A);
if ~is_scalar(T), iscomdset(A,T); end
[m,k,c] = getsize(A);
featlist = getfeatlab(A);
if ((kmin < 1) | (kmin >= k))
error('The desired feature size should be > 0 and < dataset feature size')
end
% space for criteria values
feat = zeros(1,k);
% Get performance of the individual features:
if isempty(T)
for j=1:k
feat(j) = feateval(A(:,j),crit);
end
elseif is_scalar(T)
for j=1:k
feat(j) = feateval(A(:,j),crit,T);
end
else
for j=1:k
feat(j) = feateval(A(:,j),crit,T(:,j));
end
end
% Get the kmin worst(?) individual features according to their
% individual performance:
[F,S] = sort(feat);
%sometimes the above line is bad compared to the following two
%w = featselb(A,crit,[]);
%S = fliplr(+w);
Iopt = [k-kmin+1:k];
I = [1:k];
J = [zeros(1,kmin),1:(k-kmin-1),k-kmin+1,k+1];
level = k;
% Get the performance of Iopt
if isdataset(T)
bound = feateval(A(:,S(Iopt)),crit,T(:,S(Iopt)));
elseif is_scalar(T)
bound = feateval(A(:,S(Iopt)),crit,T);
else
bound = feateval(A(:,S(Iopt)),crit);
end
C = inf;
prprogress(fid,'\nfeatselo : Branch & Bound Feature Selection\n')
prwaitbar(100,'Branch & Bound Feature Selection')
iter = 0;
while length(I) > 0 & J(k+1) == k+1;
iter = iter+1;
prwaitbar(100,100-100*exp(-iter/1000));
if J(level) == J(level+1) | level <= kmin | C <= bound
J(level) = level - kmin;
level = level + 1;
I = sort([I,J(level)]);
J(level) = J(level) + 1;
C = inf;
else
I(J(level)) = [];
level = level - 1;
if J(level+1) < 3 & level == kmin+1 & 0 % never happens ??
;
else
if isdataset(T)
C = feateval(A(:,S(I)),crit,T(:,S(I)));
elseif is_scalar(T)
C = feateval(A(:,S(I)),crit,T);
else
C = feateval(A(:,S(I)),crit);
end
%prprogress(fid,' level %i, crit: %10.5e',level,C);
if level == kmin & C > bound
bound = C;
Iopt = I;
prprogress(fid,' level %i, crit: %10.5e',level,C);
prprogress(fid,' FeatSet: ');
prprogress(fid,' %i',S(I));
prprogress(fid,'\n')
end
%prprogress(fid,'\n')
end
end
end
prprogress(fid,'featselo finished\n');
prwaitbar(0);
% Store the optimal features in the mapping:
W = featsel(k,S(Iopt));
if ~isempty(featlist)
W = setlabels(W,featlist(S(Iopt),:));
end
W = setname(W,'B&B FeatSel');
R = []; %DXD I'm still not sure what to return
return
|
github
|
jacksky64/imageProcessing-master
|
prwaitbar.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prwaitbar.m
| 11,571 |
utf_8
|
37266483f77f00ad145637eb2148b919
|
%PRWAITBAR Report PRTools progress by single waitbar
%
% H = PRWAITBAR(N,M,TEXT)
% H = PRWAITBAR(N,TEXT,FLAG)
% S = PRWAITBAR
%
% INPUT
% N Integer, total number of steps in loop
% M Integer, progress in number of steps in loop
% TEXT Text to be displayed in waitbar
% FLAG Flag (0/1)
%
% OUTPUT
% H Waitbar handle
% S Status PRWAITBAR ('on' or 'off')
%
% DESCRIPTION
% This routine may be used to report progress in PRTools experiments.
% It detects and integrates levels of loops. The following calls are
% supported:
%
% PRWAITBAR(N,TEXT) initialize loop
% PRWAITBAR(N,TEXT,FLAG) initialize loop if FLAG == 1
% PRWAITBAR(N,M) update progress
% PRWAITBAR(N,M,TEXT) update info
% PRWAITBAR(0) closes loop level
% PRWAITBAR OFF removes waitbar
% PRWAITBAR ON switches waitbar on again
% PRWAITBAR reset prwaitbar
%
% A typical sequence of calls is:
% .....
% prwaitbar(nfolds,'cross validation')
% for j = 1:nfolds
% prwaitbar(nfolds,j,['cross validation, fold ' int2str(j)])
% ....
% end
% prwaitbar(0)
% .....
% Calls to PRTWAITBAR may be nested and all progress is merged into a single
% waitbar. In this PRWAITBAR differs from Matlab's WAITBAR.
% A typical example can be visualised by:
%
% crossval({gendatb,gendath},{svc,loglc,fisherc},5,2)
%
% Some other, more high-level routines calling PRWAITBAR are
% PRWAITBARINIT, PRWAITBARNEXT, PRWAITBARONCE, PREIG, PRINV, PRPINV, PRRANK,
% PRSVD, PRCOV
%
% SEE ALSO
% PRPROGRESS, PRWAITBARINIT, PRWAITBARNEXT, PRWAITBARONCE
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function varargout = prwaitbar(n,m,text)
persistent N % array, N(DEPTH) is the loop size at level DEPTH
persistent M % array, M(DEPTH) is the present counter values at level DEPTH
persistent DEPTH % nesting DEPTH
persistent WHANDLE % handle of the waitbar
persistent MESS % cell array with message to be displayed at level DEPTH
persistent STAT % flag, if STAT = 0, PRWAITBAR is switched off
persistent WPOS % position of the waitbar on the screen
persistent FNAME % cell array with names of the calling routine at level DEPTH
persistent DOIT % flag that may switch off tracking progress at deeper levels
persistent NSKIP % level at which tracking progress has been switched off
persistent OLDPROG1 % previous progress
persistent OLDPROG2 % previous progress
%disp(['prwaitbar ' callername])
%disp(nargin)
%if nargin > 0, disp(n), end
%if nargin > 1, disp(m), end
%if nargin > 2, disp(text),end
%disp('-------------')
if isempty(DEPTH) % initialisation of persistent variables
DEPTH = 0;
MESS = cell(1,10);
FNAME = cell(1,10);
STAT = 1;
DOIT = 1;
end
decrease_depth = 0;
if nargin == 0 % ---- call: prwaitbar ----
if nargout == 0
%prwaitbar off
DEPTH = 0;
STAT = 1;
DOIT = 1;
MESS = cell(1,10);
OLDPROG1 = 0;
OLDPROG2 = 0;
err.message = '';
lasterror(err);
% if ishandle(WHANDLE)
% delete(WHANDLE);
% end
else % ---- call: out = prwaitbar ----
if nargout == 1
if STAT == 0, varargout = {'off'};
else varargout = {'on'};
end
else
varargout = {WHANDLE,N,M,DEPTH,MESS,STAT,WPOS,FNAME,DOIT,NSKIP};
end
return
end
elseif nargin == 1
if isstr(n) & strcmp(n,'off') % ---- call: prwaitbar off ----
if ~isempty(WHANDLE) & ishandle(WHANDLE)
WPOS = get(WHANDLE,'position'); % save position as user likes it
close(WHANDLE);
end
N = []; M = []; DEPTH = 0; % set variables at initial values
WHANDLE = [];
MESS = cell(1,10);
STAT = 0;
return
elseif isstr(n) & strcmp(n,'on') % ---- call: prwaitbar on ----
STAT = 1; % restart waitbar
DEPTH = [];
return
elseif n == 0 & STAT % ---- call: prwaitbar(0) ----
if ~DOIT
if (NSKIP == DEPTH) % we are back at the right level, so
DOIT = 1; % restart tracking progress
end
DEPTH = max(DEPTH - 1,1); % counting problem !!! caused by catch-try loops
return % let us continue with DEPTH = 1
end
if DEPTH < 1 % wrong call, return
return
end
M(DEPTH) = N(DEPTH); % loop almost ready
decrease_depth = 1; % decrease depth after plotting progress
else
return
end
elseif ~STAT % next commands can be skipped if switched off
return
elseif nargin == 2
if isstr(m) % ---- call: prwaitbar(n,text) ----
% note: this is a typical call to
% start a waitbar cycle
DEPTH = DEPTH + 1; % we nest one level deeper
if ~DOIT % skip if we dont track progress
return
end
err = lasterror;
% we have to find out whether we continue a proper set of prwaitbar calls, or whether
% we have to recover from some error or possible interrupt and have to re-initialise
% the admin
if (~strcmp(err.message,'##') & ~strcmp(err.message,'') & ...
~isempty(strfind(err.identifier,'prtools:'))) | (~ishandle(WHANDLE))
% yes, restart after interrupt
prwaitbar;
DEPTH = 1;
end
% find the name of the calling routine
[ss,ii] = dbstack;
if length(ss) == 1
name = ''; % call from command line!!?? debugging?
else
[path,name] = fileparts(ss(2).name);
if strcmp(name,mfilename) | strncmp(name,'prwait',6) % search deeper in case of internal call
[path,name] = fileparts(ss(3).name);
end
end
FNAME{DEPTH} = name; % store it, and display it in waitbar
set(WHANDLE,'name',[' PRWAITBAR: ' name]);
N(DEPTH) = n; % complete the admin
M(DEPTH) = 0;
MESS{DEPTH} = m; % note: m contains text
elseif DOIT % ---- call: prwaitbar(n,m) ----
DEPTH = max(DEPTH,1); % store admin
N(DEPTH) = n;
M(DEPTH) = m-1; % store m-1, assuming call is in the start of loop
else % skip and return if progress should not be reported
return
end
elseif nargin == 3
if isstr(m) % ---- call: prwaitbat(n,text,flag) ----
if ~DOIT % there is a flag, but we already skip progress
DEPTH = DEPTH + 1; % just keep track of loop nesting.
else % we are in reporting mode
DOIT = (text > 0); % check flag
if ~DOIT % stop progress reporting!!!
DEPTH = DEPTH + 1; % keep track of loop nesting
NSKIP = DEPTH; % store level
else % flag does not apply,
prwaitbar(n,m); % just print waitbar
end
end
return
else % ---- call: prwaitbar(n,m,text) ----
if ~DOIT % skip progress report if needed
return
end
if isempty(WHANDLE) % switch waitbar on if needed
prwaitbar; % this only happens if the loop is not properly opened
end
N(DEPTH) = n; % update admin
M(DEPTH) = m-1;
MESS{DEPTH} = text;
end
end
if ~STAT | ~DOIT % dont display, (just to be sure)
return
end
% waitbar creation and display
if isempty(WHANDLE) % if no waitbar, make one
s = sprintf(' \n \n \n' ); % room for 4 levels of text
if ~isempty(WPOS)
h = waitbar(0,'','position',WPOS);
h = waitbar(0,h,s);
else
h = waitbar(0,s); % create waitbar
WPOS = get(h,'position');
end
OLDPROG1 = 0;
OLDPROG2 = 0;
if DEPTH == 0, fnam = [];
else, fnam = FNAME{DEPTH}; end % retrieve name of calling routine
set(h,'name',[' PRWAITBAR: ' fnam])
%set(h,'HandleVisibility','on');
WHANDLE = h;
err.message = '##'; % store for proper continuation in next call
lasterror(err);
%if ~isempty(WPOS) % if we have a position
% set(h,'position',WPOS); % apply it
%else % otherwise
% WPOS = get(h,'position'); % get it
%end
end
progress = 0; % progress
if DEPTH == 0 % still on level zero
s = sprintf(' \n \n \n' ); % no message
else
for j=DEPTH:-1:1 % run over all levels for progress
progress = (progress + M(j))/(N(j)); % compute total progress
end
s = wtext(MESS,N,DEPTH); % construct message
end
significant1 = (progress - OLDPROG1 >= 0.005 | OLDPROG1 == 0);
significant2 = (progress - OLDPROG2 >= 0.0005);
if ishandle(WHANDLE)
if significant1 % show significant updates only
waitbar(progress,WHANDLE,s,'position',WPOS); % update waitbar
OLDPROG1 = progress;
OLDPROG2 = progress;
elseif significant2 % update text more often
set(get(get(WHANDLE,'children'),'title'),'string',s); drawnow
OLDPROG2 = progress;
end
else % handle was not proper (anymore)
WHANDLE = waitbar(progress,s,'position',WPOS); % reconstruct waitbar
OLDPROG1 = progress;
OLDPROG2 = progress;
end
if decrease_depth % update admin
DEPTH = DEPTH - 1;
if DEPTH == 0 % take care that new waitbar starts fresh
err.message = '';
lasterror(err);
WPOS = get(WHANDLE,'position'); % but in old position
%delete(WHANDLE);
%we don't delete but preserve the waitbar for future use
%so the following cleanup is needed
p=get(get(WHANDLE,'children'),'children');
set(p(2),'erasemode','normal');
waitbar(0,WHANDLE,sprintf(' \n \n \n' ));
set(WHANDLE,'name',[' PRWAITBAR: ']);
set(p(2),'erasemode','none');
prwaitbar;
%no we are ready to leave
else
if significant1
set(WHANDLE,'name',[' PRWAITBAR: ' FNAME{DEPTH}]);
end
end
end
if nargout > 0
varargout = {WHANDLE};
end
return
function s = wtext(MESS,N,DEPTH)
t = cell(1,DEPTH);
n = 0;
for j=1:DEPTH
if N(j) > 1
n = n+1;
t{n} = MESS{j};
end
end
if n == 0
s = sprintf([' \n \n \n \n ']);
elseif n == 1
s = sprintf([' \n \n' t{1} '\n ']);
elseif n == 2
s = sprintf([' \n' t{1} '\n' t{2} '\n ']);
elseif n == 3
s = sprintf([' \n' t{1} '\n' t{2} '\n' t{3}]);
else
s = sprintf([t{n-3} '\n' t{n-2} '\n' t{n-1} '\n' t{n}]);
end
return
|
github
|
jacksky64/imageProcessing-master
|
neurc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/neurc.m
| 4,133 |
utf_8
|
b5c828f2c19833cfaf7febcd6f54c3bb
|
%NEURC Automatic neural network classifier
%
% W = NEURC (A,UNITS)
%
% INPUT
% A Dataset
% UNITS Number of units
% Default: 0.2 x size smallest class in A.
%
% OUTPUT
% W Trained feed-forward neural network mapping
%
% DESCRIPTION
% Automatically trained feed-forward neural network classifier with UNITS
% units in a single hidden layer. Training, by LMNC, is stopped when the
% performance on an artificially generated tuning set of 1000 samples per
% class (based on k-nearest neighbour interpolation) does not improve anymore.
%
% NEURC always tries three random initialisations, with fixed random seeds,
% and returns the best result according to the tuning set. This is done in
% order to obtain a reproducable result.
%
% If UNITS is NaN it is optimised by REGOPTC. This may take a long
% computing time and is often not significantly better than the default.
%
% Uses the Mathworks' neural network toolbox.
%
% SEE ALSO
% MAPPINGS, DATASETS, LMNC, BPXNC, GENDATK, REGOPTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: neurc.m,v 1.9 2008/07/03 09:11:44 duin Exp $
function argout = neurc (a,units)
prtrace(mfilename);
mapname = 'Automatic Neural Classifier';
n_attempts = 3; % Try three different random initialisations.
if (nargin < 2)
units = [];
end
if (nargin < 1) | (isempty(a))
w = mapping(mfilename,units);
argout = setname(w,mapname);
return
end
[m,k] = size(a);
if isempty(units)
cs = classsizes(a);
units = ceil(0.2*min(cs));
end
if (~ismapping(units))
if isnan(units) % optimize complexity parameter: number of neurons
defs = {[]};
parmin_max = [1,30];
w = regoptc(a,mfilename,{units},defs,[1],parmin_max,testc([],'soft'),0);
return
end
islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a);
%a = setprior(a,getprior(a));
% Second parameter is not a mapping: train a network.
% Reproducability: always use same seeds.
rand('seed',1); randn('seed',1); opt_err = inf; opt_mapping = [];
% Try a number of random initialisations.
s = sprintf('%i neural network initializations: ',n_attempts);
prwaitbar(n_attempts,s);
for attempt = 1:n_attempts
prwaitbar(n_attempts,attempt,[s int2str(attempt)]);
prwarning(4,'training with initialisation %d of %d',attempt,n_attempts);
t = gendatk(a,1000,2,1); % Create tuning set based on training set.
w = lmnc(a,units,inf,[],t); % Find LMNC mapping.
e = t*w*testc; % Calculate classification error.
if (e < opt_err)
% If this is the best of the three repetitions, store it.
opt_mapping = w; opt_err = e;
end
end
prwaitbar(0);
% Output is best network found.
argout = setname(opt_mapping,mapname);
else
nodatafile(a);
% Second parameter is a mapping: execute.
w = units;
data = getdata(w);
if (length(data) > 1)
% "Old" neural network - network is second parameter: unpack.
data = getdata(w); weights = data{1};
pars = data{2}; numlayers = length(pars);
output = a; % Output of first layer: dataset.
for j = 1:numlayers-1
% Number of inputs (n_in) and outputs (n_out) of neurons in layer J.
n_in = pars(j); n_out = pars(j+1);
% Calculate output of layer J+1. Note that WEIGHTS contains both
% weights (multiplied by previous layer's OUTPUT) and biases
% (multiplied by ONES).
this_weights = reshape(weights(1:(n_in+1)*n_out),n_in+1,n_out);
output = sigm([output,ones(m,1)]*this_weights);
% Remove weights of this layer.
weights(1:(n_in+1)*n_out) = [];
end
else
% "New" neural network: unpack and simulate using the toolbox.
net = data{1};
output = sim(net,+a')';
end;
% 2-class case, therefore 1 output: 2nd output is 1-1st output.
if (size(output,2) == 1)
output = [output (1-output)];
end
% Output is mapped dataset.
argout = setdat(a,output,w);
end
return
|
github
|
jacksky64/imageProcessing-master
|
scatterd.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/scatterd.m
| 10,094 |
utf_8
|
b2c8340e223bd55cc3a165e54701df03
|
%SCATTERD Display scatterplot
%
% H = SCATTERD(A)
% H = SCATTERD(A,DIM,S,CMAP,FONTSIZE,'label','both','legend','gridded')
%
% INPUT
% A Dataset or matrix
% DIM Number of dimensions: 1,2 or 3 (optional; default: 2)
% S String specifying the colors and markers (optional)
% CMAP Matrix with a color map (optional)
%
% OUTPUT
% H Vector of handles
%
% DESCRIPTION
% SCATTERD(A) displays a 2D scatterplot of the first two features of the
% dataset A. If the number of dimensions DIM is specified (1..3), it plots
% the first D features in a D-dimensional plot (D<4). If the plot string S
% is provided, e.g. S = 'w+', all points are plotted accordingly. If given,
% different plot strings are used for different classes. See PLOT for the
% specification of plot strings.
%
% If CMAP is specified, the color of the object symbols is determined by
% CMAP indexed by the object labels. A colormap has the size [C x 3], where
% C is the number of classes. The three components of CMAP(I,:) determine
% the red, green and blue components of the color. For instance:
%
% MAP = HSV; [M,K] = SIZE(A); LABELS = CEIL(64*[1:M]'/M);
% A = DATASET(A,LABELS); SCATTERD(A,'.','COLORMAP',MAP);
%
% This may be used for tracking ordered objects.
%
% FONTSIZE may be a vector with three elements: fontsize, markersize and
% size of the label font in case of a label plot.
%
% Various other options are:
% 'LABEL' : plot labels instead of symbols
% 'BOTH' : plot labels next to each sample
% 'LEGEND' : place a legend in the figure
% 'GRIDDED': make a grid of 2D scatterplots of each pair of features
%
% All the parameters, except for the dataset A can be specified in any
% order or can be left out.
%
% Classifiers can be plot in the scatterplot by PLOTC.
% Note that PLOTC does not work for 1D and 3D scatterplots.
%
% EXAMPLES
% See PREX_CONFMAT, PREX_DENSITY, PREX_PLOTC, PREX_MCPLOT.
%
% SEE ALSO
% DATASETS, COLORMAP, PLOT, PLOTC
% Copyright: D. de Ridder, R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: scatterd.m,v 1.8 2010/06/25 09:52:40 duin Exp $
% REVISIONS
% DR1 - Dick, 05-10-2004
% Added plotting of unlabeled data as 'k.'.
function handle = scatterd(a,p1,p2,p3,p4,p5,p6,p7,p8)
prtrace(mfilename);
% Defaults
d = min(size(a,2),2); % Dimensionality of plot
s = []; % Plot symbol(s)
map = []; % Color map
plotlab = 0; % Put text labels instead of or next to samples
plotsym = 1; % Plot symbols for samples
plotlegend = 0; % Plot legend
gridded = 0; % Make a gridded plot
gridrun = 0; % Inner loop in a gridded plot?
font_size = [];
mark_size = [];
lab_size = [];
hold_axis = ishold; % A flag to check if 'hold on' is set for the current axis
if size(a,2) > 3, a = a(:,1:3); end
a = dataset(a); % Allow for a non-dataset data
a = remclass(a);
if (nargin < 9), par{8} = []; else, par{8} = p8; end
if (nargin < 8), par{7} = []; else, par{7} = p7; end
if (nargin < 7), par{6} = []; else, par{6} = p6; end
if (nargin < 6), par{5} = []; else, par{5} = p5; end
if (nargin < 5), par{4} = []; else, par{4} = p4; end
if (nargin < 4), par{3} = []; else, par{3} = p3; end
if (nargin < 3), par{2} = []; else, par{2} = p2; end
if (nargin < 2), par{1} = []; else, par{1} = p1; end
% Set up default values.
for i = 1:5
if (~isempty(par{i}))
if (length(par{i}) == 1) & par{i} < 5 & (~ischar(par{i})) % Dimensionality
d = par{i}; par{i} = 2; % Necessary for gridded: D needs to be 2.
elseif ((size(par{i},1) > 1) & (size(par{i},2)==3) & (~ischar(par{i}))) % Color map
map = par{i};
elseif (strcmp(par{i},'label'))
plotlab = 1; plotsym = 0;
elseif (strcmp(par{i},'both'))
plotlab = 1; plotsym = 1;
elseif (strcmp(par{i},'legend'))
plotlegend = 1;
elseif (strcmp(par{i},'gridded'))
gridded = 1;
par{i} = 'gridrun'; % Necessary for gridded: otherwise an infinite recursion :)
elseif (strcmp(par{i},'gridrun'))
gridrun = 1;
elseif ~isstr(par{i}) & length(par{i}) <= 3 & par{i}(1) >= 5
font_size = par{i}(1);
if length(par{i}) >= 2
mark_size = par{i}(2);
end
if length(par{i}) == 3
lab_size = par{i}(3);
end
else
s = par{i};
end
end
end
if (gridrun)
if isempty(font_size), font_size = 10; end
if isempty(mark_size), mark_size = 5; end
if isempty(lab_size), lab_size = 8; end
elseif (~hold_axis)
%clf;
cla;
if isempty(font_size), font_size = 16; end
if isempty(mark_size), mark_size = 7; end
if isempty(lab_size), lab_size = 14; end
else
if isempty(font_size), font_size = get(gca,'fontsize'); end
if isempty(mark_size), mark_size = font_size/2; end
if isempty(lab_size), lab_size = font_size-2; end
end
feats = getfeatlab(a,'string');
if isempty(feats)
for i=1:size(a,2)
feats = strvcat(feats,sprintf('Feature %d',i));
end
else
if size(feats,2) == 1
feats = [repmat('Feature ',size(feats,1),1) feats];
end
end
if (gridded)
clf;
gs = size(a,2);
for i = 1:gs
for j = 1:gs
subplot(gs,gs,(i-1)*gs+j);
gridrun = 1;
h = feval(mfilename,a(:,[j i]),par{1},par{2},par{3},par{4},par{5},par{6},par{7});
gridrun = 0;
if (i~=gs), xlabel(''); end
if (j~=1), ylabel(''); end
end
subplot(111); % Takes care of clf for the next scatterplot.
end
return;
end
if (isa(a,'dataset')) & (~isempty(getlablist(a)))
[m,k,c] = getsize(a);
lab = getnlab(a);
lablist = getlablist(a,'string');
ident = getident(a); %DXD: needed for prcursor
dataset_name = getname(a);
a = double(a);
else
[m,k] = size(a);
lab = ones(m,1);
ident = (1:m)'; %DXD: needed for prcursor
dataset_name = [];
c = 1;
a = double(a);
end
% Character string defining the plotting setup in terms of symbols and colors.
if (isempty(s))
vers = version;
if (str2num(vers(1)) < 5)
col = 'brmw';
sym = ['+*xo.']';
i = [1:20];
ss = [col(i-floor((i-1)/4)*4)' sym(i-floor((i-1)/5)*5)];
else
col = 'brmk';
sym = ['+*oxsdv^<>p']';
i = [1:44];
ss = [col(i-floor((i-1)/4)*4)' sym(i-floor((i-1)/11)*11)];
end
ss = ['k.'; ss]; % DR1 - Add symbol for "unlabeled" data.
[ms,ns] = size(ss);
if ms == 1, ss = setstr(ones(m,1)*ss); end
else
if size(s,1) == 1
ss = repmat(s,c,1); s = [];
else
ss = s; s = [];
end
ss = char('k.', ss); % DR1 - Add symbol for "unlabeled" data.
%DXD - changed [.] into char(.)
end
% Define some 'space' OY to be added around the data plotted in symbols.
oy = zeros(1,3);
if (plotsym)
oy = 0.02*(max(a)-min(a));
else
s = 'w.'; % Plot white spot instead of symbols.
end
oy(2) = 0;
% Make a plot.
lhandle = []; thandle = [];
% Also plot label "0" (unlabeled).
for i = 0:c
J = find(lab==i);
if (isempty(s)), symbol = ss(i+1,:); else, symbol = s; end
if ((d == 1) & ~isempty(J))
h = plot(a(J,1),zeros(length(J),1),symbol);
hold on;
set(h,'markersize',mark_size);
lhandle = [lhandle h];
if (plotlab)
for j = 1:length(J)
h = text(a(J(j),1)+oy(1),oy(2),lablist(lab(J(j)),:));
set(h,'fontsize',lab_size);
thandle = [thandle h]; if (~isempty(map)), set (h, 'color', map(i+1,:)); end
end
end
elseif ((d == 2) & ~isempty(J))
h = plot(a(J,1),a(J,2),symbol);
hold on;
set(h,'markersize',mark_size);
lhandle = [lhandle h];
if (plotlab)
for j = 1:length(J)
h = text(a(J(j),1)+oy(1),a(J(j),2)+oy(2),lablist(lab(J(j)),:));
set(h,'fontsize',lab_size);
thandle = [thandle h]; if (~isempty(map)), set (h, 'color', map(i+1,:)); end
end
end
elseif (~isempty(J))
h = plot3(a(J,1),a(J,2),a(J,3),symbol);
hold on;
set(h,'markersize',mark_size);
lhandle = [lhandle h];
if (plotlab)
for j = 1:length(J)
h = text(a(J(j),1)+oy(1),a(J(j),2)+oy(2),a(J(j),3)+oy(3),lablist(lab(J(j)),:));
set(h,'fontsize',lab_size);
thandle = [thandle h]; if (~isempty(map)), set (h, 'color', map(i+1,:)); end
end
end
end
%DXD: store the object identifiers in the userdata such that you
%can retrieve them by prcursor:
if ~isempty(J)
ud = get(h,'UserData');
ud.ident = ident(J);
set(h,'UserData',ud);
end
end
if (plotsym)
if (~isempty(map))
for i = 0:c, set (lhandle(i+1), 'color', map(i+1,:)); end
end
if (plotlegend),
[ht, hl] = legend(lhandle(:),lablist);
hl = hl(:)';
%set(hl(1:2*c),'markersize',mark_size);
lhandle = [lhandle hl];
thandle = [thandle ht(:)'];
end
end
% !%_%*!_% Matlab
set(gca,'fontsize',font_size);
if (~hold_axis)
dd = (max(a,1) - min(a,1))*0.05; % offset, avoiding points on plot box.
J = find(dd==0);
dd(J) = dd(J)+1;
%feats
if (d == 1),
axis ([min(a(:,1))-dd(1) max(a(:,1))+dd(1) -0.5 0.5]);
hx = xlabel(feats(1,:));
thandle = [thandle hx];
elseif (d == 2),
axis ([min(a(:,1))-dd(1) max(a(:,1))+dd(1) min(a(:,2))-dd(2) max(a(:,2))+dd(2)]);
hx = xlabel(feats(1,:)); hy = ylabel(feats(2,:));
thandle = [thandle(:)' hx hy];
view(2);
else % D = 3
axis ([min(a(:,1))-dd(1) max(a(:,1))+dd(1) min(a(:,2))-dd(2) max(a(:,2))+dd(2) min(a(:,3))-dd(3) max(a(:,3))+dd(3)]);
hx = xlabel(feats(1,:)); hy = ylabel(feats(2,:)); hz = zlabel(feats(3,:));
thandle = [thandle hx hy hz];
view(3);
end
end
%if (~gridrun) & (length(get(gcf,'children')) < 3 & any(get(gca,'position')>0.80))
if (~gridrun) & (length(get(gcf,'children')) < 3)
P = get(gca,'position');
if any(P) > 0.80 & all(P(3:4)>0.50) % don't do this in case of subplots
set(gca,'position',[0.13 0.13 0.79 0.78]); % make axis labels visible
end
end
if (~gridrun) & (~isempty(dataset_name))
title(dataset_name);
end
hold off;
if (nargout > 0)
handle = [lhandle thandle];
end
%DXD this should be standard:
vers = version;
if (str2num(vers(1)) > 6)
prcursor(gcf);
datacursormode('off');
end
return;
|
github
|
jacksky64/imageProcessing-master
|
vpc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/vpc.m
| 5,242 |
utf_8
|
3bc522bdc5d792c6303aad94091f0788
|
function B = vpc(A, W)
%VPC Voted perceptron classifier
%
% W = VPC(A)
% W = VPC(A, N)
%
% INPUT
% A Dataset
% N Number of sweeps
%
% OUTPUT
% W Voted perceptron classifier
%
% DESCRIPTION
% The classifier trains an ensemble of perceptrons on dataset A. The
% training procedure performs N full sweeps through the training data. If N
% is not specified, 10 sweeps are performed. The total number of
% perceptrons in the ensemble is equal to N x GETSIZE(A, 1).
%
% New objects are classified is performed by allowing the ensemble of
% perceptrons to vote on the label of each test point.
%
% REFERENCE
% Y. Freund and R.E. Schapire. Large Margin Classification Using the
% Perceptron Algorithm. Machine Learning 37(3):277-296, 1999.
%
% SEE ALSO
% DATASETS, MAPPINGS, PERLC, ADABOOSTC
% (C) Laurens van der Maaten, 2010
% University of California, San Diego
name = 'Voted perceptron';
% Handle untrained calls like W = vpc([]);
if nargin == 0 || isempty(A)
B = mapping(mfilename);
B = setname(B, name);
return;
% Handle training on dataset A (use A * vpc, A * vpc([]), and vpc(A))
elseif (nargin == 1 && isa(A, 'dataset')) || (isa(A, 'dataset') && isa(W, 'double'))
if nargin == 1
W = 10;
end
islabtype(A, 'crisp');
isvaldfile(A, 1, 2);
A = testdatasize(A, 'features');
A = setprior(A, getprior(A));
[m, k, c] = getsize(A);
[data.v, data.c] = train_voted_perceptron(+A, getnlab(A), W);
B = mapping(mfilename, 'trained', data, getlablist(A), k, c);
B = setname(B, name);
% Handle evaluation of a trained voted perceptron W for a dataset A
elseif isa(A, 'dataset') && isa(W, 'mapping')
test_post = predict_voted_perceptron(+A, W.data.v, W.data.c);
A = dataset(A);
B = setdata(A, test_post, getlabels(W));
% This should not happen
else
error('Illegal call');
end
end
function [v, c] = train_voted_perceptron(train_X, train_labels, max_iter)
%TRAIN_VOTED_PERCEPTRON Trains a voted perceptron on the specified data set
%
% [v, c] = train_voted_perceptron(train_X, train_labels, max_iter)
%
% The function trains a voted perceptron on the data specified by train_X
% and train_labels. For a problem with K classes, the functions trains K
% voted perceptrons in a one-vs-all manner. The cell-array v contains the
% perceptrons for each class, whereas the cell-array c contains the
% corresponding weights of the perceptrons.
%
%
% (C) Laurens van der Maaten, 2010
% University of California, San Diego
% Add the bias term to the data
train_X = [train_X ones(size(train_X, 1), 1)];
% Initialize some variables
[n, d] = size(train_X);
lablist = unique(train_labels);
no_labels = length(lablist);
% Shuffle the data
ind = randperm(n);
train_X = train_X(ind,:);
train_labels = train_labels(ind);
% Initialize voted perceptron cell arrays
c = cell(no_labels, 1);
v = cell(no_labels, 1);
% Loop over all classes
for k=1:no_labels
% Initialize voted perceptron
v{k} = zeros(d, ceil(n * max_iter / 4)); % perceptrons
c{k} = zeros(1, ceil(n * max_iter / 4)); % survival times
index = 1;
% Construct appropriate labelling
labels = train_labels;
labels(labels ~= k) = -1;
labels(labels == k) = 1;
% Perform learning iterations
for iter=1:max_iter
% Loop over all data points
for i=1:n
% Perform prediction
y = +sign(train_X(i,:) * v{k}(:,index));
% Train new perceptron if misclassified, or increase weight
if y == labels(i)
c{k}(index) = c{k}(index) + 1;
else
v{k}(:,index + 1) = v{k}(:,index) + labels(i) .* train_X(i,:)';
c{k}( index + 1) = 1;
index = index + 1;
end
end
end
% Make sure we do not have 'empty' perceptrons left
v{k} = v{k}(:,1:index);
c{k} = c{k}( 1:index);
end
end
function test_post = predict_voted_perceptron(test_X, v, c)
%PREDICT_VOTED_PERCEPTRON Classify test data using a voted perceptron
%
% test_post = predict_voted_perceptron(test_X, v, c, lablist)
%
% The function classifies the data points in test_X using the voted
% perceptron specified by v and c. The voted perceptron can be trained
% using the TRAIN_VOTED_PERCEPTRON function.
%
%
% (C) Laurens van der Maaten, 2010
% University of California, San Diego
% Add the bias term to the data
test_X = [test_X ones(size(test_X, 1), 1)];
% Prediction is maximum over all voted perceptrons
test_post = zeros(size(test_X, 1), length(v));
for k=1:length(v)
test_post(:,k) = sum(bsxfun(@times, c{k}, +sign(test_X * v{k})), 2);
end
% Estimate posterior if requested
for k=1:length(c)
test_post(:,k) = test_post(:,k) + sum(c{k});
end
test_post = bsxfun(@rdivide, test_post, sum(test_post, 2));
end
|
github
|
jacksky64/imageProcessing-master
|
featselp.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featselp.m
| 5,680 |
utf_8
|
95c5a90a0e6120fc254389b69a95cdf7
|
%FEATSELP Pudil's floating feature selection (forward)
%
% [W,R] = FEATSELP(A,CRIT,K,T,FID)
%
% INPUT
% A Training dataset
% CRIT Name of the criterion or untrained mapping
% (default: 'NN', 1-Nearest Neighbor error)
% K Number of features to select (default: K = 0, select optimal set)
% T Tuning dataset (optional)
% N Number of cross-validations (optional)
% FID File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% W Feature selection mapping
% R Matrix with step-by-step results
%
% DESCRIPTION
% Forward floating selection of K features using the dataset A. CRIT sets
% the criterion used by the feature evaluation routine FEATEVAL. If the
% dataset T is given, it is used as test set for FEATEVAL. Alternatively
% a number of cross-validations N may be supplied. For K = 0, the optimal
% feature set (maximum value of FEATEVAL) is returned. The result W can
% be used for selecting features in a dataset B using B*W.
% The selected features are stored in W.DATA and can be found by +W.
%
% Note: this routine is highly time consuming.
%
% In R the search is reported step by step:
%
% R(:,1) : number of features
% R(:,2) : criterion value
% R(:,3) : added / deleted feature
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELI,
% FEATSEL, FEATSELF, FEATSELM, PRPROGRESS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: featselp.m,v 1.5 2009/07/01 09:33:23 duin Exp $
function [w,r] = featselp(a,crit,ksel,t,fid)
prtrace(mfilename);
if (nargin < 2) | isempty(crit)
prwarning(2,'no criterion specified, assuming NN');
crit = 'NN';
end
if (nargin < 3) | isempty(ksel)
ksel = 0;
end
if (nargin < 4) | isempty(t)
prwarning(3,'no tuning set supplied (risk of overfit)');
t = [];
end
if (nargin < 5)
fid = [];
end
% If no arguments are supplied, return an untrained mapping.
if (nargin == 0) | (isempty(a))
w = mapping('featselp',{crit,ksel,t});
w = setname(w,'Floating FeatSel');
return
end
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a);
iscomdset(a,t);
[m,k,c] = getsize(a); featlist = getfeatlab(a);
% If KSEL is not given, return all features.
if (ksel == 0)
peak = 1; ksel = k;
else
peak = 0;
end
if (~isempty(t))
if (k ~= size(t,2))
error('The sizes of the training and tuning dataset do not match.')
end
end
critval_opt = zeros(1,k); % Maximum criterion value for sets of all sizes.
critval_max = 0; % Maximum criterion value found so far.
I = [1:k]; % Pool of remaining feature indices.
J = []; % Pool of selected feature indices.
r = []; % Result matrix with selection history.
Iopt = J;
n = 0;
prprogress(fid,'\nfeatselp: Pudils Floating Search\n')
while (n < k)
critval = zeros(1,length(I));
% Add the best feature.
for j = 1:length(I)
L = [J,I(j)]; % Add one feature to the already selected ones.
if (isempty(t)) % Evaluate the criterion function.
critval(j) = feateval(a(:,L),crit);
else
critval(j) = feateval(a(:,L),crit,t(:,L));
end
% If this feature is the best so far and we have not yet selected
% KSEL features, store it.
if (critval(j) > critval_max) & (n < ksel)
n_max = length(L);
critval_max = critval(j);
Iopt = L;
end
end
[mx,j] = max(critval); % Find best feature of the remaining ones,
J = [J, I(j)]; % add it to the set of selected features
I(j) = []; % and remove it from the pool.
% Store the best criterion value found for any set of n features.
n = n + 1; critval_opt(n) = mx;
r = [r; [n, mx, J(end)]];
prprogress(fid,' %d %f',r(end,1:2));
prprogress(fid,' %i',J);
prprogress(fid,'\n')
% Now keep removing features until the criterion gets worse.
while (n > 2)
critval = zeros(1,n);
for j = 1:n
L = J; L(j) = []; % Remove one feature from the selected ones.
if (isempty(t)) % Evaluate the criterion function.
critval(j) = feateval(a(:,L),crit);
else
critval(j) = feateval(a(:,L),crit,t(:,L));
end
% If removing this feature gives the best result so far (or
% the same result using less features), and we have not yet
% removed all KSEL features, store it.
if ((critval(j) > critval_max) | ((critval(j) == critval_max) & ...
(length(L) < n_max))) & ...
(n <= ksel + 1)
n_max = length(L);
critval_max = critval(j);
Iopt = L;
end
end
% If this subset is better than any found before, store and report it.
% Otherwise, stop removing features.
[mx,j] = max(critval);
if (mx > critval_opt(n-1))
n = n - 1; critval_opt(n) = mx;
I = [I,J(j)]; J(j) = [];
r = [r; [n, mx, -I(end)]];
prprogress(fid,' %d %f',r(end,1:2));
prprogress(fid,' %i',J);
prprogress(fid,'\n')
else
break;
end
end
% If we have found more than KSEL features, return the mapping using
% the best KSEL features.
if (n > ksel)
if (ksel < length(Iopt))
J = Iopt(1:ksel);
else
J = Iopt;
end
prprogress(fid,'featselp finished\n')
w = featsel(k,J);
if ~isempty(featlist)
w = setlabels(w,featlist(J,:));
end
w = setname(w,'Floating FeatSel');
return
end
end
prprogress(fid,'featselp finished\n')
% Return all features, sorted by their criterion value.
w = featsel(k,Iopt);
if ~isempty(featlist)
w = setlabels(w,featlist(Iopt,:));
end
w = setname(w,'Floating FeatSel');
return
|
github
|
jacksky64/imageProcessing-master
|
labelim.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/labelim.m
| 1,675 |
utf_8
|
54421f3d90d172ac5de0915a11706f21
|
%LABELIM Construct image of object (pixel) labels
%
% IM = LABELIM(A)
% IM = A*LABELIM
%
% INPUT
% A Dataset containing images stored as features
%
% OUTPUT
% IM Image containing the labels of the objects
%
% DESCRIPTION
% For a dataset A containing images stored as features, where each pixel
% corresponds to an object, the routine creates an image presenting the
% labels of the objects. Note that if the number of classes is small, e.g.
% 2, an appropriate colormap will have to be loaded for displaying the
% result using IMAGE(LABELS). More appropriate, LABELS should be multiplied
% such that the minimum and maximum of LABELS are well spread in the [1,64]
% interval of the standard colormaps.
% The resulting image may also directly be displayed by:
%
% LABELIM(A) or
% A*LABELIM
% for which a suitable colormap is loaded automatically.
%
% SEE ALSO
% DATASETS, CLASSIM
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: labelim.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function labels = labelim(a)
prtrace(mfilename);
% No arguments given: return an untrained mapping.
if (nargin == 0)
labels = mapping('labelim','fixed');
return
end
isfeatim(a); % Assert that A is a feature image dataset.
[n,m] = getobjsize(a); % Get image size and reshape labels to image.
J = getnlab(a); labels = reshape(J,n,m);
if (nargout == 0)
n = 61/(size(a,2)+0.5); % If no output is requested, display the
imagesc(labels*n); % image with a suitably scaled colormap.
colormap colorcube;
clear labels;
end
return
|
github
|
jacksky64/imageProcessing-master
|
parzen_map.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/parzen_map.m
| 3,716 |
utf_8
|
d8c30b56a555094142a25709bf69bcce
|
%PARZEN_MAP Map a dataset on a Parzen densities based classifier
%
% F = PARZEN_MAP(A,W)
%
% INPUT
% A Dataset
% W Trained Parzen classifier mapping (default: PARZENC(A))
%
% OUTPUT
% F Mapped dataset
%
% DESCRIPTION
% Maps the dataset A by the Parzen density based classfier W. F*sigm are the
% posterior probabilities. W should be trained by a classifier like PARZENC.
% This routine is called automatically to solve A*W, if W is trained by
% PARZENC.
%
% The global PRMEMORY is read for the maximum size of the internally declared
% matrix, default inf.
%
% SEE ALSO
% MAPPINGS, DATASETS, PARZENC, TESTP
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: parzen_map.m,v 1.5 2008/08/18 21:16:26 duin Exp $
function f = parzen_map(b,w)
prtrace(mfilename);
% If no mapping is supplied, train one.
if (nargin < 2)
w = parzenc(b);
end
pars = getdata(w);
a = pars{1}; % Stored training dataset.
h = pars{2}; % Smoothing paramater.
[m,k,c] = getsize(a); nlab = getnlab(a); p = getprior(a);
% do we have priors set in the mapping?
if length(pars)==3
p=pars{3};
end
% Prepare a matrix with smoothing parameters for each class and feature.
if (size(h,1) == 1)
h = repmat(h,c,1);
end
if (size(h,2) == 1)
h = repmat(h,1,k);
end
if (any(size(h) ~= [c,k]))
error('The size of the array with smoothing parameters does not match that of the training set of W.');
end
[mt,kt] = size(b);
if (kt ~= k)
error('The size of the set A does not match that of the training set of W.');
end
[num,n] = prmem(mt,m);
f = ones(mt,c); % Prob. densities for each test sample and class.
for j = 0:num-1 % Process each chunk of the test set separately.
if (j == num-1)
nn = mt - num*n + n; % Last chunk may have smaller size.
else
nn = n;
end
range = [j*n+1:j*n+nn];
% Estimate the class probabilities.
for i = 1:c
if islabtype(a,'crisp')
I = findnlab(a,i); hh = h(i,:); % Parameters for this class.
% Calculate squared distances to kernel centers.
D = +distm(a(I,:)./repmat(hh,length(I),1), ...
+b(range,:)./repmat(hh,length(range),1));
if (length(I) > 0)
f(range,i) = mean(exp(-D*0.5),1)'; % Apply kernel.
end
const = repmat(-log(length(I)),length(I),1);
else
hh = h(i,:);
I = find(a.targets(:,i) > 0); % Avoid objects with zero weight
v = a.targets(I,i);
D = distm(+a(I,:)./repmat(hh,length(I),1), ...
+b(range,:)./repmat(hh,length(range),1));
f(range,i) = exp(-D'*0.5) * v / sum(v);
const = log(v/sum(v));
end
% Normalize and multiply by class prior to get a density. Add REALMIN
% to prevent division-by-zero errors.
f(range,i) = p(i)*f(range,i)/((sqrt(2*pi).^k)*prod(hh)+realmin);
if (getout_conv(w) == 2) % take log of density to preserve tails
J = find(f(range,i) <= 1e-303);
N = find(f(range,i) > 1e-303);
f(range(N),i) = log(f(range(N),i));
[dm,R] = min(D(:,J)); % for zero densities use nearest neighbor only
%f(range(J),i) = log(p(i)/((sqrt(2*pi).^k)*prod(hh)+realmin)) - dm'*0.5 + const(R);
f(range(J),i) = log(p(i)) - k*log(sqrt(2*pi)) - sum(log(hh)) - dm'*0.5 + const(R);
% in case of soft labels this is tricki. We just hope that the
% weight of the nearest neighbor is sufficiently large
end
end
end
if (getout_conv(w) == 2) % scale to gain accuracy in the tails
fmax = max(f,[],2);
f = f - repmat(fmax,1,c);
f = exp(f);
else
f = f + realmin; % avoid devision by 0 in computing posterios later
end
f = setdata(b,f,getlabels(w));
return
|
github
|
jacksky64/imageProcessing-master
|
shiftop.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/shiftop.m
| 1,526 |
utf_8
|
b750bb7f4cdb20bd552bc18639636e71
|
%SHIFTOP Shift operating point of classifier
%
% S = SHIFTOP(D,E,C)
% S = SHIFTOP([],E,C);
%
% INPUT
% D Dataset, classification matrix (two classes only)
% E Desired error class N for D*TESTC
% C Index of desired class (default: C = 1)
%
% OUTPUT
% S Mapping, such that E = TESTC(D*S,[],LABEL)
%
% DESCRIPTION
% If D = A*W, with A a test dataset and W a trained classifier, then an ROC
% curve can be computed and plotted by ER = ROC(D,C), PLOTE(ER). C is the
% desired class number for which the error is plotted along the horizontal
% axis.
% The classifier W can be given any operating point along this curve by
% W = W*SHIFTOP(D,E,C)
%
% The class index C refers to its position in the label list of the dataset
% A used for training the classifier that yielded D. The relation to LABEL
% is LABEL = CLASSNAME(A,C); C = GETCLASSI(A,LABEL).
%
% SEE ALSO
% DATASETS, MAPPINGS, TESTC, ROC, PLOTE, CLASSNAME, GETCLASSI
function w = shiftop(d,e,n)
isdataset(d);
if any(any(+d)) < 0
error('Classification matrix should have non-negative entries only')
end
[m,c] = size(d);
if c ~= 2
error('Only two-class classification matrices are supported')
end
if nargin < 3 | isempty(n)
n = 1;
end
s = classsizes(d);
d = seldat(d,n)*normm;
[~,L] = sort(+d(:,n));
k = floor(e*s(n));
k = max(k,1); % avoid k = 0
alf = +(d(L(k),:)+d(L(k+1),:))/2;
if n == 1
w = diag([alf(2)/alf(1) 1]);
else
w = diag([1 alf(1)/alf(2)]);
end
w = affine(w);
|
github
|
jacksky64/imageProcessing-master
|
fisherm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/fisherm.m
| 3,331 |
utf_8
|
f729ad07dd78730a8680ff448b9c31b4
|
%FISHERM Optimal discrimination linear mapping (Fisher mapping, LDA)
%
% W = FISHERM(A,N,ALF)
%
% INPUT
% A Dataset
% N Number of dimensions to map to, N < C, where C is the number of classes
% (default: min(C,K)-1, where K is the number of features in A)
% ALF Preserved variance in the pre-whitening step
%
% OUTPUT
% W Fisher mapping
%
% DESCRIPTION
% Finds a mapping of the labeled dataset A onto an N-dimensional linear
% subspace such that it maximizes the the between scatter over the within
% scatter (also called the Fisher mapping [1 or LDA]). Note that N should be
% less than the number of classes in A. If supplied, ALF determines the
% preserved variance in the prewhitening step (i.e. removal of insignificant
% eigenvectors in the within-scatter, the EFLD procedure [2]), see KLMS.
%
% The resulting mapping is not orthogonal. It may be orthogonalised by ORTH.
%
% REFERENCES
% [1] K. Fukunaga, Introduction to statistical pattern recognition, 2nd
% ed., Academic Press, New York, 1990.
% [2] C. Liu and H. Wechsler, Robust Coding Schemes for Indexing and Retrieval
% from Large Face Databases, IEEE Transactions on Image Processing, vol. 9,
% no. 1, 2000, 132-136.
%
% SEE ALSO
% MAPPINGS, DATASETS, NLFISHERM, KLM, PCA, KLMS, ORTH
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: fisherm.m,v 1.4 2007/04/21 23:05:59 duin Exp $
function w = fisherm(a,n,alf)
prtrace(mfilename);
if (nargin < 3)
alf = [];
prwarning (4, 'no pre-whitening reduction specified, so take all features');
end
if (nargin < 2)
prwarning (4, 'number of dimensions to map to not specified, assuming min(C,K)-1');
n = [];
end
% If no arguments are specified, return an untrained mapping.
if (nargin < 1) | (isempty(a))
w = mapping('fisherm',{n,alf});
w = setname(w,'Fisher mapping');
return
end
islabtype(a,'crisp','soft');
a = testdatasize(a);
isvaldset(a,2,2); % at least 2 objects per class, 2 classes
[m,k,c] = getsize(a);
% If N is not given, set it.
%DXD Question: why do we subtract here 1 from k? Should it not be
% the next one??
%if (isempty(n)), n = min(k,c)-1; end
if (isempty(n)), n = min(k,c-1); end
if (n >= m) | (n >= c) | (n > k)
error('The dataset is too small or has too few classes for the requested dimensionality')
end
% A Fisher mapping is determined by the eigenvectors of inv(W)*B, where W
% is the within-scatter matrix, i.e. the average covariance matrix
% weighted by the prior probabilities, and B is the between-scatter
% matrix.
% To simplify computations, W can be set to the identity matrix if A is
% centered and sphered by KLMS.
a = setprior(a,getprior(a)); % set priors to avoid unnecessary warnings
v = klms(a,alf); a = a*v;
% Calculate eigenvectors of B.
u = pca(meancov(a),n);
if (n == 0)
%DXD: Careful here: I wanted to make the option n==0 behave the
% same as in pca(x,0) and bhatm(x,0). Unfortunately, it was
% already defined. So I overrule it now!!!! Please correct
% if you don't agree!
w = u;
return
%w = v; % Only one feature is available (k=1)
else
w = v*u; % Construct final mapping.
end
w = setname(w,'Fisher mapping');
return
|
github
|
jacksky64/imageProcessing-master
|
im_box.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_box.m
| 2,487 |
utf_8
|
0744833225729dd9a4c7960608872873
|
%IM_BOX Find rectangular image in datafile enclosing a blob (0/1 image)
%
% B = IM_BOX(A)
% B = A*IM_BOX
%
% If A is a 0/1 image then B is the same image with all empty (0) border
% columns and rows removed.
%
% B = IM_BOX(A,N)
%
% If A is a 0/1 image then B is the same image, but having in each direction
% N empty (0) columns and rows around the object (1).
%
% B = IM_BOX(A,[NX1 NX2 NY1 NY2])
%
% If A is a 0/1 image then B is the same image, but having NX1, NX2 empty
% columns (0) left, respectively right of the object (1) and NY1, NY2 empty
% rows (0) above, respectively below the object(1).
%
% B = IM_BOX(A,N,ALF)
%
% Adds as many empty (0) columns or rows such that the aspect ratio of
% images (height/width) equals ALF. For ALF == 1, square images are returned.
% For ALF == 0, images are taken as they are and N rows and columns are
% added.
%
% SEE ALSO
% DATASETS, DATAFILES
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [b,J] = im_box(a,n,alf)
prtrace(mfilename);
if nargin < 3, alf = []; end
if nargin < 2 | isempty(n), n= []; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{n,alf});
b = setname(b,'Image bounding box');
elseif isdataset(a)
error('Command cannot be used for datasets as it may change image size')
elseif isdatafile(a)
isobjim(a);
b = filtim(a,mfilename,{n,alf});
b = setfeatsize(b,getfeatsize(a));
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
if isa(a,'dip_image'), a = double(a); end
if isempty(n)
jx = find(sum(a,1) ~= 0);
jy = find(sum(a,2) ~= 0);
J = [min(jy),max(jy),min(jx),max(jx)];
b = a(min(jy):max(jy),min(jx):max(jx));
else
if (~isempty(alf) & alf == 0)
c = a;
else
c = feval(mfilename,a);
end
[my,mx] = size(c);
if length(n) == 1
n = [n n n n];
elseif length(n) ~= 4
error('Second parameter should be scalar or vector of length 4')
end
b = zeros(my+n(3)+n(4),mx+n(1)+n(2));
b(n(3)+1:n(3)+my,n(1)+1:n(1)+mx) = c;
end
if ~isempty(alf) & alf ~= 0
[m,k] = size(b);
r = round(m*alf) - k;
if r == 0
;
elseif r >= 1 % add r columns
c = zeros(m,k+r);
c(:,ceil(r/2):ceil(r/2)+k-1) = b;
b = c;
else % add rows
r = round(k/alf) - m;
c = zeros(m+r,k);
c(ceil(r/2):ceil(r/2)+m-1,:) = b;
b = c;
end
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_patch.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_patch.m
| 5,368 |
utf_8
|
cee874a6d4aa0b4e1e79057508a0eeb8
|
%IM_PATCH Generate patches from images
%
% B = IM_PATCH(A,PSIZE,PNUM,TYPE)
% B = IM_PATCH(A,PSIZE,COORD,'user')
% W = IM_PATCH([],PSIZE,PNUM,TYPE)
% B = A*W
%
% INPUT
% A Dataset or datafile with (multi-band) object images dataset
% PSIZE 2-dimensional patch size. If PSIZE is 1-dimensional square
% patches of size PSIZE x PSIZE are generated. In case PSIZE < 1,
% it is taken relatuive to the images size. In this case patches
% may become non-square for non-square images. Default 3 x 3
% PNUM Number of patches, see TYPE, default 1
% COORD Given set of N x 2 image coordinates of patch centra. This may
% be given either in pixels (ANY(COORD > 1) or relative to the
% image size (ALL(COORD <= 1).
% TYPE 'syst': systematic sampling generating PNUM x PNUM patches
% 'rand': generation of a random set op PNUM patches
% 'user': user defined patch positions, see COORD
% Default: 'syst'.
%
% OUTPUT
% W Mapping performing the desired patch generation
% B Resulting dataset or datafile with the same number of objects
% as in A. Single images are replaced by the patches.
%
% DESCRIPTION
% The object images (including their N bands) are sampled and windows of size
% PSIZE are generated, replacing the original image object. They are stored
% as [PSIZE(1) PSIZE(2) NUM*N] image objects, in which N is the original
% number of bands and NUM is either PNUM (for TYPE is 'rand' or 'user') or
% PNUM x PNUM (for TYPE is 'syst').
%
% By BAND2OBJ(B,N) individual patches can be transformed into objects.
%
% EXAMPLES
% B = IM_PATCH(A,0.5) % generate just the central parts of the images
% B = IM_PATCH(A,[3 5],2) % generates 4 patches of size 3x5 in centra of
% % the four quadrants
% B = IM_PATCH(A,0.1,10,'rand') % generate at random positions 10 patches
% %each with a linear size of 0.1 of the image size.
%
% SEE ALSO
% DATASETS, DATAFILES, BAND2OBJ
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_patch(a,psize,pnum,option,N)
prtrace(mfilename);
if nargin < 5, N = []; end % N just needed for datafiles that want to have a single patch
if nargin < 4 | isempty(option), option = 'syst'; end
if nargin < 3, pnum = 1; end
if nargin < 2, psize = [3 3]; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{psize,pnum,option});
b = setname(b,'Image patches');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
fsize = getfeatsize(a,3);
if strcmp(option,'rand')
pnum = rand(pnum,2); % generate desired number of points
option = 'user';
end
b = filtim(a,mfilename,{psize,pnum,option},0);
else % here we have a single image
a = double(a);
asize = size(a);
if length(psize) == 1, psize = [psize psize]; end
if all(psize < 1), psize = psize.*asize; end
% user want to know how many patches
if ~isempty(N) & N == 0 % this is just a hack, could be smarter
if strcmp(option,'syst')
if length(pnum == 1), npatches = pnum*pnum;
else, npatches = prod(pnum); end
elseif strcmp(option,'user'), npatches = size(pnum,1);
elseif strcmp(option,'random'), npatches = pnum;
else error('Unknown option');
end
b = npatches;
return
end
rsize = round(psize);
if strcmp(option,'syst')
if length(pnum) == 1, pnum = [pnum pnum]; end
if isempty(N)
patches = zeros(rsize(1),rsize(2),pnum(1)*pnum(2));
else
patches = zeros(rsize(1),rsize(2),length(N));
end
for i=1:2
if pnum(i)*psize(i) <= asize(i)
%s(i) = asize(i)/(2*pnum(i))-psize(i)/2+0.5;
s(i) = asize(i)/(2*pnum(i))-psize(i)/2+1;
d(i) = asize(i)/pnum(i);
else
%s(i) = 0.5;
s(i) = 1;
d(i) = (asize(i)-psize(i))/(pnum(i)-1);
end
end
if isempty(N)
for j2 = 1:pnum(2)
for j1 = 1:pnum(1)
aa = a(round(s(1)+(j1-1)*d(1)):round(s(1)+(j1-1)*d(1))+rsize(1)-1, ...
round(s(2)+(j2-1)*d(2)):round(s(2)+(j2-1)*d(2))+rsize(2)-1);
patches(:,:,(j2-1)*pnum(1)+j1) = aa;
end
end
else
for n = 1:length(N)
j2 = floor((N(n)-1)/pnum(1))+1;
j1 = N(n) - pnum(1)*(j2-1);
aa = a(round(s(1)+(j1-1)*d(1)):round(s(1)+(j1-1)*d(1))+rsize(1)-1, ...
round(s(2)+(j2-1)*d(2)):round(s(2)+(j2-1)*d(2))+rsize(2)-1);
patches(:,:,n) = aa;
end
end
elseif strcmp(option,'rand')
locs = rand(pnum,2);
if ~isempty(N)
locs = locs(N,2);
end
patches = feval(mfilename,a,psize,locs,option);
elseif strcmp(option,'user')
locs = pnum;
if ~isempty(N)
locs = locs(N,:);
end
pnum = size(locs,1);
patches = zeros(rsize(1),rsize(2),pnum);
if all(locs(:) <= 1) % positions given as relative coordinates
locs = locs.*repmat([asize(1)-psize(1),asize(2)-psize(2)],pnum,1);
locs = locs + repmat([0.5 0.5],pnum,1);
end
border = max(ceil(rsize/2));
a = bord(a,NaN,border); % create mirror border to avoid problems (takes time!!)
locs = locs + border;
for j = 1:pnum
s = round(locs(j,:)-psize/2);
patches(:,:,j) = a(s(1):s(1)+rsize(1)-1,s(2):s(2)+rsize(2)-1);
end
end
b = patches;
end
return
|
github
|
jacksky64/imageProcessing-master
|
pca.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/pca.m
| 1,888 |
utf_8
|
4f05b0416c32e4724340e266115a23e8
|
%PCA Principal component analysis (PCA or MCA on overall covariance matrix)
%
% [W,FRAC] = PCA(A,N)
% [W,N] = PCA(A,FRAC)
%
% INPUT
% A Dataset
% N or FRAC Number of dimensions (>= 1) or fraction of variance (< 1)
% to retain; if > 0, perform PCA; otherwise MCA. Default: N = inf.
%
% OUTPUT
% W Affine PCA mapping
% FRAC or N Fraction of variance or number of dimensions retained.
%
% DESCRIPTION
% This routine performs a principal component analysis (PCA) or minor
% component analysis (MCA) on the overall covariance matrix (weighted
% by the class prior probabilities). It finds a rotation of the dataset A to
% an N-dimensional linear subspace such that at least (for PCA) or at most
% (for MCA) a fraction FRAC of the total variance is preserved.
%
% PCA is applied when N (or FRAC) >= 0; MCA when N (or FRAC) < 0. If N is
% given (abs(N) >= 1), FRAC is optimised. If FRAC is given (abs(FRAC) < 1),
% N is optimised.
%
% Objects in a new dataset B can be mapped by B*W, W*B or by A*PCA([],N)*B.
% Default (N = inf): the features are decorrelated and ordered, but no
% feature reduction is performed.
%
% ALTERNATIVE
%
% V = PCA(A,0)
%
% Returns the cumulative fraction of the explained variance. V(N) is the
% cumulative fraction of the explained variance by using N eigenvectors.
%
% Use KLM for a principal component analysis on the mean class covariance.
% Use FISHERM for optimizing the linear class separability (LDA).
%
% SEE ALSO
% MAPPINGS, DATASETS, PCLDC, KLLDC, KLM, FISHERM
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: pca.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function [w,truefrac] = pca (varargin)
prtrace(mfilename);
[w,truefrac] = pcaklm(mfilename,varargin{:});
return
|
github
|
jacksky64/imageProcessing-master
|
im_threshold.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_threshold.m
| 2,565 |
utf_8
|
c0695bb34cf81afd570191ccd7a06f38
|
%IM_THRESHOLD Threshold images stored in a dataset (DIP_Image)
%
% B = IM_THRESHOLD(A,TYPE,PAR,INV)
% B = A*IM_THRESHOLD([],TYPE,PAR,INV)
%
% INPUT
% A Dataset with object images (possibly multi-band)
% TYPE Type of procedure, see below
% PAR Related parameter
% INV If INV = 1, result inverted, default INV = 0.
%
% OUTPUT
% B Dataset with thresholded images
%
% DESCRIPTION
% The following procedures are supported (TYPE)
% 'isodata': Thresholding using the Isodata algorithm,
% for more options (mask image, several thresholds)
% see dip_isodatathreshold. (default)
% 'triangle': Thresholding using chord method
% (a.k.a. skewed bi-modality, maximum distance to triangle)
% by Zack, Rogers and Latt (1973).
% 'background': Thresholding using unimodal background-symmetry method.
% 'fixed': Thresholding at a fixed value.
% 'double': Thresholding between two fixed values.
% 'volume': Thresholding to obtain a given volume fraction.
% 'hysteresis': From the binary image (in>low) only those regions are
% selected for which at least one pixel is (in>high)
%
% The following parameters are related to these procedures (PAR):
% ('background'): Distance to the peak where we cut-off, in
% terms of the half-width at half the maximum.
% Inf selects the default value, which is 2.
% ('fixed'): Threshold value. Inf means halfway between
% minimum and maximum value.
% ('double'): Two threshold values. Inf means min+[1/3,2/3]*(max-min).
% ('volume'): Parameter = the volume fraction (Inf means 0.5)
% ('hysteresis'):Two values: low, high (see above)
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE, THRESHOLD
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_threshold(a,type,par,inv)
prtrace(mfilename);
if nargin < 4 | isempty(inv), inv = 0; end
if nargin < 3 | isempty(par), par = inf; end
if nargin < 2 | isempty(type), type = 'isodata'; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{type,par,inv});
b = setname(b,'Image threshold');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,{type,par,inv});
b = setfeatsize(b,getfeatsize(a));
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = 1.0*dip_image(a);
b = threshold(a,type,par);
if inv
b = 1-b;
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
nmc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nmc.m
| 2,128 |
utf_8
|
d6c35ba10f1a2d77641d5948b832dd6f
|
%NMC Nearest Mean Classifier
%
% W = NMC(A)
% W = A*NMC
%
% INPUT
% A Dataset
%
% OUTPUT
% W Nearest Mean Classifier
%
% DESCRIPTION
% Computation of the nearest mean classifier between the classes in the
% dataset A. The use of soft labels is supported. Prior probabilities are
% not used.
%
% The difference with NMSC is that NMSC is based on an assumption of normal
% distributions and thereby automatically scales the features and is
% sensitive to class priors. NMC is a plain nearest mean classifiers that
% is feature scaling sensitive and unsensitive to class priors.
%
% SEE ALSO
% DATASETS, MAPPINGS, NMSC, LDC, FISHERC, QDC, UDC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: nmc.m,v 1.14 2009/12/09 15:49:54 duin Exp $
function W = nmc(a)
prtrace(mfilename);
if nargin < 1 | isempty(a)
W = mapping(mfilename);
W = setname(W,'Nearest Mean');
return
end
islabtype(a,'crisp','soft');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
[m,k,c] = getsize(a);
if isdatafile(a), a = setfeatsize(a,k); end
if c == 2 % 2-class case: store linear classifier
u = meancov(a);
u1 = +u(1,:);
u2 = +u(2,:);
R = [u1-u2]';
offset =(u2*u2' - u1*u1')/2;
W = affine([R -R],[offset -offset],a,getlablist(a));
W = cnormc(W,a);
W = setname(W,'Nearest Mean');
else
if all(classsizes(a) > 1)
a = setprior(a,0); % NMC should be independent of priors: make them equal
p = getprior(a);
U = zeros(c,k);
V = zeros(c,k);
s = sprintf('NMC: Processing %i classes: ',c);
prwaitbar(c,s);
for j=1:c
prwaitbar(c,j,[s int2str(j)]);
b = seldat(a,j);
[v,u] = var(b);
U(j,:) = +u;
V(j,:) = +v;
end
prwaitbar(0);
%G = mean(V'*p') * eye(k);
G = mean(V(:));
w.mean = +U;
w.cov = G;
w.prior =p;
W = normal_map(w,getlablist(a),k,c);
W = setname(W,'Nearest Mean');
W = setcost(W,a);
else
u = meancov(a);
W = knnc(u,1);
W = setname(W,'Nearest Mean');
end
end
W = setcost(W,a);
return
|
github
|
jacksky64/imageProcessing-master
|
gendats.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendats.m
| 2,033 |
utf_8
|
5ec6c34e8c8a19bcc26bfd04944c5b6d
|
%GENDATS Generation of a simple classification problem of 2 Gaussian classes
%
% A = GENDATS (N,K,D,LABTYPE)
%
% INPUT
% N Dataset size, or 2-element array of class sizes (default: [50 50]).
% K Dimensionality of the dataset to be generated (default: 2).
% D Distance between class means in the first dimension (default: 1).
% LABTYPE Label type to generate, 'crisp' or 'soft' (default: 'crisp').
%
% OUTPUT
% A Dataset.
%
% DESCRIPTION
% Generation of a K-dimensional 2-class dataset A of N objects. Both classes
% are Gaussian distributed with identity matrix as covariance matrix. Their
% means are on a distance D. Class priors are P(1) = P(2) = 0.5.
%
% If N is a vector of sizes, exactly N(I) objects are generated for class I,
% I = 1,2.
%
% LABTYPE defines the desired label type: 'crisp' or 'soft'. In the latter
% case true posterior probabilities are set for the labels.
%
% SEE ALSO
% DATASETS, PRDATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: gendats.m,v 1.3 2009/01/27 13:01:42 duin Exp $
function A = gendats (N,k,d,labtype)
prtrace(mfilename);
if (nargin < 1),
prwarning(2,'class sizes not specified, assuming [50 50]');
N = [50 50];
end
if (nargin < 2),
prwarning(2,'dimensionality not specified, assuming 2');
k = 2;
end
if (nargin < 3),
prwarning(2,'class mean distance not specified, assuming 1');
d = 2;
end
if (nargin < 4),
prwarning(2,'label type not specified, assuming "crisp"');
labtype = 'crisp';
end
% Set equal priors and generate random class sizes according to these.
p = [0.5 0.5]; N = genclass(N,p);
% Unit covariance matrices, zero mean except for distance D in first dim.
GA = eye(k); GB = eye(k);
ma = zeros(1,k); mb = zeros(1,k); mb(1) = d;
U = dataset([ma;mb],[1 2]');
U = setprior(U,p);
% Create dataset.
A = gendatgauss(N,U,cat(3,GA,GB),labtype);
A = setname(A,'Simple Problem');
return
|
github
|
jacksky64/imageProcessing-master
|
ffnc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/ffnc.m
| 9,651 |
utf_8
|
810924cee56981dbe41a86706eeed34c
|
%FFNC Feed-forward neural net classifier back-end
%
% [W,HIST] = FFNC (ALG,A,UNITS,ITER,W_INI,T,FID)
%
% INPUT
% ALG Training algorithm: 'bpxnc' for back-propagation (default), 'lmnc'
% for Levenberg-Marquardt
% A Training dataset
% UNITS Array indicating number of units in each hidden layer (default: [5])
% ITER Number of iterations to train (default: inf)
% W_INI Weight initialisation network mapping (default: [], meaning
% initialisation by Matlab's neural network toolbox)
% T Tuning set (default: [], meaning use A)
% FID File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% W Trained feed-forward neural network mapping
% HIST Progress report (see below)
%
% DESCRIPTION
% This function should not be called directly, but through one of its
% front-ends, BPXNC or LMNC. Uses the Mathworks' Neural Network toolbox.
%
% SEE ALSO
% MAPPINGS, DATASETS, BPXNC, LMNC, NEURC, RNNC, RBNC, PRPROGRESS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: ffnc.m,v 1.10 2009/07/26 18:43:12 duin Exp $
function [w,hist] = ffnc(alg,a,units,max_iter,w_ini,tt,fid)
prtrace(mfilename);
% Settings for the different training algorithms.
if exist('nnet') ~= 7
error('Neural network toolbox not found')
end
if (strcmp(alg,'bpxnc'))
mapname = 'BP Neural Classf';
elseif (strcmp(alg,'lmnc'))
mapname = 'LM Neural Classf';
else
error('illegal training algorithm specified');
end;
% Check arguments
if (nargin < 7), fid = []; end;
if (nargin < 6) | (isempty(tt))
prwarning(2,'no tuning set supplied, using training set for tuning (risk of overfit)');
if (nargin < 2), t = []; else, t = a; end;
tt = []; % preserve input for regopt calls
else
t = tt;
end
if (nargin < 5) | (isempty(w_ini))
prwarning(3,'no initialisation supplied, using Nguyen-Widrow random initialisation');
w_ini = [];
end
if (nargin < 4) | (isempty(max_iter))
prwarning(3,'no maximum number of iterations supplied, assuming infinite');
max_iter = inf;
end
if (nargin < 3) | (isempty(units))
prwarning(2,'no network architecture specified, assuming one hidden layer of 5 units');
units = 5;
end
if (nargin < 2) | (isempty(a))
w = mapping(alg,{units,max_iter,w_ini,t,fid});
w = setname(w,mapname);
hist = [];
return
end
a = setprior(a,getprior(a));
t = setprior(a,getprior(t));
if isnan(units) % optimize complexity parameter: number of neurons
defs = {5,[],[],[],[]};
parmin_max = [1,30;0,0;0,0;0,0;0,0];
[w,hist] = regoptc(a,alg,{units,max_iter,w_ini,tt,fid},defs,[1],parmin_max,testc([],'soft'),0);
return
end
% Training target values.
prwarning (4, 'using training targets 0.9/0.1');
target_high = 0.9;
target_low = 0.1;
% Check whether the dataset is valid.
islabtype(a,'crisp');
isvaldfile(a,1,2); % At least 1 object per class, 2 classes
a = testdatasize(a);
t = testdatasize(t);
iscomdset(a,t); % Check whether training and tuning set match
%a = setprior(a,getprior(a));
%t = setprior(a,getprior(t));
[m,k,c] = getsize(a);
lablist = getlablist(a);
% Standard training parameters.
disp_freq = inf;
err_goal = 0.02/m; % Mean-squared error goal, stop if reached
trnsf_fn = 'logsig'; % Transfer function
perf_fn = 'mse'; % Performance function
% Settings for the different training algorithms.
tp.show = disp_freq;
tp.time = inf;
tp.goal = err_goal;
if (strcmp(alg,'bpxnc'))
trnalg = 'traingdx';
lrnalg = 'learngdm';
burnin = 500; % Never stop training before this many iters
tp.epochs = min(50,max_iter); % Iteration unit
tp.lr = 0.01; % BP, initial value for adaptive learning rate
tp.lr_inc = 1.05; % BP, multiplier for increasing learning rate
tp.lr_dec = 0.7; % BP, multiplier for decreasing learning rate
tp.mc = 0.95; % BP, momentum
tp.max_perf_inc = 1.04; % BP, error ratio
tp.min_grad = 1e-6; % BP, minimum performance gradient
tp.max_fail = 5; % BP, maximum validation failures
speed = 10000; % waitbar speed
elseif (strcmp(alg,'lmnc'))
trnalg = 'trainlm';
lrnalg = 'learngdm';
burnin = 50; % Never stop training before this many iters
tp.epochs = min(1,max_iter); % Iteration unit
tp.mem_reduc = 1; % Trade-off between memory & speed
tp.max_fail = 1; % LM, maximum validation failures
tp.min_grad = 1e-6; % LM, minimum gradient, stop if reached
tp.mu = 0.001; % LM, initial value for adaptive learning rate
tp.mu_inc = 10; % LM, multiplier for increasing learning rate
tp.mu_dec = 0.1; % LM, multiplier for decreasing learning rate
tp.mu_max = 1e10; % LM, maximum learning rate
speed = 100; % waitbar speed
end;
% Scale each feature to the range [0,1].
prwarning(3,'scaling such that training set features have range [0,1]');
ws = scalem(a,'domain'); a_scaled = a*ws; t_scaled = t*ws;
% Set number of network outputs: 1 for 2 classes, c for c > 2 classes.
if (c == 2), cout = 1; else cout = c; end
% Create target matrix: row C contains a high value at position C,
% the correct class, and a low one for the incorrect ones (place coding).
if (cout > 1)
target = target_low * ones(c,c) + (target_high - target_low) * eye(c);
else
target = [target_high; target_low];
end
% Create the target arrays for both datasets.
target_a = target(getnlab(a),:)';
target_t = target(getnlab(t),:)';
% Create the network layout: K inputs, N(:) hidden units, COUT outputs.
numlayers = length(units)+1; numunits = [k,units(:)',cout];
transfer_fn = cellstr(char(ones(numlayers,1)*trnsf_fn));
% Create network and set training parameters. The network is initialised
% by the Nguyen-Widrow rule by default.
warning('OFF','NNET:Obsolete')
net = newff(ones(numunits(1),1)*[0 1],numunits(2:end),...
transfer_fn,trnalg,lrnalg,perf_fn);
net.trainParam = tp;
% If an initial network is specified, use its weights and biases.
if (~isempty(w_ini))
% Use given initialisation.
[data,lab,type_w] = get(w_ini,'data','labels','mapping_file');
if (strcmp(type_w,'sequential'))
a_scaled = a*data{1}; t_scaled = t*data{1}; ws = data{1};
[data,lab,type_w] = get(data{2},'data','labels','mapping_file');
end
% Check whether the mapping's dimensions are the same as the network's.
[kw,cw] = size(w_ini); net_ini = data{1};
if (~strcmp(type_w,'neurc')) | (kw ~= k) | (cw ~= c) | ...
(net.numInputs ~= net_ini.numInputs) | ...
(net.numLayers ~= net_ini.numLayers) | ...
(net.numOutputs ~= net_ini.numOutputs) | ...
any(net.biasConnect ~= net_ini.biasConnect) | ...
any(net.inputConnect ~= net_ini.inputConnect) | ...
any(net.outputConnect ~= net_ini.outputConnect)
error('incorrect size initialisation network supplied')
end
% Check whether the initialisation network was trained on the same data.
[dummy1,nlab,dummy2] = renumlab(lablist,lab);
if (max(nlab) > c)
error('initialisation network should be trained on same classes')
end
net.IW = net_ini.IW; net.LW = net_ini.LW; net.b = net_ini.b;
end
% Initialize loop
opt_err = inf; opt_iter = inf; opt_net = net;
iter = 0; this_iter = 1; hist = [];
% Loop while
% - training has not gone on for longer than 50 iterations or 2 times the
% number of iterations for which the error was minimal, and
% - the number of iterations does not exceed the maximum
% - the actual training function still performed some iterations
prprogress(fid,'%s: neural net, %i units: \n',alg,units);
prprogress(fid,'%i %5.3f %5.3f\n',0,1,1);
s = sprintf('%s: neural net, %i units',alg,units);
prwaitbar(100,s);
while ((iter <= 2*opt_iter) | (iter < burnin)) & ...
(iter < max_iter) & (this_iter > 0) & (opt_err > 0)
prwaitbar(100,100-100*exp(-iter/speed));
% Call TRAIN, from Matlab's NN toolbox.
prwarning(4,'[%d] calling NNETs train', iter);
%net.trainParam.mu = min(net.trainParam.mu_max*0.9999,net.trainParam.mu);
net.trainParam.showWindow = 0;
net.trainParam.showCommandLine = 0;
[net,tr] = train(net,+a_scaled',target_a);
this_iter = length(tr.epoch)-1; iter = iter + this_iter;
% Copy current learning rate as the one to start with for the next time.
if (strcmp(alg,'bpxnc'))
net.trainParam.lr = tr.lr(end);
else
net.trainParam.mu = tr.mu(end);
end;
% Map train and tuning set.
w = mapping('neurc','trained',{net},lablist,k,c);
w = setname(w,mapname);
% Calculate mean squared errors (MSE).
out_a = a_scaled*w; out_t = t_scaled*w;
mse_a = mean(mean(((out_a(:,1:cout))-target_a').^2,1));
mse_t = mean(mean(((out_t(:,1:cout))-target_t').^2,1));
% Calculate classification errors.
e_a = testc(a_scaled,w); e_t = testc(t_scaled,w);
% If this error is minimal, store the iteration number and weights.
if (e_t < opt_err)
opt_err = e_t; opt_iter = iter; opt_net = net;
end
w1 = cell2mat(net.IW); w1 = w1(:);
%w2 = cell2mat(net.LW'); bugfix, doesnot work for multilayer networks
%w2 = w2(:);
netLW = net.LW(:);
w2 = [];
for j=1: length(netLW)
ww = netLW{j};
w2 = [w2; ww(:)];
end
hist = [hist; iter e_a e_t mse_a mse_t ...
mean([w1; w2].^2)];
prprogress(fid,'%i %5.3f %5.3f\n',iter,e_t,opt_err);
end
prwaitbar(0);
% Create mapping.
w = ws*mapping('neurc','trained',{opt_net},lablist,k,c);
w = setname(w,mapname);
w = setcost(w,a);
return
|
github
|
jacksky64/imageProcessing-master
|
im_resize.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_resize.m
| 3,822 |
utf_8
|
9b9aa3cc9eb40cb875da06de9efcddb7
|
%IM_RESIZE Mapping for resizing object images in datasets and datafiles
%
% B = IM_RESIZE(A,SIZE,METHOD)
% B = A*IM_RESIZE([],SIZE,METHOD)
%
% INPUT
% A Dataset or datafile
% SIZE Desired size
% METHOD Method, see IMRESIZE
%
% OUTPUT
% B Dataset or datafile
%
% DESCRIPTION
% The objects stored as images in the dataset or datafile A are resized
% using the IMRESIZE command. Default METHOD is 'nearest' (nearest
% neighbor interpolation).
%
% A special method is 'preserve', which exactly copies the existing data,
% cuts it, or extends it with zeros as far as appropriate. In SIZE the
% desired output size has to be stored. Note that for proper use in
% PRTools third size parameter of multi-band images, e.g. 3 for RGB
% images, has to be supplied.
%
% In case SIZE is a scalar the default METHOD is 'preserve', which
% implies that the first SIZE samples are taken, which is useful if
% A is a 1-D signal. Otherwise the deafult METHOD is 'nearest'.
%
% SEE ALSO
% MAPPINGS, DATASETS, DATAFILES, IM2OBJ, DATA2IM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
%DXD 24-8-2007
% I rewrote a part of this function. Now there are default values
% given, a bug is removed, and the identation is correct again.
function b = im_resize(a,imsize,method,par)
if nargin < 4
par = [];
end
if nargin < 3
method = [];
end
if nargin < 2 | isempty(imsize)
imsize = [16 16];
end
if nargin < 1
a = [];
end
if isempty(method)
if length(imsize) == 1
method = 'preserve';
else
method = 'nearest';
end
end
if isempty(a)
b = mapping(mfilename,'fixed',{imsize,method});
b = setname(b,'im_resize');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,{imsize,method},imsize); % prepare execution image by image
else
b = double(a);
if strcmp(method,'preserve') | strcmp(method,'preserve_bottom') | ...
strcmp(method,'preserve_centre') | strcmp(method,'preserve_top')
% copy the image pixel by pixel into a larger or smaller image
sizeb = size(b); % original size
if length(imsize) == 1
imsize = [1 imsize];
end
if length(sizeb) == 3 & length(imsize) == 2
imsize(3) = sizeb(3);
end
if length(imsize) ~= length(sizeb)
error('Desired images size should have as many dimension as data')
end
sizec = min(imsize,sizeb); % size of part to be copied
subs = cell(1,length(sizec)); % store indices in cell array
[subs{:}] = ind2sub(sizec,[1:prod(sizec)]);
subsb = subs; subsc = subs; % cell arrays for original and result
switch method
case 'preserve_bottom'
delc = imsize-sizeb;
case 'preserve_centre'
delc = round((imsize-sizeb)/2);
case {'preserve_top','preserve'}
delc = zeros(1,length(imsize));
end
for j=1:length(delc) % indices for
if delc(j) > 0 % result
subsc{j} = subs{j} + delc(j);
elseif delc(j) < 0 % and original
subsb{j} = subs{j} - delc(j);
end
end
Lc = sub2ind(imsize,subsc{:}); % corresponding linear coordinates of result
Lb = sub2ind(sizeb,subsb{:}); % corresponding linear coordinates of original
c = zeros(imsize); % embed result in zeros
c(Lc) = b(Lb); % copy
b = c; % store result
else % resizing the image using Matlab's imresize
if length(imsize) > 1
b = imresize(b,imsize(1:2),method);
elseif imsize > 1 & round(imsize) == imsize
b = imresize(a,[imsize imsize],method);
else
[m,n] = size(a);
b = imresize(a,round(imsize*[m,n]),method);
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
remoutl.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/remoutl.m
| 1,593 |
utf_8
|
30de9687b8f002b3fc42aa90be9ee9dd
|
%REMOUTL Remove outliers from a dataset
%
% B = REMOUTL(A,T,P)
% B = A*REMOUTL([],T,P)
%
% INPUT
% A Dataset
% T Threshold for outlier detection (default 3)
% P Fraction of distances passing T (default 0.10)
%
% OUTPUT
% B Dataset
%
% DESCRIPTION
% Outliers in A are removed, other objects are copied to B. Class by class
% a distance matrix is constructed and objects are removed that have a fraction
% P of their distances larger than the average distance in the class + T times
% the standard deviation of the within-class distances. This routine works
% also on unlabeled datasets. In partially labeled datasets the unlabeled
% objects are neglected.
function a = remoutl(a,t,p);
if nargin < 3, t = []; end
if nargin < 2, p = []; end
if nargin < 1 | isempty(a)
a = mapping(mfilename,'fixed',{t,p});
a = setname(a,'rem_outliers');
return
end
a = testdatasize(a);
c = getsize(a,3);
if c == 0
d = sqrt(distm(+a));
J = findoutd(d,t,p);
a(J,:) = [];
else
R = [];
for j=1:c
L = findnlab(a,j);
d = sqrt(distm(seldat(a,j)));
J = findoutd(d,t,p);
R = [R;L(J)];
end
a(R,:) = [];
end
%FINDOUTD Detect outliers in distance matrix
%
% J = FINDOUTD(D,T,P)
%
% Find the indices of the objects in the dissimilarity representation D
% that have a fraction P (default P = 0.10) of their distances larger than
% mean(D(:)) + T * std(D), default T = 3.
function J = findoutd(d,t,p);
if nargin < 3 | isempty(p), p = 0.10; end
if nargin < 2 | isempty(t), t = 3; end
x = +d;
x = x(:);
L = find(x~=0);
x = x(L);
s = mean(x) + t * std(x);
J = find(sum(+d > s,2) > p*size(d,2));
|
github
|
jacksky64/imageProcessing-master
|
histm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/histm.m
| 4,184 |
utf_8
|
aa606d4c44c644bd3466cbf920b12c6a
|
%HISTM Histogramming: mapping of dataset (datafile) to histogram
%
% W = HISTM(A,N)
% W = A*HISTM([],N)
% C = B*W
%
% C = HISTM(B,X)
% C = B*HISTM([],X)
%
%
%
% INPUT
% A Dataset or datafile for defining histogram bins (training)
% N Scalar defining number of histogram bins (default 10)
%
% B Dataset or datafile to be transformed into a histogram with
% predifined bins.
% X User defined histogram bins (centers)
%
% OUTPUT
% C Dataset or datafile with histogram bin frequencies
%
% DESCRIPTION
% For every object in the dataset B the set of feature values is mapped
% into a histogram, specifying for each bin the number of features having a
% value as specified for that bin. This is particular useful if the objects
% are images and the features are pixels. In that case for every image a
% histogram is found.
%
% The dataset A may be used to find the proper histogram bins. In that case
% histograms with N bins are constructed between the minimum and maximum
% values over all objects in A.
%
% Formally HISTM([],N) is an untrained mapping, to be trained by A as the
% dataset (datafile) A is used to determine the histogram bin centers.
% In case the bins are given like in HISTM(B,X) then we have a trained mapping.
% Consequently, if A is a datafile then in C = A*HISTM(A,10) all objects in
% A are processed twice. Once for determining the bin positions and once for
% filling them. If appropriate a command like C = A*HISTM(A(1,:),10) is
% thereby significantly faster.
%
% SEE ALSO
% DATASETS, DATAFILES, MAPPINGS, HIST
function w = histm(a,bins)
fixed = 0;
if nargin < 2, bins = 10; end
if nargin < 1, a = []; end
if isdouble(bins) & ~is_scalar(bins)
fixed = 1;
end
if ismapping(bins)
bins = getdata(bins); %DXD: I don't know how to solve it
fixed = 1;
end
mapname = 'histogramming';
if fixed % fixed histograms
if isempty(a)
%w = mapping(mfilename,'fixed',bins,bins(:),0,length(bins));
%DXD make it a trained mapping, you know the output size
% Unfortunately, you don't really know, because for color
% images you get a histogram *per* color band. Therefore I
% decided not to set the feature labels.
w = mapping(mfilename,'trained',bins,[],0,0); % size_out is unknown
% as it depends on the number of bands
w = setname(w,mapname);
else
n = getfeatsize(a,3);
if isdatafile(a)
%w = addpostproc(a,histm,length(bins)*n);
w = addpostproc(a,histm([],bins));
else
[m,k] = size(a);
fsize = getfeatsize(a);
h = zeros(m,length(bins),n);
for i=1:m
im = reshape(+a(i,:),fsize);
for j=1:n
imj = im(:,:,j);
hh = hist(imj(:),length(bins));
h(i,:,j) = hh;
end
end
h = reshape(h,m,length(bins)*n);
w = setdat(a,h);
end
end
else % adjustable histograms
if isempty(a) % defining
w = mapping(mfilename,'untrained',bins);
w = setname(w,mapname);
elseif ~ismapping(bins) % training
if bins < 3
error('Number of histogram bins should be larger than 2')
end
bins = bins - 2; % room for end bins
if isdatafile(a) % oeps! training from datafile
next = 1; % we just find minimum and maximum
xmin = inf; % of all feature values in all datafiles
xmax = -inf;
while next > 0
[b,next] = readdatafile(a,next);
b = +b;
xmin = min(min(b(:)),xmin);
xmax = max(max(b(:)),xmax);
end
binsize = (xmax-xmin)/bins; % and compute the bins
X = [xmin+binsize/2:binsize:xmax-binsize/2]';
n = bins;
else
[N,X] = hist(+a,bins);
n = size(N,1);
end
X(1) = X(1)-10*eps; % forces all objects inside edges
X = [2*X(1)-X(2) ; X ; 2*X(end)-X(end-1)];
outsize = getfeatsize(a,3)*(n+2);
w = mapping(mfilename,'trained',X,[1:outsize]',getfeatsize(a),outsize);
w = setname(w,mapname);
else % execution, bins is a mapping
w = feval(mfilename,a,getdata(bins)); % use fixed mapping
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
costm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/costm.m
| 3,037 |
utf_8
|
8d9480389c20643eb572a49a15806a5c
|
%COSTM Cost mapping, classification using costs
%
% Y = COSTM(X,C,LABLIST)
% W = COSTM([],C,LABLIST)
%
% DESCRIPTION
% Maps the classifier output X (assumed to be posterior probability
% estimates) to the cost-outputs, defined by the cost-matrix C:
%
% C(i,j) = cost of misclassifying an object from class i as class j.
%
% Default C is the cost matrix stored in the dataset X.
% The order of the classes is defined by LABLIST. When no lablist is
% given, the order as given by GETFEATLAB(X) is assumed.
% In order to apply this mapping, it is assumed that the dataset X
% represents posterior class probabilities (i.e. normalized by
% classc).
%
% EXAMPLE
% x = gendatb(100);
% w1 = x*ldc; % standard classifier
% C = [0 2; 1 0]; % new cost matrix
% w2 = w1*classc*costm([],C); % classifier using this cost-matrix
%
% SEE ALSO
% MAPPINGS, CLASSC, TESTD, TESTCOST, SETCOST
% Copyright: D.M.J. Tax, R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function w = costm(a,C,lablist)
prtrace(mfilename);
% costm is implemented as a trained mapping to enable proper handling
% of constructs like W = fisherc(train)*costm([],C,Clab); test*W;
if nargin < 3, lablist = []; end
if nargin < 2, C = []; end
[s_in,s_out] = size(C);
if nargin < 1 | isempty(a)
w = mapping(mfilename,'combiner',{C,lablist});
w = setname(w,'Mis-classification-cost');
return
end
if ismapping(a) % we do something like w*costm()
if isempty(lablist)
lablist = getlabels(a);
end
if ~isempty(C) & ~isempty(lablist)
% match the labels with that of the previous mapping
[C,lablist] = matchcost(a.labels,C,lablist);
end
% and now we have a trained mapping:
w = mapping(mfilename,'trained',{a,C,lablist},lablist,size(a,1),s_out);
elseif isdataset(a) & ismapping(C)
% we deal now with d*costm()
w = feval(mfilename, a*C.data{1}, C.data{2}, C.data{3});
elseif isdataset(a) & ~ismapping(C)
% the case that d*costm([],C,lablist)
if ~isempty(C) % store in dataset for standard error checking handling
% I doubt whether it is really the right thing to do
% as it may disturb a different labellingsystem in case
% we are dealing with a testset.
a = setcost(a,C,lablist);
end
C = a.cost; % retrieve from dataset
if isempty(C) % still empty, no costs
w = a;
else
% Get the data size
d = size(a,2);
if ( (size(C,1) ~= d) | (size(C,2) < d) )
error('Cost matrix has wrong size');
end
% Map the dataset using the costs:
w = a*C;
% Now we have a problem: PRTools expects that the estimated class
% has the highest output, and here we have calculated the cost
% (which should be low!)
% Thus we patch:
w = -w;
%w = setfeatlab(w,getfeatlab(a));
if isempty(lablist)
lablist = getfeatlab(a);
end
w = setfeatlab(w,lablist);
end
else
error('Input should be mapping or dataset');
end
return
|
github
|
jacksky64/imageProcessing-master
|
remclass.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/remclass.m
| 715 |
utf_8
|
015f458b4cb61086e8c3c94574db9072
|
%REMCLASS Remove small classes
%
% B = REMCLASS(A,N)
%
% INPUT
% A Dataset
% N Integer, maximum class size to be removed (optional; default 0)
%
% OUTPUT
% B Dataset
%
% DESCRIPTION
% Classes having N objects or less are removed. The corresponding objects
% are made unlabeled. Use SELDAT to remove unlabeled objects.
% In case of soft labeled objects the number of objects in A is compared
% with N. If it is smaller all object labels are removed (NaN).
%
% SEE ALSO
% SELDAT, GENDAT
function b = remclass(a,n)
prtrace(mfilename);
if nargin < 2, n = 0; end
N = classsizes(a);
J = find(N <= n);
L = findnlab(a,J);
b = setnlab(a,0,L);
b = setlablist(b);
return
|
github
|
jacksky64/imageProcessing-master
|
clevals.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/clevals.m
| 7,795 |
utf_8
|
78938416bcf29c02dc21b55343c11a1c
|
%CLEVALS Classifier evaluation (feature size/learning curve), bootstrap possible
%
% E = CLEVALS(A,CLASSF,FEATSIZE,TRAINSIZES,NREPS,T)
%
% INPUT
% A Training dataset
% CLASSF Classifier to evaluate
% FEATSIZE Vector of feature sizes
% (default: 1:K, where K is the number of features in A)
% TRAINSIZES Vector of class sizes, used to generate subsets of A
% (default [2,3,5,7,10,15,20,30,50,70,100])
% NREPS Number of repetitions (default 1)
% T Tuning set, or 'bootstrap' (default [], i.e. use remaining
% objects in A)
%
% OUTPUT
% E Error structure (see PLOTE)
%
% DESCRIPTION
% Generates at random, for all feature sizes defined in FEATSIZES or all
% class sizes defined in TRAINSIZES, training sets out of the dataset A and
% uses these for training the untrained classifier CLASSF. CLASSF may also
% be a cell array of untrained classifiers; in this case the routine will be
% run for all of them. The resulting trained classifiers are tested on all
% objects in A. This procedure is then repeated N times.
%
% Training set generation is done "with replacement" and such that for each
% run the larger training sets include the smaller ones and that for all
% classifiers the same training sets are used.
%
% If CLASSF is fully deterministic, this function uses the RAND random
% generator and thereby reproduces if its seed is reset (see RAND).
% If CLASSF uses RANDN, its seed may have to be set as well.
%
% EXAMPLES
% See PREX_CLEVAL.
%
% SEE ALSO
% MAPPINGS, DATASETS, CLEVALB, TESTC, PLOTE
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: clevals.m,v 1.4 2008/07/03 09:05:50 duin Exp $
function e = clevals(a,classf,featsizes,learnsizes,nreps,t,fid)
prtrace(mfilename);
prwaitbar
% use of fid is outdated
if (nargin < 6)
prwarning(2,'no tuning set supplied, bootstrapping');
t = [];
end;
if (nargin < 5)
prwarning(2,'number of repetitions not specified, assuming NREPS = 1');
nreps = 1;
end;
% If a single mapping is given, convert it to a 1 x 1 cell array.
if (ismapping(classf)), classf = {classf}; end
% Correct for old argument order.
if (isdataset(classf)) & (ismapping(a))
tmp = a; a = classf; classf = {tmp};
end
if (isdataset(classf)) & (iscell(a)) & (ismapping(a{1}))
tmp = a; a = classf; classf = tmp;
end
if ~iscell(classf), classf = {classf}; end
% Assert that all is right.
isdataset(a); ismapping(classf{1});
% Remove requested class sizes that are larger than the size of the
% smallest class.
mc = classsizes(a); [m,k,c] = getsize(a);
% Defaults for size arrays.
if (nargin < 4)
prwarning(2,'vector of training set class sizes not specified, assuming [2,3,5,7,10,15,20,30,50,70,100]');
learnsizes = [2,3,5,7,10,15,20,30,50,70,100];
end;
if (nargin < 3)
prwarning(2,'vector of feature sizes not specified, assuming K');
featsizes = k;
end;
learncurve = 0; featcurve = 0;
if (isempty(featsizes)) % Learning curve.
toolarge = find(learnsizes >= min(mc));
if (~isempty(toolarge))
prwarning(2,['training set class sizes ' num2str(learnsizes(toolarge)) ...
' larger than the minimal class size in A; removed them']);
learnsizes(toolarge) = [];
end
learnsizes = learnsizes(:)';
featsizes = k;
sizes = learnsizes;
learncurve = 1;
else % Feature size curve.
toolarge = find(featsizes > k);
if (~isempty(toolarge))
prwarning(2,['feature sizes ' num2str(featsizes(toolarge)) ...
' larger than number of features in A; removed them']);
featsizes(toolarge) = [];
end
if (max(size(learnsizes)) > 1)
error('For a feature curve, specify a scalar LEARNSIZE.');
end;
featsizes = featsizes(:)';
sizes = featsizes;
featcurve = 1;
end;
% Fill the error structure.
nw = length(classf(:));
datname = getname(a);
e.error = zeros(nw,length(sizes));
e.std = zeros(nw,length(sizes));
e.xvalues = sizes(:)';
e.n = nreps;
e.names = [];
if (nreps > 1)
e.ylabel= ['Averaged error (' num2str(nreps) ' experiments)'];
elseif (nreps == 1)
e.ylabel = 'Error';
else
error('Number of repetitions NREPS should be >= 1.');
end;
if (~isempty(datname))
if (isempty(t))
e.title = ['Bootstrapped learning curve on ' datname];
else
e.title = ['Learning curve on ' datname];
end
end;
if (learncurve)
e.xlabel = 'Training set size';
else
e.xlabel = 'Feature size';
end;
if (sizes(end)/sizes(1) > 20)
e.plot = 'semilogx'; % If range too large, use a log-plot for X.
end
% Report progress.
s1 = sprintf('clevals: %i classifiers: ',nw);
prwaitbar(nw,s1);
% Store the seed, to reset the random generator later for different
% classifiers.
seed = rand('state');
% Loop over all classifiers (with index WI).
for wi = 1:nw
% Assert that CLASSF{WI} is an untrained mapping.
isuntrained(classf{wi});
name = getname(classf{wi});
e.names = char(e.names,name);
prwaitbar(nw,wi,[s1 name]);
% E1 will contain the error estimates.
e1 = zeros(nreps,length(sizes));
% Take care that classifiers use same training set.
rand('state',seed); seed2 = seed;
% For N repetitions...
s2 = sprintf('clevals: %i repetitions: ',nreps);
prwaitbar(nreps,s2);
for i = 1:nreps
prwaitbar(nreps,i,[s2 int2str(i)]);
if (isempty(t))
% Bootstrap. Store the randomly permuted indices of samples of class
% CI to use in this training set in JR(CI,:).
JR = zeros(c,max(learnsizes));
for ci = 1:c
JC = findnlab(a,ci);
% Necessary for reproducable training sets: set the seed and store
% it after generation, so that next time we will use the previous one.
rand('state',seed2);
R = ceil(rand(1,max(learnsizes))*length(JC));
JR(ci,:) = JC(R)';
seed2 = rand('state');
end
t = a;
end
% Either the outer loop or the inner loop will be traversed just once,
% depending on whether we want to find a learning curve or feature
% size curve.
ii = 0;
nlearns = length(learnsizes);
s3 = sprintf('cleval: %i sizes: ',nlearns);
prwaitbar(nlearns,s3);
for li = 1:nlearns
nj = learnsizes(li);
prwaitbar(nlearns,li,[s3 int2str(li) ' (' int2str(nj) ')']);
nfeatsizes = length(featsizes);
s4 = sprintf('clevals: %i feature sizes: ',nfeatsizes);
prwaitbar(nfeatsizes,s4);
for fi = 1:nfeatsizes
prwaitbar(nfeatsizes,fi,[s4 int2str(fi) ' (' int2str(featsizes(fi)) ')']);
ii = ii + 1;
% Ja will contain the indices for this training set, Jt for
% the tuning set.
Ja = [];
for ci = 1:c
Ja = [Ja;JR(ci,1:nj)'];
end;
Jt = setdiff(1:m,Ja);
% Train classifier CLASSF{WI} on this training set and
% calculate error on tuning set.
if (learncurve)
e1(i,ii) = testc(a, ...
a(Ja,1:featsizes(fi))*classf{wi});
else
e1(i,ii) = testc(t(Jt,1:featsizes(fi)), ...
a(Ja,1:featsizes(fi))*classf{wi});
end;
end
prwaitbar(0);
end
prwaitbar(0);
end
prwaitbar(0);
% Calculate average error and standard deviation for this classifier
% (or set the latter to zero if there's been just 1 repetition).
e.error(wi,:) = mean(e1,1);
if (nreps == 1)
e.std(wi,:) = zeros(1,size(e.std,2));
else
e.std(wi,:) = std(e1)/sqrt(nreps);
end
end
prwaitbar(0);
% The first element is the empty string [], remove it.
e.names(1,:) = [];
return
|
github
|
jacksky64/imageProcessing-master
|
nlfisherm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nlfisherm.m
| 3,145 |
utf_8
|
72b443c040e6a245d4a94d5ca1cde5d6
|
%NLFISHERM Non-linear Fisher Mapping according to Marco Loog
%
% W = NLFISHERM(A,N)
%
% INPUT
% A Dataset
% N Number of dimensions (optional; default: MIN(K,C)-1, where
% K is the dimensionality of A and C is the number of classes)
%
% OUTPUT
% W Non-linear Fisher mapping
%
% DESCRIPTION
% Finds a mapping of the labeled dataset A to a N-dimensional linear
% subspace emphasizing the class separability for neighboring classes.
%
% REFERENCES
% 1. R. Duin, M. Loog and R. Haeb-Umbach, Multi-Class Linear Feature
% Extraction by Nonlinear PCA, in: ICPR15, 15th Int. Conf. on Pattern
% Recognition, vol.2, IEEE Computer Society Press, 2000, 398-401.
% 2. M. Loog, R.P.W. Duin and R. Haeb-Umbach, Multiclass Linear Dimension
% Reduction by Weighted Pairwise Fisher Criteria, IEEE Trans. on
% Pattern Analysis and Machine Intelligence, vol.23, no.7, 2001, 762-766.
%
% SEE ALSO
% MAPPINGS, DATASETS, FISHERM, KLM, PCA
% Copyright: M. Loog, R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: nlfisherm.m,v 1.4 2010/02/08 15:29:48 duin Exp $
function W = nlfisherm(a,n)
prtrace(mfilename);
if (nargin < 2)
n = [];
end
% No input data, an untrained mapping returned.
if (nargin < 1) | (isempty(a))
W = mapping('nlfisherm',n);
W = setname(W,'Non-linear Fisher mapping');
return;
end
islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 2 objects per class, 2 classes
a = testdatasize(a);
[m,k,c] = getsize(a);
prior = getprior(a);
a = setprior(a,prior);
if (isempty(n))
n = min(k,c)-1;
prwarning(4,'Dimensionality N not supplied, assuming MIN(K,C)-1.');
end
if (n >= m) | (n >= c)
error('Dataset too small or has too few classes for demanded output dimensionality.')
end
% Non-linear Fisher mapping is determined by the eigenvectors of CW^{-1}*CB,
% where CW is the within-scatter, understood as the averaged covariance
% matrix weighted by the prior probabilities, and CB is the between-scatter,
% modified in a nonlinear way.
% To simplify the computations, CW can be set to the identity matrix.
w = klms(a);
% A is changed such that CW = I and the mean of A is shifted to the origin.
b = a*w;
k = size(b,2);
u = +meancov(b);
d = +distm(u); % D is the Mahalanobis distance between the classes.
% Compute the weights E to be used in the modified between-scatter matrix G
% E should diminish the influence of large distances D.
e = 0.5*erf(sqrt(d)/(2*sqrt(2)));
G = zeros(k,k);
for j = 1:c
for i=j+1:c
% Marco-Loog Mapping
G = G + prior(i)*prior(j)*e(i,j)*(u(j,:)-u(i,:))'*(u(j,:)-u(i,:))/d(i,j);
G = (G + G')/2; % Avoid a numerical inaccuracy: cov. matrix should be symmetric!
end
end
% Perform the eigendecomposition of the modified between-scatter matrix.
[F,V] = preig(G);
[v,I] = sort(-diag(V));
I = I(1:n);
rot = F(:,I);
off = -mean(b*F(:,I));
% After non-linear transformations, NLFISHERM is stored as an affine (linear) map.
W = affine(rot,off,a);
W = setname(w*W,'Non-linear Fisher mapping');
return;
|
github
|
jacksky64/imageProcessing-master
|
mdsc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/mdsc.m
| 3,283 |
utf_8
|
5aeefec94fce41fbe831891e643a2f93
|
%MDSC Manhatten Dissimilarity Space Classification
%
% W = MDSC(A,R,CLASSF)
% W = A*FDSC([],R,CLASSF)
% D = X*W
%
% INPUT
% A Dateset used for training
% R Dataset used for representation
% or a fraction of A to be used for this.
% Default: R = A.
% CLASSF Classifier used in dissimilarity space
% Default LIBSVC([],[],100)
% X Test set.
%
% OUTPUT
% W Resulting, trained feature space classifier
% D Classification matrix
%
% DESCRIPTION
% This is a dissimilarity based classifier intended for a feature
% respresentation. The training set A is used to compute for every class
% its own eigenspace. All eigenvectors are used. A dissimilarity space is
% built by the Manhatten (L1, or Minkowsky-1 or city block) distances
% between training objects A or test objects X and the representation
% objects R after transformation (i.e. rotation) them to the eigenspace of
% the class of the particular represention object.
%
% Note that Euclidean distances are not affected by rotation, but Manhatten
% distances are.
%
% New objects in feature space can be classified by D = X*W or by
% D = MAP(X,W). Labels can be found by LAB = D*LABELD or LAB = LABELD(D).
%
% SEE ALSO
% DATASETS, MAPPINGS, FDSC
% Copyright: S.W. Kim, R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = mdsc(a,r,classf)
if nargin < 3 | isempty(classf), classf = libsvc([],[],100); end
if nargin < 2, r = []; end
if nargin < 1 | isempty(a)
w = mapping(mfilename,'untrained',{r,classf});
w = setname(w,'ManhattenDisSpaceC');
return
end
isvaldfile(a,2,2); % at least 2 objects per class, 2 classes
if isempty(r)
r = a; % default representation set is the training set
elseif is_scalar(r)
[r,a] = gendat(a,r); % or we take a random fraction
end
% Training set and representation set should belong to the same set of
% classes. Let us check that.
laba = getlablist(a);
labr = getlablist(r);
[nlab1,nlab2,lablist] = renumlab(laba,labr);
c = size(lablist,1);
if any([length(unique(nlab1)) length(unique(nlab2))] ~= c)
error('Training set and representation set should contain the same classes')
end
% We are now ready to compute the classifier. The set of class dependent
% rotations will be stored in a stacked set of mappings v.
v = cell(1,c);
for j=1:c % compute the mapping for every class
b = seldat(a,getclassi(a,lablist(j,:))); % training set of class j
[e,d] = preig(covm(b)); % its eigenvalue decomposition
u = affine(e); % the rotation, apply it to the represention
s = seldat(r,getclassi(r,lablist(j,:)))*u; % objects of the same class
v{j} = u*proxm(s,'m',1); % store the rotation and the proximity mapping
% to the rotated representation objects
end
v = stacked(v); % combine all mappings as a stacked mapping
d = a*v;
n = disnorm(d);
w = a*(v*n*classf); % apply it to the training set, compute the classifier
% and include the mapping for use by the test objects
w = setname(w,'ManhattenDisSpaceC');
return
|
github
|
jacksky64/imageProcessing-master
|
isuntrained.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isuntrained.m
| 746 |
utf_8
|
f722c42ff9acdb259cab4bf5896afa5a
|
%ISUNTRAINED Test on untrained mapping
%
% I = ISUNTRAINED(W)
% ISUNTRAINED(W)
%
% True if the mapping type of W is 'untrained' (see HELP MAPPINGS).
% If called without an output argument ISUNTRAINED generates
% an error if the mapping type of W is not 'untrained'.
% $Id: isuntrained.m,v 1.1 2009/03/18 16:12:41 duin Exp $
function i = isuntrained(w)
prtrace(mfilename,2);
if iscell(w)
i = strcmp(w{1}.mapping_type,'untrained');
for j=2:length(w)
if strcmp(w{j}.mapping_type,'untrained') ~= i
error('Cell array of classifiers cannot be partially trained')
end
end
else
i = strcmp(w.mapping_type,'untrained');
end
if (nargout == 0) & (i == 0)
error([newline '---- Untrained mapping expected ----'])
end
return
|
github
|
jacksky64/imageProcessing-master
|
rnnc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rnnc.m
| 2,817 |
utf_8
|
916bb7ca9fd194f6c83f71f944206b17
|
%RNNC Random Neural Net classifier
%
% W = RNNC(A,N,S)
%
% INPUT
% A Input dataset
% N Number of neurons in the hidden layer
% S Standard deviation of weights in an input layer (default: 1)
%
% OUTPUT
% W Trained Random Neural Net classifier
%
% DESCRIPTION
% W is a feed-forward neural net with one hidden layer of N sigmoid neurons.
% The input layer rescales the input features to unit variance; the hidden
% layer has normally distributed weights and biases with zero mean and
% standard deviation S. The output layer is trained by the dataset A.
% Default N is number of objects * 0.2, but not more than 100.
%
% If N and/or S is NaN they are optimised by REGOPTC.
%
% Uses the Mathworks' Neural Network toolbox.
%
% SEE ALSO
% MAPPINGS, DATASETS, LMNC, BPXNC, NEURC, RBNC
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: rnnc.m,v 1.4 2007/06/19 11:45:08 duin Exp $
function w = rnnc(a,n,s)
prtrace(mfilename);
if exist('nnet') ~= 7
error('Neural network toolbox not found')
end
mapname = 'Random Neural Net';
if (nargin < 3)
prwarning(3,'standard deviation of hidden layer weights not given, assuming 1');
s = 1;
end
if (nargin < 2)
n = [];
end
% No input arguments: return an untrained mapping.
if (nargin < 1) | (isempty(a))
w = mapping('rnnc',{n,s});
w = setname(w,mapname);
return
end
islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a);
[m,k,c] = getsize(a);
if isempty(n)
n = min(ceil(m/5),100);
prwarning(3,['no number of hidden units specified, assuming ' num2str(n)]);
end
if isnan(n) | isnan(s) % optimize complexity parameter: number of neurons, st. dev.
defs = {m/5,1};
parmin_max = [1,min(m,100);0.01,10];
w = regoptc(a,mfilename,{n,s},defs,[1,2],parmin_max,testc([],'soft'),[0,1]);
return
end
% The hidden layer scales the input to unit variance, then applies a
% random rotation and offset.
w_hidden = scalem(a,'variance');
w_hidden = w_hidden * cmapm(randn(n,k)*s,'rot');
w_hidden = w_hidden * cmapm(randn(1,n)*s,'shift');
% The output layer applies a FISHERC to the nonlinearly transformed output
% of the hidden layer.
w_output = w_hidden * sigm;
w_output = fisherc(a*w_output);
% Construct the network and insert the weights.
transfer_fn = { 'logsig','logsig','logsig' };
net = newff(ones(k,1)*[0 1],[n size(w_output,2)],transfer_fn,'traingdx','learngdm','mse');
net.IW{1,1} = w_hidden.data.rot'; net.b{1,1} = w_hidden.data.offset';
net.LW{2,1} = w_output.data.rot'; net.b{2,1} = w_output.data.offset';
w = mapping('neurc','trained',{net},getlabels(w_output),k,c);
w = setname(w,mapname);
w = setcost(w,a);
return
|
github
|
jacksky64/imageProcessing-master
|
fdsc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/fdsc.m
| 3,173 |
utf_8
|
cd9903c57175b348ec71705429713f3a
|
%FDSC Feature based Dissimilarity Space Classification
%
% W = FDSC(A,R,FEATMAP,TYPE,P,CLASSF)
% W = A*FDSC([],R,FEATMAP,TYPE,P,CLASSF)
% D = X*W
%
% INPUT
% A Dateset used for training
% R Dataset used for representation
% or a fraction of A to be used for this.
% Default: R = A.
% FEATMAP Preprocessing in feature space (e.g. SCALEM)
% Default: no preprocessing.
% TYPE Dissimilarity rule, see PROXM
% Default 'DISTANCE'.
% P Parameter for dissimilarity rule, see PROXM
% Default P = 1.
% CLASSF Classifier used in dissimilarity space
% Default LIBSVC([],[],100)
% X Test set
%
% OUTPUT
% W Resulting, trained feature space classifier
% D Classification matrix
%
% DESCRIPTION
% This routine builds a classifier in feature space based on a
% dissimilarity representation defined by the representation set R
% and the dissimilarities found by A*FEATMAP*PROXM(R*FEATMAP,TYPE,P).
% FEATMAP is a preprocessing in feature space, e.g. scaling
% (SCALEM([],'variance') or pre-whitening (KLMS).
%
% R can either be explicitely given, or by a fraction of A. In the
% latter case the part of A that is randomly generated to create the
% representation set R is excluded from the training set.
%
% New objects in feature space can be classified by D = B*W or by
% D = MAP(B,W). Labels can be found by LAB = D*LABELD or LAB = LABELD(D).
%
% EXAMPLE
% A = GENDATB([100 100]); % Training set of 200 objects
% R = GENDATB([10 10]); % Representation set of 20 objects
% W = FDSC(A,R); % Compute classifier
% SCATTERD(A); % Scatterplot of trainingset
% HOLD ON; SCATTERD(R,'ko'); % Add representation set to scatterplot
% PLOTC(W); % Plot classifier
%
% SEE ALSO
% DATASETS, MAPPINGS, SCALEM, KLMS, PROXM, LABELD, KERNELC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = fdsc(a,r,featmap,type,p,classf)
if nargin < 6 | isempty(classf), classf = libsvc([],[],100); end
if nargin < 5 | isempty(p), p = 1; end
if nargin < 4 | isempty(type), type = 'distance'; end
if nargin < 3 | isempty(featmap), featmap = []; end
if nargin < 2, r = []; end
if nargin < 1 | isempty(a)
w1 = mapping(mfilename,'untrained',{r,featmap,type,p,classf});
w = setname(w1,['FDSC ',getname(classf)]);
return
end
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
if isdataset(a) | isdatafile(a)
isvaldfile(a,1,1);
if isempty(featmap)
v = scalem(a); % shift mean to the origin
elseif isuntrained(featmap)
v = a*featmap;
elseif ismapping(featmap)
v = featmap;
else
error('Feature mapping expected')
end
if isempty(r)
r = a;
elseif is_scalar(r)
[r,a] = gendat(a,r);
end
w = proxm(r*v,type,p);
if ~isuntrained(classf)
error('Untrained classifier expected')
end
b = a*v*w;
%b = testdatasize(b);
n = disnorm(b);
u = b*n*classf;
w = v*w*n*u;
else
error('Unexpected input')
end
|
github
|
jacksky64/imageProcessing-master
|
spatm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/spatm.m
| 2,054 |
utf_8
|
e46a002860322effbf2030ce585f464d
|
%SPATM Augment image dataset with spatial label information
%
% E = SPATM(D,S)
% E = D*SPATM([],S)
%
% INPUT
% D image dataset classified by a classifier
% S smoothing parameter (optional, default: sigma = 1.0)
%
% OUTPUT
% E augmented dataset with additional spatial information
%
% DESCRIPTION
% If D = A*W*CLASSC, the output of a classification of a dataset A
% containing feature images, then E is an augmented version of D:
% E = [D T]. T contains the spatial information in D, such that
% it adds for each class of which the objects in D are assigned to,
% a Gaussian convoluted (std. dev s) 0/1 image with '1'-s on the
% pixel positions (objects) of that class. T is normalized such that
% its row sums are 1. It thereby effectively contains Parzen estimates
% of the posterior class probabilities if the image is considered as a
% feature space. Default: S = 1.
%
% Spatial and feature information can be combined by feeding E into
% a class combiner, e.g: A*W*CLASSC*SPATM([],2)*MAXC
%
% SEE ALSO
% DATASETS, MAPPINGS, PREX_SPATM
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: spatm.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function b = spatm(a,s)
prtrace(mfilename);
if nargin < 2, s = 1; end
if nargin < 1 | isempty(a)
b = mapping('spatm','fixed',s);
return
end
% assertion: the image with pixels being objects is required
isfeatim(a);
% initialize the label-image y:
[m,k,c] = getsize(a);
[n1,n2] = getobjsize(a);
%DXD Avoid that the feature labels might be reordered...
%[labt,x,newlablist] = renumlab(getfeatlab(a),labeld(a));
[dummy,x] = max(a,[],2);
y = zeros(n1,n2,max(x));
y((x(:)-1)*n1*n2 + [1:n1*n2]') = ones(n1,n2);
% make the label-image a dataset:
z = im2feat(y);
% Store also all the useful things like prior or lablist
z = setdat(a,z);
% smooth the label-image and add it to the dataset a:
b = [a datgauss(z,s)];
%b = datgauss(z,s);
return
|
github
|
jacksky64/imageProcessing-master
|
matchlab.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/matchlab.m
| 2,443 |
utf_8
|
4ce3510698452c48d4c4a857a3131926
|
%MATCHLAB Compare two labellings and rotate the labels for an optimal match
%
% LABELS = MATCHLAB(LAB1,LAB2)
%
% INPUT
% LAB1,LAB2 Label lists of the same objects
%
% OUTPUT
% LABELS A rotated version of LAB2, optimally matched with LAB1
%
% DESCRIPTION
% LAB1 and LAB2 are label lists for the same objects. The returned LABELS
% constitute a rotated version of LAB2, such that the difference with
% LAB1 is minimized. This can be used for the alignment of cluster results.
%
% EXAMPLES
% See PREX_MATCHLAB.
%
% SEE ALSO
% DATASETS, HCLUST, MODESEEK, KMEANS, EMCLUST
% $Id: matchlab.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function [lab,L] = matchlab(lab1,lab2)
prtrace(mfilename);
[ok1,lab1] = iscolumn(lab1);
[ok2,lab2] = iscolumn(lab2);
if (~ok1) | (~ok2)
prwarning(5,'Label lists should be column lists. LAB1 and LAB2 are made so.');
end
% Compute the confusion matrix and renumber the labels.
C = confmat(lab1,lab2);
[nl1,nl2,lablist] = renumlab(lab1,lab2);
% N1 and N2 describe the number of distinct labels (classes) in LAB1 and LAB2.
[n1,n2] = size(C);
L = zeros(n2,1); % Label list for the rotated LAB2
K = [1:n1]; % Class labels of LAB1
% Find the best match based on the confusion numbers.
for i=1:n1
[NN,r] = min(sum(C(:,K),1) - max(C(:,K),[],1));
j = K(r); % J is the actual class of LAB2
[nn,s] = max(C(:,j)); % to be assigned as S.
L(j) = s;
C(:,j) = zeros(n1,1); % J is already processed, remove it
K(r) = []; % from further considerations.
end
lab = lablist(L(nl2),:);
return;
%ISCOLUMN Checks whether the argument is a column array
%
% [OK,Y] = ISCOLUMN(X)
%
% INPUT
% X Array: an array of entities such as numbers, strings or cells
%
% OUTPUT
% OK 1 if X is a column array and 0, otherwise
% Y X or X' to ensure that Y is a column array
%
% DESCRIPTION
% Returns 1 if X is a column array and 0, otherwise. Y is the column
% version of X. If X is a matrix, an error is returned.
%
% Important: note that an array of one entity only is considered as
% a column array. So, X = 'Apple', X = {'Apple'} or X = 1 are column
% arrays.
%
function [ok,x] = iscolumn(x)
s = size(x);
if (isstr(x)) % Char array
ok = 1;
else % Vector of numbers
ok = (s(1) > 1 & s(2) == 1) | all(s == 1);
if all(s > 1)
error('X is a matrix. A vector is expected.');
end
end
if (~ok), x = x'; end
return;
|
github
|
jacksky64/imageProcessing-master
|
sequential.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/sequential.m
| 3,611 |
utf_8
|
c0548a91d3772beb03a2c590f1a43189
|
%SEQUENTIAL Sequential mapping
%
% V = SEQUENTIAL(W1,W2)
% B = SEQUENTIAL(A,W)
%
% INPUT
% W,W1,W2 Mappings
% A Dataset
%
% OUTPUT
% V Sequentially combined mapping
% B Dataset
%
% DESCRIPTION
% The two mappings W1 and W2 are combined into a single mapping V. Note
% that SEQUENTIAL(W1,W2) is equivalent to W1*W2. If W2 is a mapping of
% a type 'combiner', it is called to make a combination attempt.
% SEQUENTIAL(A,W) maps the dataset A by the sequential mapping W.
%
% This routine is automatically called to execute W = W1*W2 or B = A*W2 in
% case W2 is a sequential mapping. It should not be directly called by users.
%
% SEE ALSO
% MAPPINGS, DATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: sequential.m,v 1.6 2010/06/25 09:52:40 duin Exp $
function w = sequential(w1,w2,w3)
prtrace(mfilename);
% Just necessary to inform MAP.
if (nargin == 0)
w = mapping(mfilename,'combiner');
return;
end
[m1,k1] = size(w1);
[m2,k2] = size(w2);
if (~isa(w2,'mapping'))
error('Second argument should be a mapping.')
end
if isa(w1,'mapping')
% Definition
if isempty(w1) % treat empty mapping as unity mapping
w = w2;
elseif (iscombiner(w2))
% Execute the mapping W2.
map = getmapping_file(w2);
pars = getdata(w2);
w = feval(map,w1,pars{:});
else
% W2 is just a general mapping.
if (k1 > 0) & (m2 > 0) & (k1 ~= m2)
error('Inner mapping/data sizes do not agree.')
end
% Define the mapping type after combining W1 and W2.
if (isuntrained(w1)) | (isuntrained(w2))
mappingtype = 'untrained';
elseif (istrained(w1)) | (istrained(w2))
mappingtype = 'trained';
else
mappingtype = 'fixed';
end
if strcmp(mappingtype,'untrained')
labels = [];
size_in = 0;
size_out = 0;
elseif (m2 == 0 | k2 == 0) & (m1 ~= 0) & (k1 ~= 0)
% E.G. TRAINED * FIXED
labels = getlabels(w1);
size_in = getsize_in(w1);
size_out = getsize_out(w1);
elseif (m2 ~= 0) & (k2 ~= 0) & (m1 == 0 | k1 == 0)
% FIXED * TRAINED
labels = getlabels(w2);
size_in = getsize_in(w2);
size_out = getsize_out(w2);
elseif ~istrained(w2)
% TRAINED * FIXED
labels = getlabels(w1);
size_in = getsize_in(w1);
size_out = getsize_out(w2);
else
% TRAINED * TRAINED
labels = getlabels(w2);
size_in = getsize_in(w1);
size_out = getsize_out(w2);
end
w = mapping(mfilename,mappingtype,{w1,w2},labels,size_in,size_out);
end
w = setbatch(w,(getbatch(w1) & getbatch(w2)));
elseif isempty(w2) % treat empty mapping as unity mapping
w = w1;
else
% Execution. We are here, when SEQUENTIAL(A,V) is called.
if nargin == 3 % needed as MAP breaks down sequential mappings
w2 = w2*w3; % restore them!
end
a = w1;
if (~isa(a,'double')) & (~isa(a,'dataset'))
error('Just datasets or doubles can be mapped.')
end
% V can be a more complex mapping.
v = +w2; v1 = v{1}; v2 = v{2};
if (isuntrained(v1))
if (isuntrained(v2))
u = a*v1;
w = u*(a*u*v2);
else
w = a*v1*v2;
end
else
if (isuntrained(v2))
w = v1*(a*v1*v2);
% may be v1 changed the dimensionality, reset it:
w = setsize_in(w,size(a,2));
else
w = a*v1*v2;
featlabels = getlabels(w2);
if (isdataset(w)) & ~isempty(featlabels)
w = setfeatlab(w,featlabels);
end
end
end
if ismapping(w)
w = setbatch(w,getbatch(w2));
end
end
return;
|
github
|
jacksky64/imageProcessing-master
|
gendatd.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatd.m
| 2,549 |
utf_8
|
2490ae4a0fa5edd6119f172424195e52
|
%GENDATD Generation of 'difficult' normally distributed classes
%
% A = GENDATD(N,K,D1,D2,LABTYPE)
%
% INPUT
% N Number of objects in each of the classes (default: [50 50])
% K Dimensionality of the dataset (default: 2)
% D1 Difference in mean in feature 1 (default: 3)
% D2 Difference in mean in feature 2 (default: 3)
% LABTYPE 'crisp' or 'soft' labels (default: 'crisp').
%
% OUTPUT
% A Generated dataset
%
% DESCRIPTION
% Generation of a K-dimensional 2-class dataset A of N objects.
% Class variances are very different for the first two dimensions.
% Separation is thereby, for small sample sizes, 'difficult'.
%
% D1 is the difference between the means for the first feature, D2
% is the difference between the means for the second feature. In all
% other directions the means are equal. The two covariance matrices
% are equal with a variance of 1 in all directions except for the
% second feature, which has a variance of 40. The first two feature
% are rotated over 45 degrees to construct a strong correlation.
% Class priors are P(1) = P(2) = 0.5.
%
% If N is a vector of sizes, exactly N(I) objects are generated
% for class I, I = 1,2.
%
% LABTYPE defines the desired label type: 'crisp' or 'soft'. In the
% latter case true posterior probabilities are set for the labels.
%
% SEE ALSO
% DATASETS, PRDATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: gendatd.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function A = gendatd(N,k,d1,d2,labtype)
prtrace(mfilename);
if nargin < 5, labtype = 'crisp'; end
if nargin < 4, d2 = 3; end
if nargin < 3, d1 = 3; end
if nargin < 2, k = 2; end
if nargin < 1, N = [50 50]; end
if k < 2,
error('Number of features should be larger than 1'),
end
V = ones(1,k); V(2) = 40; V = sqrt(V);
p = [0.5 0.5];
N = genclass(N,p);
ma = zeros(1,k);
mb = zeros(1,k); mb(1:2) = [d1, d2];
A = [randn(N(1),k).*V(ones(1,N(1)),:) + ma(ones(1,N(1)),:); ...
randn(N(2),k).*V(ones(1,N(2)),:) + mb(ones(1,N(2)),:)];
A(:,1:2) = A(:,1:2)*[1 -1; 1 1]./sqrt(2);
lab = genlab(N);
A = dataset(A,lab,'name','Difficult Dataset','prior',p);
switch labtype
case 'crisp'
;
case 'soft'
U = dataset([ma(1:2);mb(1:2)],getlablist(A));
G = diag(V(1:2));
W = nbayesc(U,G);
targets = A(:,1:2)*W*classc;
A = setlabtype(A,'soft',targets);
otherwise
error(['Label type ' labtype ' not supported'])
end
return
|
github
|
jacksky64/imageProcessing-master
|
showfigs.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/showfigs.m
| 700 |
utf_8
|
cd1ab9d2bc6692b6dccc8b2cd94faea6
|
%SHOWFIGS Show all figures on the screen
%
% SHOWFIGS(K)
%
% Use K figures on a row
function showfigs(k)
h = sort(get(0,'children')); % handles for all figures
n = length(h); % number of figure
if nargin == 0
k = ceil(sqrt(n)); % figures to be shown
end
s = 0.95/k; % screen stitch
r = 0.93; % image size reduction
t = 0.055; % top gap
b = 0.005; % border gap
fig = 0;
set(0,'units','pixels');
monpos = get(0,'monitorposition');
for i=1:k
for j=1:k
fig = fig+1;
if fig > n, break; end
set(h(fig),'units','pixels','position',[(j-1)*s+b,(1-t)-i*s,s*r,s*r]*monpos(4));
figure(h(fig));
end
end
for j=n:-1:1, figure(h(j)); end
|
github
|
jacksky64/imageProcessing-master
|
parsc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/parsc.m
| 822 |
utf_8
|
c12237507f36a7b2589880ab583a1e25
|
%PARSC Parse classifier
%
% PARSC(W)
%
% Displays the type and, for combining classifiers, the structure of the
% mapping W.
%
% See also MAPPINGS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: parsc.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function parsc(w,space)
prtrace(mfilename);
% If W is not a mapping, do not generate an error but simply return.
if (~isa(w,'mapping')) return; end
if (nargin == 1)
space = '';
end
% Display W's type.
display(w,space);
% If W is a combining classifier, recursively call PARSC to plot the
% combined classier.
pars = getdata(w);
if (iscell(pars))
space = [space ' '];
for i=1:length(pars)
parsc(pars{i},space)
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
nusvo.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nusvo.m
| 13,099 |
utf_8
|
77ea7fcfc5be9ceba0683f334fd54943
|
%NUSVO Support Vector Optimizer: NU algorithm
%
% [V,J,NU,C] = NUSVO(K,NLAB,NU,OPTIONS)
%
% INPUT
% K Similarity matrix
% NLAB Label list consisting of -1/+1
% NU Regularization parameter (0 < NU < 1): expected fraction of SV (optional; default: 0.01)
% OPTIONS
% .PD_CHECK force positive definiteness of the kernel by adding a small constant
% to a kernel diagonal (default: 1)
% .BIAS_IN_ADMREG it may happen that bias of svc (b term) is not defined, then
% if BIAS_IN_ADMREG == 1, b will be taken from its admissible
% region (if the region is bounded, the midpoint will be used);
% if BIAS_IN_ADMREG == 0 the situation will be considered as
% an optimization failure and treated accordingly (deafault: 1)
% .ALLOW_UB_BIAS_ADMREG it may happen that bias admissible region is unbounded
% if ALLOW_UB_BIAS_ADMREG == 1, b will be heuristically taken
% from its admissible region, otherwise(ALLOW_UB_BIAS_ADMREG == 0)
% the situation will be considered as an optimization failure and
% treated accordingly (deafault: 1)
% .PF_ON_FAILURE if the optimization is failed (optimizer did not converge, or there are
% problems with finding of the bias term and PF_ON_FAILURE == 1,
% then Pseudo Fisher classifier will be computed,
% otherwise (PF_ON_FAILURE == 0) an error will be issued (default: 1)
%
%
% OUTPUT
% V Vector of weights for the support vectors
% J Index vector pointing to the support vectors
% NU NU parameter (useful when NU was automatically selected)
% C C regularization parameter of SVC algorithm, which gives the same classifier
%
%
%
% DESCRIPTION
% A low level routine that optimizes the set of support vectors for a 2-class
% classification problem based on the similarity matrix K computed from the
% training set. SVO is called directly from SVC. The labels NLAB should indicate
% the two classes by +1 and -1. Optimization is done by a quadratic programming.
% If available, the QLD function is used, otherwise an appropriate Matlab routine.
%
% NU is bounded from above by NU_MAX = (1 - ABS(Lp-Lm)/(Lp+Lm)), where
% Lp (Lm) is the number of positive (negative) samples. If NU > NU_MAX is supplied
% to the routine it will be changed to the NU_MAX.
%
% If NU is less than some NU_MIN which depends on the overlap between classes
% algorithm will typically take long time to converge (if at all).
% So, it is advisable to set NU larger than expected overlap.
%
% Weights V are rescaled in a such manner as if they were returned by SVO with the parameter C.
%
% SEE ALSO
% SVC_NU, SVO, SVC
% Copyright: S.Verzakov, [email protected]
% Based on SVO.M by D.M.J. Tax, D. de Ridder, R.P.W. Duin
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: nusvo.m,v 1.3 2010/02/08 15:29:48 duin Exp $
function [v,J,nu,C] = nusvo(K,y,nu,Options,arg)
% old call: K,y,nu,pd,abort_on_error
prtrace(mfilename);
% Old call conventions
if nargin > 4 | (nargin == 4 & ~isstruct(Options) & isempty(Options))
abort_on_error = [];
if nargin == 5
abort_on_error = arg;
end
pd = [];
if nargin >= 4
pd = Options;
end
clear Options
Options.pd_check = pd;
Options.bias_in_admreg = 1;
Options.allow_ub_bias_admreg = 1;
Options.pf_on_failure = ~abort_on_error;
end
if nargin < 4
Options = [];
end
DefOptions.pd_check = 1;
DefOptions.bias_in_admreg = 1;
DefOptions.allow_ub_bias_admreg = 1;
DefOptions.pf_on_failure = 1;
Options = updstruct(DefOptions,Options,1);
if nargin < 3
prwarning(3,'The regularization parameter NU is not specified, assuming 0.01.');
nu = 0.01;
end
nu_max = 1 - abs(nnz(y == 1) - nnz(y == -1))/length(y);
nu_max = nu_max*(1-1e-6); % to be on a safe side
if nu > nu_max
prwarning(3,['nu==' num2str(nu) ' is not feasible; set to ' num2str(nu_max)]);
nu = nu_max;
end
vmin = 1e-9; % Accuracy to determine when an object becomes the support object.
% Set up the variables for the optimization.
n = size(K,1);
D = (y*y').*K;
f = zeros(1,n);
A = [y';ones(1,n)];
b = [0; nu*n];
lb = zeros(n,1);
ub = ones(n,1);
p = rand(n,1);
D = (D+D')/2; % guarantee symmetry
if Options.pd_check
% Make the kernel matrix K positive definite.
i = -30;
while (pd_check (D + (10.0^i) * eye(n)) == 0)
i = i + 1;
end
if (i > -30),
prwarning(2,'K is not positive definite. The kernel is regularized by adding 10.0^(%d)*I',i);
end
i = i+2;
D = D + (10.0^(i)) * eye(n);
end
% Minimization procedure initialization:
% 'qp' minimizes: 0.5 x' D x + f' x
% subject to: Ax <= b
%
if (exist('qld') == 3)
v = qld (D, f, -A, b, lb, ub, p, length(b));
elseif (exist('quadprog') == 2)
prwarning(1,'QLD not found, the Matlab routine QUADPROG is used instead.')
v = quadprog(D, f, [], [], A, b, lb, ub);
else
prwarning(1,'QLD not found, the Matlab routine QP is used instead.')
verbos = 0;
negdef = 0;
normalize = 1;
v = qp(D, f, A, b, lb, ub, p, length(b), verbos, negdef, normalize);
end
try
% check if the optimizer returned anything
if isempty(v)
error('Optimization did not converge.');
end
% Find all the support vectors.
J = find(v > vmin);
Jp = J(y(J) == 1);
Jm = J(y(J) == -1);
% Sanity check: if there are support objects from both classes
if isempty(J)
error('There are no support objects.');
elseif isempty(Jp)
error('There are no support objects from the positive class.');
elseif isempty(Jm)
error('There are no support objects from the negative class.');
end
% Find the SV on the boundary
I = J(v(J) < 1-vmin);
Ip = I(y(I) == 1);
Im = I(y(I) == -1);
% Include class information into object weights
v = y.*v;
[rho, b] = FindRhoAndB(nu,y,K,v,J,Jp,Jm,Ip,Im,Options);
v = [v(J); b]/rho;
C = 1/rho;
catch
if Options.pf_on_failure
prwarning(1,[lasterr ' Pseudo-Fisher is computed instead.']);
n = size(K,1);
%v = prpinv([K ones(n,1)])*y;
v = prpinv([K ones(n,1); ones(1,n) 0])*[y; 0];
J = [1:n]';
C = nan;
else
rethrow(lasterror);
end
end
return;
function [rho, b] = FindRhoAndB(nu,y,K,v,J,Jp,Jm,Ip,Im,Options)
% There are boundary support objects from both classes, we can use them to find a bias term
if ~isempty(Ip) & ~isempty(Im)
% r1 = rho-b
r1 = mean(K(Ip,J)*v(J));
% r2 = rho+b
r2 = -mean(K(Im,J)*v(J));
else
% Boundary support objects are absent at least in one of classes
n = length(v);
% non SV, we need them to resctric the addmissible region from above
J0 = (1:n)';
J0(J) = [];
J0p = J0(y(J0) == 1);
J0m = J0(y(J0) == -1);
% Only margin errors SV exist
if isempty(Ip) & isempty(Im)
% If only margin error SV's are present then it has to be true
% nSVp = nSVm, nu*n = nSVp + nSVm, it means that
% rho and b should be in the region
% lb1 <= rho-b <= ub1, lb2 <= rho+b <= ub2
% rho > 0 (rho = 0 corresponds to the zero margin solution, and cannot be
% interpreted as a standard SVC)
if length(Jp) ~= length(Jm)
error('Inconsistency: only margin errors SV exist and nSVp ~= nSVm.');
elseif nu*n ~= length(J)
error('Inconsistency: only margin errors SV exist and nu*n ~= nSV.');
elseif ~Options.bias_in_admreg
error('The bias term is undefined.');
end
% suport objects are always exist, the region is alway bounded from below
% if there are no nonSV, the region is unbounded from above
% r1 = rho-b
lb1 = max(K(Jp,J)*v(J));
ub1 = min([K(J0p,J)*v(J); inf]);
% r2 = rho+b
lb2 = -min(K(Jm,J)*v(J));
ub2 = -max([K(J0m,J)*v(J); -inf]);
if lb1 > ub1 | lb2 > ub2
error('Admissible region of the bias term is empty.');
end
if isinf(ub1) | isinf(ub2)
Msg = 'Admissible region of the bias term is unbounded';
if Options.allow_ub_bias_admreg
prwarning(1,Msg);
else
error(Msg);
end
end
% admissible region is a a part of
% domain [lb1; ub1] x [lb2; ub2] which is above r2 = -r1 line
%
% we put (r1,r2) on a rectangle diagonal connecting upper right and bottom left
% corners half way from the point of intersection between this diagonal and line r2 = -r1;
%
% first we make a rectangle bounded (put upper right corner above r2 = -r1 line)
if isinf(ub1)
ub1 = max(-lb2,lb1)+1;
end
if isinf(ub2)
ub2 = max(-lb1,lb2)+1;
end
r1_intersection = (ub2*lb1 - ub1*lb2)/(ub2-lb2 + ub1-lb1);
r2_intersection = -r1_intersection;
% it may happen that intersecton does not exist:
%
% 1) the whole domain is above line r2 = -r1,
% then we use bottom left corner insted of it
%
% 2) the whole domain is below line r2 = - r1, it means that there is no solution
% with positive margin and the condition r1+r2 > 0 will be violated (we check it at the end)
lb1 = max(lb1,r1_intersection);
lb2 = max(lb2,r2_intersection);
r1 = (lb1 + ub1)/2;
r2 = (lb2 + ub2)/2;
% Only margin errors SV are present in the negative class
elseif ~isempty(Ip) & isempty(Im)
% r1 = rho-b
r1 = mean(K(Ip,J)*v(J)); % rho-b
% r2 = rho+b
lb2 = -min(K(Jm,J)*v(J));
ub2 = -max([K(J0m,J)*v(J); -inf]);
if lb2 > ub2
error('The admissible region of the bias term is empty.');
end
% we need to minimize(2*mSVm - nu*n)*r2
% s.t. lb2 <= r2 <= ub2, r2 > -r1
coeff_sign = 2*length(Jm) - nu*n;
if coeff_sign > 0
r2 = lb2; % put r2 to the lowest value, it has to be large than -r1
elseif coeff_sign < 0
r2 = ub2;
% If coeff_sign <0 it means, that nu*n > 2*mSVm
% Also, nu*n <= nu_max*n = n-abs(np-nm) = 2*min(np,nm)
% mSVm < min(np,nm) <= nm
% thus nm-mSVm = nonSVm+bSVm = nonSVm > 0 and ub2 < inf
else % coeff_sing == 0
if ~Options.bias_in_admreg
error('The bias term is undefined.');
end
% correcting lb2 in such a way that rho >= 0, for (r1,lb2),
% it may happen that lb2 > ub2, let's check it later (r1+r2 > 0)
lb2 = max(lb2,-r1);
if isinf(ub2)
Msg = 'Admissible region of the bias term is unbounded';
if Options.allow_ub_bias_admreg
prwarning(1,Msg);
ub2 = lb2 + 1;
else
error(Msg);
end
end
r2 = (lb2+ub2)/2;
end
% Only margin errors SV are present in the positive class
elseif isempty(Ip) & ~isempty(Im)
% r1 = rho-b
lb1 = max(K(Jp,J)*v(J));
ub1 = min([K(J0p,J)*v(J); inf]);
% r2 = rho+b
r2 = -mean(K(Im,J)*v(J));
if lb1 > ub1
error('The admissible region of the bias term is empty.');
end
% we need to minimize(2*mSVp - nu*n)*r1
% s.t. lb1 <= r1 <= ub1, r2 > -r1
coeff_sign = 2*length(Jp) - nu*n;
if coeff_sign > 0
r1 = lb1; % put r1 to the lowest value, it has to be large than -r2
elseif coeff_sign < 0
r1 = ub1;
% If coeff_sign <0 it means, that nu*n > 2*mSVp
% Also, nu*n <= nu_max*n = n-abs(np-nm) = 2*min(np,nm)
% mSVp < min(np,nm) <= np
% thus np-mSVp = nonSVp+bSVp = nonSVp > 0 and ub1 < inf
else % coeff_sing == 0
if ~Options.bias_in_admreg
error('The bias term is undefined.');
end
% correcting lb1 in such a way that rho >= 0, for (lb1,r2),
% it may happen that lb1 > ub1, let's check it later (r1+r2 > 0)
lb1 = max(lb1,-r2);
if isinf(ub1)
Msg = 'The admissible region of the bias term is unbounded.';
if Options.allow_ub_bias_admreg
prwarning(1,Msg);
ub2 = lb1 + 1;
else
error(Msg);
end
end
r1 = (lb1+ub1)/2;
end
end
if r1 + r2 <= 0
error('The solution with the positive margin does not exist.');
elseif isinf(r1) | isinf(r2)
% This should never happen, because nu <=nu_max
error('The contradiction is detected. Although nu <=nu_max, the rho (functional margin size) is infinite');
end
end
rho = (r2+r1)/2;
b = (r2-r1)/2;
return
|
github
|
jacksky64/imageProcessing-master
|
bagc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/bagc.m
| 5,838 |
utf_8
|
34c5773a5b24755a649f551adf94c547
|
%BAGC Bag classifier for classifying sets of objects
%
% [WBAG,WOBJ] = BAGC(A,OBJCLASSF,BAGINDEX,BAGCOMBC,BAGCLASSF,BAGLAB)
% D = B*WBAG
%
% INPUT
% A Training dataset with object labels and bag indices
% B Test Dataset with index list of bags, stored as label list
% OBJCLASSF Trained or untrained object classifier, default QDC
% BAGINDEX String or a label_list_index defining in which label list
% of A the bag indices are stored, default 2.
% BAGCOMBC Combiner for objects in a bag, default VOTEC
% BAGCLASSF Untrained classifier for bags, default FISHERC
% BAGLAB String or a label_list_index defining in which label list
% of A the bag labels are stored. Objects with the same
% bag index should have the same bag label.
% Default is the current labeling of A
%
% OUTPUT
% WBAG Trained bag classifier
% WOBJ Trained object classifier
% D Classification matrix of bags in B
%
% DESCRIPTION
% This routine offers a classifier for bags (e.g. images) of objects
% (e.g. pixels) stored in a single dataset. The objects in the training
% set A should have at least two labels: bag labels (the class of their bag)
% and bag indices, defining which objects belong to the same bag. These two
% label sets should be stored by the ADDLABELS command in the dataset A.
% Refer to the multi-labeling system (see MULTI_LABELING) offered by
% PRTools. The current object labels of A can be the bag labels, but may
% also be different, e.g. true object labels.
%
% BAGINDEX should be a label_list_name or a label_list_index defining the
% label list used for storing the bag indices that refer to the bag an
% object belongs to. The same label_list_name or label_list_index should be
% used for defining the bags of the test objects in B.
%
% All objects in A are used to train the object classifier OBJCLASSF if it
% is untrained. The current object labels are used for that. Classification
% results of the objects in the same bag are combined by BAGCOMBC, which
% can be any of the fixed combiners MEANC, PRODC, PERC, MAXC, etcetera.
% This results for every bag in a single confidence vector for the classes.
%
% If an untrained bag classifier BAGCLASSF is supplied, the bag confidence
% vectors are used to train a bag classifier.
%
% New bags, organised in a dataset like B, with the proper bag indices per
% object stored in a label list with the same name or label_list_index as
% used in A, can be classified by the bag classifier WBAG.
%
% If no bag classifier BAGCLASSF was defined during training, just the
% results of the object classifier WOBJ are returned combined by BAGCOMBC
% over the objects in the same bag in B. In this case the final result is
% identical to B*(A*WOBJ)*BAGCC([],BAGCOMBC), provided that A has class
% labels and B is labeled by its bag indices.
%
% SEE ALSO
% DATASETS, MAPPINGS, MULTI_LABELING, BAGCC, LOSO,
% DATASET/ADDLABELS, DATASET/CHANGELABLIST
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [out1,out2] = bagc(a,objclassf,bagindex,bagcombc,bagclassf,baglab)
if nargin < 6 | isempty(baglab), baglab = []; end
if nargin < 5 | isempty(bagclassf), bagclassf = []; end
if nargin < 4 | isempty(bagcombc), bagcombc = votec; end
if nargin < 3 | isempty(bagindex), bagindex = 2; end
if nargin < 2 | isempty(objclassf), objclassf = qdc; end
if nargin < 1 | isempty(a)
% define the mapping
wset = mapping(mfilename,'untrained',{objclassf,bagindex,setcombc,bagclassf,baglab});
out1 = setname(wset,'Set classifier');
elseif isuntrained(objclassf) | nargin > 2 | ~strcmp(getmapping_file(objclassf),mfilename)
% train the mapping (classifier)
% we need datasets with at least 1 object per class and 2 classes
isvaldset(a,1,2);
% if the object classifier is untrained, train it, else use it
if isuntrained(objclassf)
wobj = a*objclassf;
else
wobj = objclassf;
end
if ismapping(bagclassf) & isuntrained(bagclassf)
% if the bag labels are not given,
% use the objcts labels for the bags too
if isempty(setlab), setlab = curlablist(a); end
% classifiy the dataset and change labeling to bag index
x = changelablist(a*wobj,setindex);
% avoid empty bags
x = setlablist(x);
% combine object results to bag results
d = bagcc(x,bagcombc);
% change to bag labels
d = changelablist(d,baglab);
% train bag classifier
bagclassf = d*bagclassf;
% get outputlabels
labels_out = getlabels(bagclassf);
else
labels_out = getlabels(wobj);
end
% store all what is needed for execution in the mapping
out1 = mapping(mfilename,'trained',{wobj,bagcombc,bagclassf,bagindex,baglab}, ...
labels_out, size(a,2),size(labels_out,1));
% prevent batch execution
out1 = setbatch(out1,0);
% return the object classifier as well
out2 = wobj;
else % here we are for execution
% the mapping is stored in objclassf
w = getdata(objclassf);
% save current lablist
curlist = curlablist(a);
% use the bag index for the test set if supplied
if ~isempty(w{4}), testset = changelablist(a,w{4}); end
% classify test set by the object classifier
d = testset*w{1};
% avoid empty bags
d = setlablist(d);
% combine objects in the same bag
d = bagcc(d,w{2});
% reset lablist for classification matrix
d = changelablist(d,curlist);
% apply the set classifier, if defined
if ~isempty(w{3}), d = d*w{3}; end
% that is it, define class labels as feature labels
out1 = setfeatlab(d,getlabels(objclassf));
end
|
github
|
jacksky64/imageProcessing-master
|
isdatafile.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isdatafile.m
| 432 |
utf_8
|
3db749ec603b6905a19079febdbe4ad0
|
%ISDATAFILE Test whether the argument is a datafile
%
% N = ISDATAFILE(A);
%
% INPUT
% A Input argument
%
% OUTPUT
% N 1/0 if A is/isn't a datafile
%
% DESCRIPTION
% The function ISDATAFILE test if A is a datafile object.
%
% SEE ALSO
% ISMAPPING, ISDATAIM, ISFEATIM
function n = isdatafile(a)
prtrace(mfilename);
n = isa(a,'datafile');
if (nargout == 0) & (n == 0)
error([newline 'Datafile expected.'])
end
return;
|
github
|
jacksky64/imageProcessing-master
|
getlab.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/getlab.m
| 1,052 |
utf_8
|
b98123fcb599f94c58d4cf2fc066238a
|
%GETLAB Get labels of dataset or mapping
%
% LABELS = GETLAB(A)
% LABELS = GETLAB(W)
%
% INPUT
% A Dataset
% W Mapping
%
% OUTPUT
% LABELS Labels
%
% DESCRIPTION
% Returns the labels of the objects in the dataset A or the feature labels
% assigned by the mapping W.
%
% If A (or W) is neither a dataset nor a mapping, a set of dummy
% labels is returned, one for each row in A. All these labels have the
% value NaN.
%
% Note that for datasets and mappings GETLAB() is effectively the same
% as GETLABELS().
%
% SEE ALSO
% DATASETS, MAPPINGS, GETLABELS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: getlab.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function labels = getlab(a)
prtrace(mfilename);
if isa(a,'dataset')
labels = getlabels(a,'crisp');
elseif isa(a,'datafile')
labels = getlabels(a,'crisp');
elseif isa(a,'mapping')
labels = getlabels(a);
else
labels = repmat(NaN,size(a,1),1);
end
return
|
github
|
jacksky64/imageProcessing-master
|
nlabeld.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nlabeld.m
| 1,491 |
utf_8
|
68528c7a976a65375113b0826d3e77c2
|
%NLABELD Return numeric labels of classified dataset
%
% NLABELS = NLABELD(Z)
% NLABELS = Z*NLABELD
% NLABELS = NLABELD(A,W)
% NLABELS = A*W*NLABELD
%
% INPUT
% Z Classified dataset, or
% A,W Dataset and classifier mapping
%
% OUTPUT
% NLABELS vector of numeric labels
%
% DESCRIPTION
% Returns the numberic labels of the classified dataset Z (typically the result of a
% mapping or classification A*W). For each object in Z (i.e. each row) the
% feature label or class label (i.e. the column label) of the maximum column
% value is returned.
%
% SEE ALSO
% MAPPINGS, DATASETS, TESTC, PLOTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function labels = nlabeld(a,w)
prtrace(mfilename);
if (nargin == 0)
% Untrained mapping.
labels = mapping(mfilename,'fixed');
elseif (nargin == 1)
% In a classified dataset, the feature labels contain the output
% of the classifier.
[m,k] = size(a); featlist = getfeatlab(a);
if (k == 1)
% If there is one output, assume it's a 2-class discriminant:
% decision boundary = 0.
J = 2 - (double(a) >= 0);
else
% Otherwise, pick the column containing the maximum output.
[dummy,J] = max(+a,[],2);
end
labels = J;
elseif (nargin == 2)
% Just construct classified dataset and call again.
labels = feval(mfilename,a*w);
else
error ('too many arguments');
end
return
|
github
|
jacksky64/imageProcessing-master
|
issequential.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/issequential.m
| 690 |
utf_8
|
423df5d323415d1898676c9dc38ba5de
|
%ISSEQUENTIAL Test on sequential mapping
%
% N = ISSEQUENTIAL(W)
% ISSEQUENTIAL(W)
%
% INPUT
% W input mapping
%
% OUTPUT
% N logical value
%
% DESCRIPTION
% Returns true for sequential mappings. If no output is required,
% false outputs are turned into errors. This may be used for
% assertion.
%
% SEE ALSO
% ISMAPPING, ISSEQUENTIAL
function n = issequential(w)
prtrace(mfilename);
if isa(w,'mapping') & strcmp(w.mapping_file,'sequential')
n = 1;
else
n = 0;
end
% generate error if input is not a sequential mapping
% AND no output is requested (assertion)
if nargout == 0 & n == 0
error([newline '---- Sequential mapping expected -----'])
end
return
|
github
|
jacksky64/imageProcessing-master
|
meancov.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/meancov.m
| 4,697 |
utf_8
|
516e769bd293798e8908454943696bae
|
%MEANCOV Estimation of the means and covariances from multiclass data
%
% [U,G] = MEANCOV(A,N)
%
% INPUT
% A Dataset
% N Normalization to use for calculating covariances: by M, the number
% of samples in A (N = 1) or by M-1 (default, unbiased, N = 0).
%
% OUTPUT
% U Mean vectors
% G Covariance matrices
%
% DESCRIPTION
% Computation of a set of mean vectors U and a set of covariance matrices G
% of the C classes in the dataset A. The covariance matrices are stored as a
% 3-dimensional matrix G of the size K x K x C, the class mean vectors as a
% labeled dataset U of the size C x K.
%
% The use of soft labels or target labels is supported.
%
% SEE ALSO
% DATASETS, NBAYESC, DISTMAHA
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: meancov.m,v 1.7 2010/02/08 15:31:47 duin Exp $
function [U,G] = meancov(a,n)
prtrace(mfilename);
% N determines whether the covariances are normalized by M (N = 1) or by
% M-1 (unbiased, N = 0), where M is the number of objects.
if nargin < 1
U = mapping(mfilename,'fixed');
return
end
if (nargin < 2 | isempty(n))
prwarning(4,'normalisation not specified, assuming by M-1');
n = 0;
end
if (n ~= 1) & (n ~= 0)
error('Second parameter should be either 0 or 1.')
end
if (isdouble(a)) % A is a matrix: compute mean and covariances
U = mean(a); % in the usual way.
if nargout > 1
G = prcov(a,n);
end
elseif (isdatafile(a))
if nargout < 2
U = meancov_datafile(a,n);
else
[U,G] = meancov_datafile(a,n);
end
elseif (isdataset(a))
[m,k,c] = getsize(a);
if nargout == 2
G = zeros(k,k,c);
end
if (islabtype(a,'crisp'))
if (c==0) % special solution if all data is unlabeled
U = mean(+a);
if nargout > 1
G = prcov(+a,n);
end
else
for i = 1:c
J = findnlab(a,i);
if isempty(J)
U(i,:) = repmat(NaN,1,k);
if nargout > 1
G(:,:,i) = repmat(NaN,k,k);
end
else
U(i,:) = mean(a(J,:),1);
if (nargout > 1)
G(:,:,i) = covm(a(J,:),n);
end
end
end
end
labu = getlablist(a);
elseif (islabtype(a,'soft'))
problab = gettargets(a);
% Here we also have to be careful for unlabeled data
if (c==0)
prwarning(2,'The dataset has soft labels but no targets defined: using targets 1');
U = mean(+a);
if nargout > 1
G = prcov(+a,n);
end
else
U = zeros(c,k);
for i = 1:c
g = problab(:,i);
if mean(g) == 0 % all targets are zero: zero mean, zero cov.
G(:,:,i) = zeros(k,k);
else
% Calculate relative weights for the means.
g = g/mean(g);
U(i,:) = mean(a.*repmat(g,1,k)); % Weighted mean vectors
if (nargout > 1)
u = mean(a.*repmat(sqrt(g),1,k));
% needed to weight cov terms properly
G(:,:,i) = covm(a.*repmat(sqrt(g),1,k),1) - U(i,:)'*U(i,:) + u'*u;
% Re-normalise by M-1 if requested.
if (n == 0)
G(:,:,i) = m*G(:,:,i)/(m-1);
end
end
end
end
end
labu = getlablist(a);
else
% Default action.
U = mean(a);
if nargout > 1
G = covm(a,n);
end
labu = [];
end
% Add attributes of A to U.
U = dataset(U,labu,'featlab',getfeatlab(a), ...
'featsize',getfeatsize(a));
if (~islabtype(a,'targets'))
% p = getprior(a);
U = setprior(U,a.prior);
end
else
error('Illegal datatype')
end
return
%MEANCOV Datafile overload
function [u,g] = meancov_datafile(a,n)
if nargin < 2, n = []; end
[m,k,c] = getsize(a);
k = 0; % just for detecting first loop
next = 1;
while next > 0
[b,next] = readdatafile(a,next);
if k == 0
k = size(b,2);
if c == 0
u = zeros(1,k);
else
u = zeros(c,k);
end
if nargout > 1
if c == 0
g = zeros(k,k);
else
g = zeros(k,k,c);
end
end
end
%compute for each call to readdatafile contributions to mean and cov
bb = + b;
if c == 0
u = u + sum(bb,1);
else
nlab = getnlab(b);
for j=1:size(b,1)
if nlab(j) > 0
u(nlab(j),:) = u(nlab(j),:) + bb(j,:);
if nargout > 1
g(:,:,nlab(j)) = g(:,:,nlab(j)) + bb(j,:)'*bb(j,:);
end
end
end
end
end
f = classsizes(a);
u = u ./ repmat(f',1,k);
if nargout == 2
for j=1:c
g(:,:,j) = g(:,:,j)/f(j) - u(j,:)'*u(j,:);
if isempty(n) | n == 0
g(:,:,j) = (f(j)/(f(j)-1))*g(:,:,j);
end
end
end
u = dataset(u,getlablist(b));
u.prior = b.prior;
return
|
github
|
jacksky64/imageProcessing-master
|
lmnc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/lmnc.m
| 1,729 |
utf_8
|
d81df5248a7ba509f542ad246d4ee62e
|
%LMNC Levenberg-Marquardt trained feed-forward neural net classifier
%
% [W,HIST] = LMNC (A,UNITS,ITER,W_INI,T)
%
% INPUT
% A Dataset
% UNITS Vector with numbers of units in each hidden layer (default: [5])
% ITER Number of iterations to train (default: inf)
% W_INI Weight initialization network mapping (default: [], meaning
% initialization by Matlab's neural network toolbox)
% T Tuning set (default: [], meaning use A)
%
% OUTPUT
% W Trained feed-forward neural network mapping
% HIST Progress report (see below)
%
% DESCRIPTION
% A feed-forward neural network classifier with length(N) hidden layers with
% N(I) units in layer I is computed for the dataset A. Training is stopped
% after ITER epochs (at least 50) or if the iteration number exceeds twice
% that of the best classification result. This is measured by the labeled
% tuning set T. If no tuning set is supplied A is used. W_INI is used, if
% given, as network initialization. Use [] if the standard Matlab
% initialization is desired. Progress is reported in file FID (default 0).
%
% The entire training sequence is returned in HIST (number of epochs,
% classification error on A, classification error on T, MSE on A, MSE on T,
% mean of squared weights).
%
% Uses the Mathworks' Neural Network toolbox.
%
% SEE ALSO
% MAPPINGS, DATASETS, BPXNC, NEURC, RNNC, RBNC, PRPROGRESS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: lmnc.m,v 1.3 2007/06/15 09:58:30 duin Exp $
function [w,hist] = lmnc(varargin)
prtrace(mfilename);
[w,hist] = ffnc(mfilename,varargin{:});
return
|
github
|
jacksky64/imageProcessing-master
|
nbayesc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nbayesc.m
| 1,973 |
utf_8
|
f3a84fd0ca90586f58eeb8c3cb521e93
|
%NBAYESC Bayes Classifier for given normal densities
%
% W = NBAYESC(U,G)
%
% INPUT
% U Dataset of means of classes
% G Covariance matrices (optional; default: identity matrices)
%
% OUTPUT
% W Bayes classifier
%
% DESCRIPTION
% Computation of the Bayes normal classifier between a set of classes.
% The means, labels and priors are defined by the dataset U of the size
% [C x K]. The covariance matrices are stored in a matrix G of the
% size [K x K x C], where K and C correspond to the dimensionality and
% the number of classes, respectively.
%
% If C is 1, then G is treated as the common covariance matrix, yielding
% a linear solution. For G = I, the nearest mean solution is obtained.
%
% This routine gives the exact solution for the given parameters, while
% the trainable classifiers QDC and LDC give approximate solutions, based
% on the parameter estimates from a training set. For a given dataset, U
% and G can be computed by MEANCOV.
%
% EXAMPLES
% [U,G] = MEANCOV(GENDATB(25));
% W = NBAYESC(U,G);
%
% SEE ALSO
% MAPPINGS, DATASETS, QDC, LDC, NMC.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: nbayesc.m,v 1.4 2009/01/04 21:11:07 duin Exp $
function W = nbayesc(U,G);
prtrace(mfilename);
[cu,ku] = size(U); % CU is the number of classes and KU - the dimensionality
if nargin == 1,
prwarning(4,'Covariance matrix is not specified, the identity matrix is assumed.');
G = eye(ku);
end
[k1,k2,c] = size(G); % C = 1, if G is the common covariance matrix.
if (c ~= 1 & c ~= cu) | (k1 ~= k2) | (k1 ~= ku)
error('Covariance matrix or a set of means has a wrong size.')
end
pars.mean = +U;
pars.cov = G;
pars.prior = getprior(U);
%W = mapping('normal_map','trained',pars,getlablist(U),ku,cu);
W = normal_map(pars,getlablist(U),ku,cu);
W = setname(W,'BayesNormal');
W = setcost(W,U);
return;
|
github
|
jacksky64/imageProcessing-master
|
im2feat.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im2feat.m
| 2,376 |
utf_8
|
e83cbb9ad8a4892f4b9e358f6649c454
|
%IM2FEAT Convert Matlab images or datafile to dataset feature
%
% B = IM2FEAT(IM,A)
%
% INPUT
% IM X*Y image, X*Y*K array of K images, or cell-array of images
% The images may be given as a datafile.
% A Input dataset
%
% OUTPUT
% B Dataset with IM added
%
% DESCRIPTION
% Add standard Matlab images, as features, to an existing dataset A. If A is
% not given, a new dataset is created. Images of type 'uint8' are converted
% to 'double' and divided by 256. The set of images IM may be given as a
% datafile.
%
% SEE ALSO
% DATASETS, DATAFILES, IM2OBJ, DATA2IM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: im2feat.m,v 1.4 2008/07/28 08:59:47 duin Exp $
function a = im2feat (im,a)
prtrace(mfilename);
if (isa(im,'cell'))
% If IM is a cell array of images, unpack it and recursively call IM2FEAT
% to add each image.
im = im(:);
if (nargin < 2)
a = dataset([]);
end
n = length(im);
s = sprintf('Converting %i images: ',n);
prwaitbar(n,s);
for i = 1:length(im)
prwaitbar(n,i,[s int2str(i)]);
a = [a feval(mfilename,im{i})];
end
prwaitbar(0);
elseif isdatafile(im)
if (nargin < 2)
a = dataset([]);
end
testdatasize(im);
a = [a feval(mfilename,data2im(im))];
else
% If IM is an image or array of images, reshape it and add it in one go.
n = size(im,3); imsize = size(im);
if length(imsize) == 4
m = imsize(4);
else
m = 1;
end
imsize = imsize(1:2);
% Convert to double, if necessary
if (isa(im,'uint8') | isa(im,'uint16'))
prwarning(4,'Image is uint; converting to double and dividing by 256');
im = double(im)/256;
end
% Reshape images to vectors and store bands as features in dataset.
if m==1
imm = reshape(im,imsize(1)*imsize(2),n);
objsize = imsize(1:2);
else
imm = [];
for i=1:m
imm = [imm; reshape(im(:,:,:,i),imsize(1)*imsize(2),n)];
end
objsize = [imsize(1:2) m];
end
if (nargin > 1)
if (~isa(a,'dataset'))
error('Second argument is not a dataset')
end
if (size(imm,1) ~= size(a,1))
error('Image size and dataset object size do not match')
end
a = [a imm];
else
a = dataset(imm);
a = setobjsize(a,objsize);
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
datasetconv.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/datasetconv.m
| 352 |
utf_8
|
b95f2e854d2189ab21fc91db2b4dc30c
|
%DATASETCONV Convert to dataset if needed
%
% A = DATASETCONV(A)
%
% If A is not a dataset it is converted to a dataset.
%
% SEE ALSO
% DATASETS, DATASET
function a = datasetconv(a)
% This is just programmed like this for speed, as
% a = dataset(a) will do the same but involves more checking
if ~isdataset(a)
a = dataset(a);
end
|
github
|
jacksky64/imageProcessing-master
|
normm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/normm.m
| 2,861 |
utf_8
|
cb4e55cf8a9dfcb89939f885a33d9420
|
%NORMM Apply Minkowski-P distance normalization map
%
% B = A*NORMM(P)
% B = NORMM(A,P)
%
% INPUT
% A Dataset or matrix
% P Order of the Minkowski distance (optional; default: 1)
%
% OUTPUT
% B Dataset or matrix of normalized Minkowski-P distances
%
% DESCRIPTION
% Normalizes the distances of all objects in the dataset A such that their
% Minkowski-P distances to the origin equal one. For P=1 (default), this is
% useful for normalizing the probabilities. For 1-dimensional datasets
% (SIZE(A,2)=1), a second feature is added before the normalization such
% that A(:,2)=1-A(:,1).
%
% Note that NORMM(P) or NORMM([],P) is a fixed mapping.
%
% SEE ALSO
% MAPPINGS, DATASETS, CLASSC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: normm.m,v 1.4 2007/12/10 15:56:06 davidt Exp $
function w = normm(a,p)
prtrace(mfilename);
if (nargin == 0) | (isempty(a))
% No data, store the parameters of a fixed mapping.
if nargin<2, p=1; end;
w = mapping(mfilename,'fixed',{p});
w = setname(w,'Normalization Mapping');
elseif (nargin == 2) & (isempty(a))
% No data, store the parameters of a fixed mapping.
w = mapping(mfilename,'fixed',p);
w = setname(w,'Normalization Mapping');
elseif (nargin == 1 & (isa(a,'dataset') | length(a) > 1)) | (nargin == 2)
% We have the case of either W = NORMM(A) or W = NORMM(A,P),
% hence W is now a dataset A with normalized Minkowski-P distances.
[m,k] = size(a);
if (k == 1) & isdataset(a)
% Normalisation of a 1-D dataset may only be used for one-class
% classification outcomes. So we test whether this is the case as
% good as possible and send out warnings as well
a = [a 1-a]; % Add a second feature, handy for the normalization.
k = 2;
prwarning(4,'SIZE(A,2)=1, so the second feature 1-A(:,1) is added.');
featlist = getfeatlab(a);
if size(featlist,1) < 2
error('No two class-names found; probably a wrong dataset used.')
else
a = setfeatlab(a,featlist(1:2,:));
end
end
if (nargin == 1),
prwarning(3,'Parameter P is not specified, 1 is assumed.');
p = 1;
end
% Compute the Minkowski-P distances to the origin.
if (p == 1)
dist = sum(abs(a),2); % Simplify the computations for P=1.
else
dist = sum(abs(a).^p,2).^(1/p);
end
% For non-zero distances, scale them to 1.
% Note that W is now a dataset with scaled Minkowski distances.
J = find(dist ~= 0);
w = a;
if ~isempty(J)
w(J,:) = +a(J,:)./repmat(dist(J,1),1,k);
end
elseif (nargin == 1) & isa(a,'double') & (length(a) == 1)
% We have the case W = NORMM(P), hence W is the mapping.
w = mapping(mfilename,'fixed',a);
w = setname(w,'Normalization Mapping');
else
error('Operation undefined.')
end
return;
|
github
|
jacksky64/imageProcessing-master
|
isobjim.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isobjim.m
| 772 |
utf_8
|
c465aa4b99a145aff0001ec8b413bdba
|
%ISOBJIM test if the dataset contains objects that are images
%
% N = ISOBJIM(A)
% ISOBJIM(A)
%
% INPUT
% A input dataset
%
% OUTPUT
% N logical value
%
% DESCRIPTION
% True if dataset contains objects that are images. If no output is required,
% false outputs are turned into errors. This may be used for assertion.
%
% SEE ALSO
% ISDATASET, ISDATAIM
% $Id: isobjim.m,v 1.5 2009/01/31 15:43:10 duin Exp $
function n = isobjim(a)
prtrace(mfilename);
n = (isa(a,'dataset') & length(a.featsize) > 1) | isdatafile(a);
% generate error if input is not a dataset with image data with
% pixels being features AND no output is requested (assertion)
if nargout == 0 & n == 0
error([newline '---- Dataset with object images expected -----'])
end
return
|
github
|
jacksky64/imageProcessing-master
|
datgauss.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/datgauss.m
| 2,418 |
utf_8
|
ace1a3fbf372299804b0c039c7127923
|
%DATGAUSS Apply Gaussian filter on images in a dataset
%
% B = DATGAUSS(A,SIGMA)
%
% INPUT
% A Dataset containing images
% SIGMA Standard deviation of Gaussian filter (default 1)
%
% OUTPUT
% B Dataset with filtered images
%
% DESCRIPTION
% All images stored as objects (rows) or as features (columns) of dataset A
% are filtered with a Gaussian filter with standard deviation SIGMA and
% stored in dataset B. Image borders are mirrored before filtering.
%
% SEE ALSO
% DATASETS, DATAIM, IM2OBJ, IM2FEAT, DATUNIF, DATFILT
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: datgauss.m,v 1.5 2009/01/04 21:04:44 duin Exp $
function a = datgauss(a,sigma)
prtrace(mfilename);
if nargin < 2 | isempty(sigma)
sigma = 1;
end
if nargin < 1 | isempty(a)
a = mapping(mfilename,'fixed',{sigma});
a = setname(a,'Gaussian filter');
return
end
if ismapping(sigma)
w = sigma;
sigma = w.data{1};
end
% Convert dataset to image or image array.
im = data2im(a); [imheight,imwidth,nim] = size(im);
% Check argument.
sigma = sigma(:);
if (length(sigma) ~= 1) & (length(sigma) ~= nim)
error('incorrect mumber of standard deviations specified')
end
% Create filter(s): 1D Gaussian.
bordersize = ceil(2*sigma); filtersize = 2*bordersize + 1;
filter = exp(-repmat((([1:filtersize] - bordersize - 1).^2),length(sigma),1) ...
./repmat((2.*sigma.*sigma),1,filtersize)); % Gaussian(s).
filter = filter ./ repmat(sum(filter,2),1,filtersize); % Normalize.
% Replicate filter if just a single SIGMA was specified.
if (length(sigma) == 1)
bordersize = repmat(bordersize,nim,1);
filter = repmat(filter,nim,1);
end
% Process all images...
if exist('gaussf') == 2
for i=1:nim
im(:,:,i) = double(gaussf(1*im(:,:,i),sigma));
end
else
for i = 1:nim
out = bord(im(:,:,i),NaN,bordersize(i)); % Add mirrored border.
out = conv2(filter(i,:),filter(i,:),out,'same'); % Convolve with filter.
im(:,:,i) = resize(out,bordersize(i),imheight,imwidth);
% Crop back to original size.
end
end
% Place filtered images back in dataset.
im = squeeze(im);
if (isfeatim(a))
a = setdata(a,im2feat(im),getfeatlab(a));
else
a = setdata(a,im2obj(im,getfeatsize(a)),getfeatlab(a));
end
return
|
github
|
jacksky64/imageProcessing-master
|
prforum.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prforum.m
| 94 |
utf_8
|
f268817c3db7b653655098ff868b5e86
|
%PRFORUM
%
% N = PRFORUM(L)
%
%PRTools test
function prforum(k)
prforum_private(k);
|
github
|
jacksky64/imageProcessing-master
|
qdc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/qdc.m
| 4,296 |
utf_8
|
4055290392ab0ff63272a6d4c54a5402
|
%QDC Quadratic Bayes Normal Classifier (Bayes-Normal-2)
%
% [W,R,S,M] = QDC(A,R,S,M)
% W = A*QDC([],R,S)
%
% INPUT
% A Dataset
% R,S Regularization parameters, 0 <= R,S <= 1
% (optional; default: no regularization, i.e. R,S = 0)
% M Dimension of subspace structure in covariance matrix (default: K,
% all dimensions)
%
% OUTPUT
% W Quadratic Bayes Normal Classifier mapping
% R Value of regularization parameter R as used
% S Value of regularization parameter S as used
% M Value of regularization parameter M as used
%
% DESCRIPTION
% Computation of the quadratic classifier between the classes of the dataset
% A assuming normal densities. R and S (0 <= R,S <= 1) are regularization
% parameters used for finding the covariance matrix by
%
% G = (1-R-S)*G + R*diag(diag(G)) + S*mean(diag(G))*eye(size(G,1))
%
% This covariance matrix is then decomposed as G = W*W' + sigma^2 * eye(K),
% where W is a K x M matrix containing the M leading principal components
% and sigma^2 is the mean of the K-M smallest eigenvalues.
%
%
%
% The use of soft labels is supported. The classification A*W is computed by
% NORMAL_MAP.
%
% If R, S or M is NaN the regularisation parameter is optimised by REGOPTC.
% The best result are usually obtained by R = 0, S = NaN, M = [], or by
% R = 0, S = 0, M = NaN (which is for problems of moderate or low dimensionality
% faster). If no regularisation is supplied a pseudo-inverse of the
% covariance matrix is used in case it is close to singular.
%
% EXAMPLES
% See PREX_MCPLOT, PREX_PLOTC.
%
% REFERENCES
% 1. R.O. Duda, P.E. Hart, and D.G. Stork, Pattern classification, 2nd
% edition, John Wiley and Sons, New York, 2001.
% 2. A. Webb, Statistical Pattern Recognition, John Wiley & Sons,
% New York, 2002.
%
% SEE ALSO
% MAPPINGS, DATASETS, REGOPTC, NMC, NMSC, LDC, UDC, QUADRC, NORMAL_MAP
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: qdc.m,v 1.8 2010/02/08 15:29:48 duin Exp $
function [w,r,s,dim] = qdc(a,r,s,dim)
prtrace(mfilename);
if (nargin < 4)
prwarning(4,'subspace dimensionality M not given, assuming K');
dim = [];
end
if (nargin < 3) | isempty(s)
prwarning(4,'Regularisation parameter S not given, assuming 0.');
s = 0;
end
if (nargin < 2) | isempty(r)
prwarning(4,'Regularisation parameter R not given, assuming 0.');
r = 0;
end
if (nargin < 1) | (isempty(a)) % No input arguments:
w = mapping(mfilename,{r,s,dim}); % return an untrained mapping.
elseif any(isnan([r,s,dim])) % optimize regularisation parameters
defs = {0,0,[]};
parmin_max = [1e-8,9.9999e-1;1e-8,9.9999e-1;1,size(a,2)];
[w,r,s,dim] = regoptc(a,mfilename,{r,s,dim},defs,[3 2 1],parmin_max,testc([],'soft'),[1 1 0]);
else % training
islabtype(a,'crisp','soft'); % Assert A has the right labtype.
isvaldfile(a,2,2); % at least 2 objects per class, 2 classes
[m,k,c] = getsize(a);
% If the subspace dimensionality is not given, set it to all dimensions.
if (isempty(dim)), dim = k; end;
dim = round(dim);
if (dim < 1) | (dim > k)
error ('Number of dimensions M should lie in the range [1,K].');
end
[U,G] = meancov(a);
% Calculate means and priors.
pars.mean = +U;
pars.prior = getprior(a);
% Calculate class covariance matrices.
pars.cov = zeros(k,k,c);
for j = 1:c
F = G(:,:,j);
% Regularize, if requested.
if (s > 0) | (r > 0)
F = (1-r-s) * F + r * diag(diag(F)) +s*mean(diag(F))*eye(size(F,1));
end
% If DIM < K, extract the first DIM principal components and estimate
% the noise outside the subspace.
if (dim < k)
dim = min(rank(F)-1,dim);
[eigvec,eigval] = preig(F); eigval = diag(eigval);
[dummy,ind] = sort(-eigval);
% Estimate sigma^2 as avg. eigenvalue outside subspace.
sigma2 = mean(eigval(ind(dim+1:end)));
% Subspace basis: first DIM eigenvectors * sqrt(eigenvalues).
F = eigvec(:,ind(1:dim)) * diag(eigval(ind(1:dim))) * eigvec(:,ind(1:dim))' + ...
sigma2 * eye(k);
end
pars.cov(:,:,j) = F;
end
w = normal_map(pars,getlab(U),k,c);
w = setcost(w,a);
end
w = setname(w,'Bayes-Normal-2');
return;
|
github
|
jacksky64/imageProcessing-master
|
roc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/roc.m
| 5,483 |
utf_8
|
8d0022cbb75dfc2d81a59beca6ddc7b7
|
%ROC Receiver-Operator Curve
%
% E = ROC(A,W,C,N)
% E = ROC(B,C,N)
%
% INPUT
% A Dataset
% W Trained classifier, or
% B Classification result, B = A*W*CLASSC
% C Index of desired class (default: C = 1)
% N Number of points on the Receiver-Operator Curve (default: 100)
%
% OUTPUT
% E Structure containing the error of the two classes
%
% DESCRIPTION
% Computes N points on the receiver-operator curve of the classifier W for
% class C in the labeled dataset B, which is typically the result of
% B = A*W; or for the dataset A labelled by applying the (cell array of)
% trained classifiers W.
%
% Note that a Receiver-Operator Curve is related to a specific class (class C)
% for which the errors are plotted horizontally. The total error on all other
% classes is plotted vertically. The class index C refers to its position in
% the label list of the dataset (A or B). It can be found by GETCLASSI.
%
% The curve is computed for N thresholds of the posteriori probabilities
% stored in B. The resulting error frequencies for the two classes are
% stored in the structure E. E.XVALUES contains the errors in the first
% class, E.ERROR contains the errors in the second class. In multi-class
% problems these are the mean values in a single class, respectively the
% mean values in all other classes. This may not be very useful, but not
% much more can be done as for multi-class cases the ROC is equivalent to a
% multi-dimensional surface.
%
% Use PLOTE(E) for plotting the result. In the plot the two types of error
% are annotated as 'Error I' (error of the first kind) and 'Error II' (error
% of the second kind). All error estimates are weighted according the class
% prior probabilities. Remove the priors in A or B (by setprior(A,[])) to
% produce a vanilla ROC.
%
% EXAMPLES
% Train set A and test set T:
% B = T*NMC(A); E = ROC(T,50); PLOTE(E); % Plots a single curve
% E = ROC(T,A*{NMC,UDC,QDC}); PLOTE(E); % Plots 3 curves
%
% REFERENCES
% 1. R.O. Duda, P.E. Hart, and D.G. Stork, Pattern classification, 2nd edition,
% John Wiley and Sons, New York, 2001.
% 2. A. Webb, Statistical Pattern Recognition, John Wiley & Sons, New York,
% 2002.
%
% SEE ALSO
% DATASETS, MAPPINGS, PLOTE, REJECT, TESTC, GETCLASSI
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: roc.m,v 1.8 2009/07/09 14:17:38 davidt Exp $
function e = roc(a,w,clas,n)
% Depending on the call, CLAS may the third or second argument.
% and N the third or the fourth.
if nargin < 4, n = []; end
if nargin < 3, clas= []; end
if nargin < 2, w = []; end
if nargin < 1, a= []; end
if isempty(a)
e = mapping('roc','fixed',{w,clas,n});
return;
end
name = [];
num_w = 1;
compute = 0;
if isa(w,'double') | isempty(w)
n = clas;
clas = w;
b = a;
elseif iscell(w)
num_w = length(w);
compute = 1;
elseif ismapping(w)
istrained(w);
b = a*w*classc;
name = getname(w);
else
error('Classifier or cell array of classifiers expected.')
end
if isempty(n),
n = 100;
prwarning(4,'number of ROC points not given, assuming 100');
end
if isempty(clas)
clas = 1;
prwarning(4,'no class given, class 1 assumed');
end
p = getprior(a);
datname = getname(a);
lablist = getlablist(a,'string');
if size(lablist,1)<2
error('At least two classes should be present for computing the ROC curve.');
end
if clas > size(lablist,1)
error('Wrong class number')
end
clasname= lablist(clas,:);
%DXD: also check the class sizes:
cs = classsizes(a);
if cs(clas)==0
error(['Class ',clas,' does not contain objects.']);
end
cs(clas) = 0;
if sum(cs)==0
error(['One of the classes does not contain objects.']);
end
% Set up the ROC structure.
e.error = zeros(num_w,n+1);
e.std = zeros(num_w,n+1);
e.xvalues = [0:n]/n;;
e.n = 1;
e.xlabel = 'Error I';
e.ylabel = 'Error II';
e.plot = 'plot';
e.names = name;
if (~isempty(datname))
e.title = ['ROC curve for the ' datname ', class ' clasname];
end
for j = 1:num_w
thr = []; % Threshold range, will be set below.
% If a cell array of classifiers was given, apply each one here.
if (compute)
v = w{j};
if (~istrained(v))
error('The supplied classifier mappings should be trained.')
end
b = a*v*classc;
e.names = char(e.names,getname(v));
else
b = b*normm; % make sure we have a normalised classification matrix
end
[m,c] = size(b); nlab = getnlab(b); d = sort(b(:));
% Attempt to compute a good threshold range on the first classified
% dataset.
if (isempty(thr))
thr = [min(d)-eps d(ceil(([1:n-1]/(n-1))*m*c))' 1];
end
e1 = []; e2 = [];
% NLAB_OUT will be one where B is larger than THR.
I = matchlablist(getlablist(b),getfeatlab(b)); % Correct possible changes class orders
nlab_out = (repmat(+b(:,I(clas)),1,n+1) >= repmat(thr,m,1));
% ERRS will be 1 where the numeric label is unequal to NLAB_OUT
% (i.e., where errors occur).
errs = (repmat((nlab==clas),1,n+1) ~= nlab_out);
% Split the cases where ERRS = 1 into cases for CLAS (E1) and all
% other classes (E2).
e1 = [mean(errs(find(nlab==clas),:),1)];
e2 = [mean(errs(find(nlab~=clas),:),1)];
% Fill results in the ROC structure.
e.error(j,:) = e2;
e.xvalues(j,:) = e1;
end
% First name will be the empty string [], remove it.
if (num_w > 1)
e.names(1,:) = [];
end
return
|
github
|
jacksky64/imageProcessing-master
|
myfixedmapping.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/myfixedmapping.m
| 3,358 |
utf_8
|
d32084aeb276bb7537cce545039c805b
|
%MYFIXEDMAPPING Skeleton for a user supplied mapping
%
% W = MYFIXEDMAPPING([],PAR]
% W = MYFIXEDMAPPING
% B = A*MYFIXEDMAPPING
% B = A*MYFIXEDMAPPING([],PAR]
% B = MYFIXEDMAPPING(A,PAR)
%
% INPUT
% A Dataset
% PAR Parameter
%
% OUTPUT
% W Mapping definition
% B Dataset A mapped by MYFIXEDMAPPING
%
% DESCRIPTION
% This is a fake routine just offering the skeleton of a user supplied
% fixed mapping. By changing the lines indicated in the source and renaming
% the routine user may program their own mapping. The routine as it is just
% selects the features (columns of A) as defined in PAR.
%
% SEE ALSO
% DATASETS, MAPPINGS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function OUT = myfixedmapping(A,PAR)
% take care that there is always a second parameter, even if you don't
% need it, PRTools will.
% define here the default values for all parameters. Defaults might be
% empty ([]), but the routine should then test on that if the parameter
% is used.
if (nargin < 2)
PAR = [];
end
% determine the type of call
if (nargin == 0) | (isempty(A))
% we are here if the routine is called by W = myfixedmapping, or by
% W = myfixedmapping([],PAR)
% this is a definition call. So we need to return a fixed mapping
OUT = mapping(mfilename,'fixed',{PAR});
% the first parameter in the above call is the name of the routine that
% should handle the mapping when it is called with data. Usually this
% is this routine. Its name is returned by mfilename.
% The third parameter is cell array containing all parameters of the
% call. Defaults should be substituted.
OUT = setname(OUT,'Fixed Mapping Skeleton');
% Here just a name is supplied for your own information. It is
% displayed when you call the routine without a ';'
else
% now we have a normal call with a dataset A and parameter PAR.
% Let us first check the inputs
isdataset(A); % returns an error if A is not a dataset
% checking parameter values depends on the mapping we want to
% implement. In our fake example it should be in the range of feature
% numbers. If there are still empty parameter values they should be
% given a sensible value here.
if isempty(PAR)
% select all features by defaults (i.e. do nothing)
PAR = [1:size(A,2)];
end
if any(PAR < 1) | any(PAR > size(A,2))
% Features to be selected should be in a proper range
error('Feature number out of range')
end
% now the mapping itself should be programmed. We can simpy put
% OUT = A(:,PAR);
% but sometimes operations on the data stored in the dataset are needed
% that cannot be done within PRTools. The following serves as an
% example on how this might be done.
data = getdata(A); % isolate the data from the dataset
data = data(:,PAR); % do whatever is needed. Replace this line by what
% is needed for defining the desired operation of
% myfixedmapping
OUT = setdata(A,data); % resubstitute the resulting data into the
% original data structure of A. The resulting
% dataset has thereby the same name, user- and
% ident-fields as input dataset.
end
return
|
github
|
jacksky64/imageProcessing-master
|
prwaitbaronce.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prwaitbaronce.m
| 903 |
utf_8
|
a3e428983a44e7ed0cab38cf4eac163c
|
%PRWAITBARONCE Generate single prwaitbar message
%
% PRWAITBARONCE(STRING,PAR)
%
% INPUT
% STRING - String with text to be written in the waitbar,
% e.g. '%i x %i eigenvalue decomposition: '.
% This will be parsed by S = SPRINTF(STRING,PAR{:});
% PAR - scalar or cell array with parameter values
%
% This routine has to be used in combination with PRWAITBAR(0), e.g.:
%
% prwaitbaronce('%i x %i eigenvalue decomposition ... ',{n,n})
% [Q,L] = eig(H);
% prwaitbar(0)
%
% It makes clear to the user what is happening.
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function prwaitbaronce(ss,par)
if nargin < 2
prwaitbar(2,ss);
elseif ~iscell(par)
prwaitbar(2,sprintf(ss,par));
else
prwaitbar(2,sprintf(ss,par{:}));
end
return
|
github
|
jacksky64/imageProcessing-master
|
stamp_map.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/stamp_map.m
| 4,244 |
utf_8
|
63bbd553d399602bb1ab73c0929db82d
|
%STAMP_MAP Stamping and storing of mappings for fast reusage
%
% C = STAMP_MAP(A,W) or C = A*W
% U = STAMP_MAP(V,W) or U = V*W
%
% This routine is equivalent to MAP except that it stores previous
% results (C or U) and retrieves them when the same inputs (A and W
% or V and W) are given. This is especially good in case of combining
% classifier studies when the same mappings have to be computed multiple
% times.
%
% Note that only the highest level of calls to MAP are stored by STAMP_MAP.
% If multiple calls to lower level calls (e.g. somewhere included in a
% complicated combined classifier) are expected, they should be called
% first explicitely.
%
% STAMP_MAP is automatically called inside MAP (and thereby by every
% overloaded * operation between datasets and mappings) controlled by
% the following settings:
%
% STAMP_MAP(0) - disables all storage and retrieval of mappings.
% This should be called when no duplicates are expected
% as it prevents the unnecessary checking of inputs.
% STAMP_MAP(1) - Retrieving of stored results only only.
% No new results are stored.
% STAMP_MAP(2) - Enables retrieval as well as storage of results.
%
% SEE ALSO
% DATASETS, MAPPINGS, MAP
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function c = stamp_map(a,b)
persistent CHECK_STAMPS nstamps cell_stamp stamps
if isempty(CHECK_STAMPS)
CHECK_STAMPS = 0;
nstamps = 0;
stamps = zeros(1000,3);
cell_stamp = cell(1,1000);
end
if nargin == 0
c = CHECK_STAMPS;
elseif nargin == 1
if a < 3
CHECK_STAMPS = a;
if nargout > 0
c = a;
end
else
disp(nstamps)
for j=1:nstamps
fprintf('STAMPS: %10.6e %10.6e: ',stamps(j,:));
cell_stamp{j}
end
end
else
if CHECK_STAMPS == 0 % checking is off, no stamp_mapping
c = []; % execution call: try to pass this routine
elseif iscell(a) | iscell(b) % don't handle cell constructs
c = [];
elseif CHECK_STAMPS == 1 | CHECK_STAMPS == 2 % checking is on
sa = getstamp(a);
sb = getstamp(b);
Ja = find(stamps(1:nstamps,1)==sa);
J = [];
if ~isempty(Ja)
Jb = find(stamps(Ja,2)==sb);
if ~isempty(Jb) % found, we have it!
J = Ja(Jb);
if ~isempty(J) & length(J) > 1
error('Stamps are not unique')
end
c = cell_stamp{J}; % use it!
stamps(J,3) = stamps(J,3)+1;
%disp(['found: ' getname(a) '..,..' getname(b)])
end
end
if isempty(J) % not found, let map do the work
checkstamps = CHECK_STAMPS; % Take care that we skip stamp_map
CHECK_STAMPS = checkstamps+2; % when we call map
c = map(a,b); % during execution of map CHECK_STAMPS will be reset
CHECK_STAMPS = checkstamps; % so this is in fact not needed
if CHECK_STAMPS == 2 % store as well
%disp(['stored: ' getname(a) '..,..' getname(b)])
nstamps = nstamps + 1;
if nstamps > length(cell_stamp)
stamps = [stamps; zeros(1000,3)];
cell_stamp = [cell_stamp cell(1,1000)];
end
stamps(nstamps,1:2) = [sa,sb];
cell_stamp{nstamps} = c;
end
end
elseif CHECK_STAMPS == 3 | CHECK_STAMPS == 4
CHECK_STAMPS = CHECK_STAMPS-2; % reset of computation of map
c = [];
else
;
end
end
return
%GETSTAMP Compute unique stamp for data
%
% S = GETSTAMP(A)
%
%Computes 64-bit stamp S of input A
function s = getstamp(a)
s = 0;
type = class(a);
switch(type)
case 'char'
a = abs(a);
n = length(a(:));
s = s + abs(sin(1:n))*(a(:));
case 'double'
n = length(a(:));
s = s + abs(sin(1:n)*a(:));
case {'mapping','dataset','datafile'}
a = struct2cell(struct(a));
s = s + getstamp(a);
case 'struct'
a = struct2cell(a);
s = s + getstamp(a);
case 'cell'
for j=1:length(a(:))
s = s + getstamp(a{j});
end
otherwise
try
n = length(a(:));
s = s + abs(sin(1:n))*abs(double(a(:)));
catch
;
end
end
|
github
|
jacksky64/imageProcessing-master
|
featselv.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featselv.m
| 1,072 |
utf_8
|
c4a82524f1333db4a149ebaf8e45203b
|
%FEATSELV Varying feature selection
%
% W = FEATSELV(A)
% W = A*FEATSELV
%
% Selects all features with a non-zero variance.
% Classifiers can be trained like A*(FEATSELV*LDC([],1E-3)) to make
% use of this feature selection
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELO, FEATSELB, FEATSELF,
% FEATSEL, FEATSELP, FEATSELM, FEATSELI
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = featselv(a)
prtrace(mfilename);
% If no arguments are supplied, return an untrained mapping.
if (nargin == 0) | (isempty(a))
w = mapping('featselv');
else
[m,k,c] = getsize(a);
featlist = getfeatlab(a);
v = std(+a);
J = find(v > 1e-6 & v < 1e6);
if isempty(J)
error('All objects are equal')
end
% Return the mapping found.
w = featsel(k,J);
if ~isempty(featlist)
w = setlabels(w,featlist(J,:));
end
end
w = setname(w,'Varying FeatSel');
return
|
github
|
jacksky64/imageProcessing-master
|
isvaldfile.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isvaldfile.m
| 2,064 |
utf_8
|
add4fdfc5794d47ac7f0165a39792c80
|
%ISVALDFILE Test whether the argument is a valid datafile or dataset
%
% N = ISVALDFILE(A);
% N = ISVALDFILE(A,M);
% N = ISVALDFILE(A,M,C);
%
% INPUT
% A Input argument, to be tested on datafile or dataset
% M Minimum number of objects per class in A
% C Minimum number of classes in A
%
% OUTPUT
% N 1/0 if A is / isn't a valid datafile or dataset
%
% DESCRIPTION
% The function ISVALDFILE tests if A is a datafile or dataset that has
% at least C classes. It is an extension of ISVALDSET and can be used it
% when datasets as well as datafiles are allowed.
% For datafiles(sets) with soft or targets labels it is tested whether A
% has at least M objects.
%
% SEE ALSO
% ISDATASET, ISMAPPING, ISDATAIM, ISFEATIM, ISCOMDSET, ISVALDSET
function n = isvaldfile(a,m,c)
prtrace(mfilename);
if nargin < 3 | isempty(c), c = 0; end
if nargin < 2 | isempty(m), m = 0; end
if nargout == 0
if ~isdatafile(a)
isdataset(a);
end
else
n = 1;
if ~isdatafile(a) & ~isdataset(a)
n = 0;
return
end
end
if c == 1 & getsize(a,3) == 0
; % accept unlabeled dataset as having one class
elseif c > 0 & getsize(a,3) == 0
if nargout == 0
error([newline 'Labeled datafile(set) expected'])
else
n = 0;
end
elseif getsize(a,3) < c
if nargout == 0
error([newline 'Datafile(set) should have at least ' num2str(c) ' classes'])
else
n = 0;
end
end
if islabtype(a,'crisp') & any(classsizes(a) < m)
if nargout == 0
if m == 1
error([newline 'Classes should have at least one object.' newline ...
'Remove empty classes by A = remclass(A).'])
else
cn = num2str(m);
error([newline 'Classes should have at least ' cn ' objects.' ...
newline 'Remove small classes by A = remclass(A,' cn ')'])
end
else
n = 0;
end
end
if islabtype(a,'soft','targets') & size(a,1) < m
error([newline 'Datafile(set) should have at least ' num2str(m) ' objects'])
end
return
|
github
|
jacksky64/imageProcessing-master
|
prrank.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prrank.m
| 359 |
utf_8
|
bd7b267f3361cdd10b064e53104abc0b
|
%PRRANK Call to RANK() including PRWAITBAR
%
% B = PRRANK(A,tol)
%
% This calls B = RANK(A,tol) and includes a message to PRWAITBAR
% in case of a large A
function B = prrank(varargin)
[m,n] = size(varargin{1});
if min([m,n]) >= 500
prwaitbaronce('Rank of %i x %i matrix ...',[m,n]);
B = rank(varargin{:});
prwaitbar(0);
else
B = rank(varargin{:});
end
|
github
|
jacksky64/imageProcessing-master
|
prprogress.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prprogress.m
| 2,167 |
utf_8
|
45837f238a625e60b78f5cb0f8f737ca
|
%PRPROGRESS Report progress of some PRTools iterative routines
%
% PRPROGRESS ON
%
% All progress of all routines will be written to the command window.
%
% PRPROGRESS(FID)
%
% Progress reports will be written to the file with file descriptor FID.
%
% PRPROGRESS(FID,FORMAT,...)
%
% Writes progress message to FID. If FID == [], the predefined destination
% (command window or file) is used.
%
% PRPROGRESS OFF
% PRPROGRESS(0)
%
% Progress reporting is turned off.
%
% PRPROGRESS
%
% Toggles between PRPROGRESS ON and PRPROGRESS OFF
%
% FID = PRPROGRESS
%
% Retrieves the status of PRPROGRESS
%
% Some routines (e.g. CLEVAL) have a switch in the function call by which
% progress reporting for that routine only can be initiated.
%
% By default, PRPROGRESS is switched off. Interactive progress tracing can
% be best following by PRWAITBAR
%
% SEE ALSO
% PRWAITBAR
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function fid = prprogress(par,varargin)
persistent GLOBALPRPROGRESS
mlock; % prevents GLOBALPRPROGRESS being cleared by CLEAR ALL
if isempty(GLOBALPRPROGRESS)
GLOBALPRPROGRESS = 0;
end
if nargin == 0
if nargout == 0
if GLOBALPRPROGRESS ~= 0,
GLOBALPRPROGRESS = 0;
else
GLOBALPRPROGRESS = 1;
end
else
fid = GLOBALPRPROGRESS;
end
elseif nargin == 1 & nargout == 0
if isstr(par)
switch par
case {'on','ON'}
GLOBALPRPROGRESS = 1;
case {'off','OFF'}
GLOBALPRPROGRESS = 0;
otherwise
error('Illegal input for PRPROGRESS')
end
else
GLOBALPRPROGRESS = par;
end
elseif (GLOBALPRPROGRESS > 0) & (~isempty(par)) & (par>0) %DXD, fid=0 means no printing...
s = sprintf(varargin{:});
n = fprintf(par,s);
if nargout > 0
fid = length(s);
end
elseif GLOBALPRPROGRESS > 0
s = sprintf(varargin{:});
n = fprintf(GLOBALPRPROGRESS,s);
if nargout > 0
fid = length(s);
end
else
if nargout > 0
fid = 0;
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
renumlab.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/renumlab.m
| 5,523 |
utf_8
|
ac9d5150e678debdb0b3b1bbdc792d64
|
%RENUMLAB Renumber labels
%
% [NLAB,LABLIST] = RENUMLAB(LABELS)
% [NLAB1,NLAB2,LABLIST] = RENUMLAB(LABELS1,LABELS2)
%
% INPUT
% LABELS,LABELS1,LABELS2 Array of labels
%
% OUTPUT
% NLAB,NLAB1,NLAB2 Vector of numeric labels
% LABLIST Unique labels
%
% DESCRIPTION
% If a single array of labels LABELS is supplied, it is converted and
% renumbered to a vector of numeric labels NLAB. The conversion table
% LABLIST is such that LABELS = LABLIST(NLAB,:). When two arrays LABELS1
% and LABELS2 are given, they are combined into two numeric label vectors
% NLAB1 and NLAB2 with a common conversion table LABLIST.
%
% Note that numeric labels with value -inf or NaN and string labels CHAR(0)
% are interpreted as missing labels. Their entry in NLAB will be 0 and they
% will not have an entry in LABLIST.
%
% A special command is
%
% NLAB = RENUMLAB(LABELS,LABLIST)
%
% which returns the indices of LABELS in a given LABLIST.
%
% SEE ALSO
% DATASET
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: renumlab.m,v 1.7 2009/01/04 22:18:57 duin Exp $
function [out1,out2,out3] = renumlab(slab1,slab2)
prtrace(mfilename);
out1 = []; out2 = []; out3 = [];
% Obsolete call?
if (isempty(slab1)) & (nargin == 1 | isempty(slab2))
return
end
% Clean up the symbolic labels.
slab1 = clean_lab(slab1);
if (nargin == 1) | (isempty(slab2))
% Find unique labels for LABLIST and indices into LABLIST for NLAB.
[lablist,dummy,nlab] = unique(slab1,'rows');
% Remove "missing label", if present.
[lablist,nlab] = remove_empty_label(lablist,nlab);
% Set output arguments.
out1 = nlab; out2 = lablist;
elseif nargout > 1 | nargin == 1
% Check whether SLAB1 and SLAB2 match in type.
if (isstr(slab1) ~= isstr(slab2))
error(['Label lists do not match.' ...
newline 'They should be both characters, strings or numbers'])
end
% Clean up SLAB2 and put the union of SLAB1 and SLAB2 into SLAB.
slab2 = clean_lab(slab2);
if isstr(slab1), slab = char(slab1,slab2); else, slab = [slab1;slab2]; end
% Find unique labels for LABLIST and indices into LABLIST for NLAB.
if (iscell(slab))
[lablist,dummy,nlab] = unique(slab);
else
[lablist,dummy,nlab] = unique(slab,'rows');
end;
% Remove "missing label", if present.
[lablist,nlab] = remove_empty_label(lablist,nlab);
% Set output arguments.
out1 = nlab(1:size(slab1,1)); % Renumbered SLAB1 labels
out2 = nlab(size(slab1,1)+1:end); % Renumbered SLAB2 labels
out3 = lablist;
else % nargout == 1 & nargin > 1, call like nlab = renumlab(labels,lablist)
[k2,s2] = feval(mfilename,slab2);
[n1,n2,s12] = feval(mfilename,slab1,slab2);
% This gives a headache, but it seems to work
R = zeros(size(s12,1),1); % zeros for all possible labels
J = find(n2~=0);
R(n2(J)) = J; % substitute the existing ones
J = find(n1~=0);
out1 = zeros(length(n1),1); % space for output
out1(J) = R(n1(J)); % replace existing ones by their index in lablist
% pffft !!!!
if 0
if size(s12,1) > size(s2,1) % some labels are not in lablist
% This gives a headache, but it seems to work
S = zeros(max([n1;n2]),1); % zeros for all possible labels
R = S;
R(n2) = [1:length(n2)]; % substitute the existing ones
S(n2) = n2; % all indices zeros, except the existing ones
n1 = S(n1); % replace non-existing ones by zeros
J = find(n1~=0); % these are the existing ones
out1 = zeros(length(n1),1); % space for output
out1(J) = R(n1(J)); % replace existing ones by their index in lablist
% pffft !!!!
else
% easy!
J = find(~isnan(n2));
[nn2,listn2] = sort(n2(J));
out1 = zeros(length(n2),1);
out1(J) = listn2(n1(J));
%alternative version
%what is above seems not always working
%J = find(n2~=0);
%[nn2,listn2] = sort(n2(J));
%listn2 = J(listn2);
%J = find(n1~=0);
%out1 = zeros(length(n1),1);
%out1(J) = listn2(n1(J));
end
end
end
return
% LAB = CLEAN_LAB(LAB)
%
% Clean labels; for now, just replaces occurences of NaN in numeric labels
% by -inf (both denoting "missing labels").
function slab = clean_lab(slab)
if (iscell(slab)) % Cell array of labels.
;
elseif isempty(slab)
;
elseif (size(slab,2) == 1) & (~isstr(slab)) % Vector of numeric labels.
J = isnan(slab);
slab(J) = -inf;
elseif (isstr(slab)) % Array of string labels.
;
else
error('labels should be strings or scalars')
end
return
% [LABLIST,NLAB] = REMOVE_EMPTY_LABEL (LABLIST,NLAB)
%
% Removes the empty first label from LABLIST and NLAB (corresponding to the
% "missing label"), if present.
function [lablist,nlab] = remove_empty_label (lablist,nlab)
% Find occurences of '' (in cell array label lists), '\0' (in string
% label lists) or -inf (in numeric label lists) and remove them.
if (iscellstr(lablist)) % Cell array of labels.
if (strcmp(lablist{1},'')), lablist(1) = []; nlab = nlab -1; end
elseif (isstr(lablist)) % Array of string labels.
if (strcmp(lablist(1,:),char(0))) | isempty(deblank(lablist(1,:)))
lablist(1,:) = []; nlab = nlab -1;
end
else
% Vector of numeric labels.
if (lablist(1) == -inf), lablist(1) = []; nlab = nlab -1; end
end
return
|
github
|
jacksky64/imageProcessing-master
|
rbnc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rbnc.m
| 3,564 |
utf_8
|
9664c09d16c78330d2de8a63f79b3fe0
|
%RBNC Radial basis function neural network classifier
%
% W = RBNC(A,UNITS)
%
% INPUT
% A Dataset
% UNITS Number of RBF units in hidden layer
%
% OUTPUT
% W Radial basis neural network mapping
%
% DESCRIPTION
% A feed-forward neural network classifier with one hidden layer with
% UNITS radial basis units is computed for labeled dataset A.
% Default UNITS is number of objects * 0.2, but not more than 100.
% Uses the Mathworks' Neural Network toolbox.
%
% If UNITS is NaN it is optimised by REGOPTC. This may take a long
% computing time and is often not significantly better than the default.
%
% This routine calls MathWork's SOLVERB routine (Neural Network toolbox)
% as SOLVB.
%
% SEE ALSO
% MAPPINGS, DATASETS, LMNC, BPXNC, NEURC, RNNC, REGOPTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: rbnc.m,v 1.4 2007/06/19 11:45:08 duin Exp $
function w = rbnc(a,units)
prtrace(mfilename);
if exist('nnet') ~= 7
error('Neural network toolbox not found')
end
if nargin < 2, units = []; end
if (nargin <1) | isempty(a)
% Create an empty mapping:
w = mapping(mfilename,units);
w = setname(w,'RBF Neural Network');
return
end
if isempty(units)
units = min(ceil(size(a,1)/5),100);
prwarning(2,['no number of hidden units specified, assuming ' num2str(units)]);
end
if isnan(units) % optimize complexity parameter: number of neurons
defs = {[]};
parmin_max = [1,30];
w = regoptc(a,mfilename,{units},defs,[1],parmin_max,testc([],'soft'),0);
return
end
if units > size(a,1)
error('Number of hidden units should not increase datasize')
end
% Training target values.
target_low = 0.1;
target_high = 0.9;
islabtype(a,'crisp');
isvaldfile(a,2,2); % at least 2 objects per class, 2 classes
a = testdatasize(a);
[m,k,c] = getsize(a); nlab = getnlab(a);
% Set standard training parameters.
disp_freq = inf; % Display interval: switch off
err_goal = 0.005*m; % Sum squared error goal, stop if reached
sigma = 0.5; % RBF kernel width
% Create target matrix: row C contains a high value at position C,
% the correct class, and a low one for the incorrect ones (place coding).
target = target_low * ones(c,c) + (target_high - target_low) * eye(c);
target = target(nlab,:)';
% Shift and scale the training set to zero mean, unit variance.
ws = scalem(a,'variance');
% Add noise to training set, as SOLVB sometimes has problems with
% identical inputs.
r = randn(m,k) * 1e-6;
% Compute RBF network.
% RD I changed the below call from NEWRBE() to NEWRB() and added
% the number of units as parameter. NEWRBE always uses M units
% net = newrb(+(a*ws)'+r',target,sigma);
net = newrb(+(a*ws)'+r',target,0,sigma,units,inf);
weight1 = net.IW{1,1}; weight2 = net.LW{2,1};
bias1 = net.b{1}; bias2 = net.b{2};
n_hidden_units = length(bias1);
% Construct resulting map. First apply the shift and scale mapping WS.
% The first layer then calculates EXP(-D), where D are the squared
% distances to RBF kernel centers, scaled by the biases.
w = ws*proxm(weight1,'distance',2); % RBF distance map
w = w*cmapm(bias1'.^(-2),'scale'); % Multiply by scale (sq. bias)
w = w*cmapm(n_hidden_units,'nexp'); % Take negative exponential
% Second layer is affine mapping on output of first layer, followed
% by a sigmoid mapping.
w = nodatafile*w*affine(weight2',bias2',[],getlablist(a))*sigm;
w = setname(w,'RBF Neural Classf');
return
|
github
|
jacksky64/imageProcessing-master
|
prdataset.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prdataset.m
| 2,177 |
utf_8
|
62381781251a635adbb3dbd86682f0e3
|
%PRDATASET Load and convert dataset from disk
%
% A = PRDATASET(NAME,M,N)
%
% The dataset given in NAME is loaded from a .mat file and converted
% to the current PRTools definition. Objects and features requested
% by the index vectors M and N are returned.
%
% See PRDATA for loading arbitrary data into a PRTools dataset.
% See PRDATASETS for an overview of datasets.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: prdataset.m,v 1.3 2009/12/21 10:35:12 duin Exp $
function a = prdataset(name,M,N,no_message)
prtrace(mfilename);
persistent FIRST;
if isempty(FIRST), FIRST = 1; end
if nargin < 4, no_message = 0; end
if nargin < 3, N = []; end
if nargin < 2, M = []; end
if exist([name '.mat']) ~= 2
error([newline '---- Dataset ''' name ''' not available ----'])
end
s = warning;
warning off
b = load(name);
warning(s);
% Try to find out what data we actually loaded:
names = fieldnames(b);
eval(['a = b.' names{1} ';']);
if ~isdataset(a) & ndims(a) > 2
% We loaded an image?
a = im2feat(a);
prwarning(2,'Assumed that a feature image is loaded')
else
a = dataset(a);
end
[m,k] = size(a);
% Maybe a subset of the features is requested:
if ~isempty(N)
if min(size(N)) ~= 1
error([newline 'Feature indices should be stored in vector'])
end
if max(N) > k
error([newline 'Dataset has not the requested features'])
end
a = a(:,N);
end
% Maybe a subset of the objects are requested:
if ~isempty(M)
if min(size(M)) ~= 1
error([newline 'Object indices should be stored in vector'])
end
if max(M) > m
error([newline 'Dataset has not the requested objects'])
end
a = a(M,:);
end
if FIRST & ~no_message
disp(' ')
disp('*** You are using one of the datasets distibuted by PRTools. Most of them')
disp('*** are publicly available on the Internet and converted to the PRTools')
disp('*** format. See the Contents of the datasets directory (HELP PRDATASETS)')
disp('*** or the load routine of the specific dataset to retrieve its source.')
disp(' ')
FIRST = 0;
end
return
|
github
|
jacksky64/imageProcessing-master
|
distmaha.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/distmaha.m
| 2,996 |
utf_8
|
dea417eab0552e74f75db3c579415a17
|
%DISTMAHA Mahalanobis distance
%
% D = DISTMAHA (A,U,G)
%
% INPUT
% A Dataset
% U Mean(s) (optional; default: estimate on classes in A)
% G Covariance(s) (optional; default: estimate on classes in A)
%
% OUTPUT
% D Mahalanobis distance matrix
%
% DESCRIPTION
% Computes the M*N Mahanalobis distance matrix of all vectors in M*K dataset
% A to an N*K dataset of points U, using the covariance matrix or matrices
% G. G should be either be one K*K matrix, or a K*K*N matrix containing a
% covariance matrix for each point in U.
%
% When U and G are not specified, it estimates the C*C Mahalanobis distance
% matrix between all classes in A: the distance between the means,
% relative to the average per-class covariance matrix.
%
% SEE ALSO
% DATASETS, DISTM, PROXM, MEANCOV
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: distmaha.m,v 1.4 2010/02/08 15:31:48 duin Exp $
function d = distmaha (a,u,g)
prtrace(mfilename);
[m,k,c] = getsize(a);
a = testdatasize(a);
a = testdatasize(a,'features');
if (nargin == 1)
% Calculate Mahalanobis distance matrix between classes in dataset:
% the distance matrix between the class means, sphered using the
% average covariance matrix of the per-class centered data.
u = zeros(c,k);
for i = 1:c
J = findnlab(a,i);
if (~isempty(J))
% Mean of class I.
u(i,:) = mean(a(J,:),1);
% Remove class mean, for later covariance calculation.
a(J,:) = a(J,:) - repmat(+u(i,:),length(J),1);
end
end
% Sphere means and calculate distance matrix.
[E,V] = preig(covm(a)); u = u*E*sqrt(prinv(V));
d = distm(u);
elseif (nargin == 2)
% Calculate Euclidean distance between data and means.
prwarning(4,'covariance matrix not specified, assuming G = I');
d = distm(a,u);
elseif (nargin == 3)
% Calculate distance between A and distributions specified by U and G.
% Check arguments.
[kg1,kg2,cg] = size(g); [cu,ku] = size(u);
if any([kg1,kg2,ku] ~= k) | (cu ~= cg & cg ~= 1)
error('sizes of mean(s) and covariance(s) do not match')
end
% Get labels of means if present, or assign labels 1:N. These are
% only used in the construction of the dataset D.
if (isa(u,'dataset')), labels = getlab(u); else, labels = [1:cu]'; end
% If there is only one covariance matrix, invert it here.
if (cg == 1), g_inv = prinv(g); end
d = zeros(m,cu);
for j = 1:cu
% If each mean has its own covariance matrix, invert it here.
if (cg ~= 1), g_inv = prinv(g(:,:,j)); end
% And calculate the standard Mahalanobis distance.
d(:,j) = sum((a-repmat(+u(j,:),m,1))'.*(g_inv*(a-repmat(+u(j,:),m,1))'),1)';
end
% Construct the distance matrix dataset.
d = setdata(a,d,labels);
d = setname(d,'Maha Dist');
else
error('incorrect number of arguments')
end
return
|
github
|
jacksky64/imageProcessing-master
|
selectim.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/selectim.m
| 1,152 |
utf_8
|
3422b0b2161ddca7f72bcf27039e7cb3
|
%SELECTIM Select one or more images in multiband image or dataset
%
% B = SELECTIM(A,N)
% B = A*SELECTIM([],N)
%
% INPUT
% A Multiband image or dataset containing multiband images
% N Vector or scalar pointing to desired images
%
% OUTPUT
% B New, reduced, multiband image or dataset
%
% This function is obsolete. Use the more general command BANDSEL instead.
function b = selectim(a,n)
if nargin < 2, n = 1; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{n})
b = setname(b,'SelectImage');
return
end
if isdataset(a)
im = data2im(a);
if ndims(im) < 3 | ndims(im) > 4
error('3D images expected')
elseif ndims(im) == 3
im = im(:,:,n);
else
im = im(:,:,n,:);
end
fsize = size(im);
if isobjim(a)
b = setdat(a,im2obj(im,fsize(1:3)));
b = setfeatsize(b,fsize(1:3));
else
b = im2feat(im);
end
elseif isdatafile(a)
b = a*filtm([],'selectim',n);
elseif isa(a,'double')
if ndims(a) ~= 3
error('3D images expected')
end
b = a(:,:,n);
else
error('Unexpected datatype')
end
return
|
github
|
jacksky64/imageProcessing-master
|
doublem.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/doublem.m
| 452 |
utf_8
|
af0d345d5316cb22136b39db9aed4eb6
|
%DOUBLEM Datafile mapping for conversion to double
%
% B = DOUBLEM(A)
% B = A*DOUBLEM
%
% For datasets B = A, in all other cases A is converted to double.
function a = doublem(a)
prtrace(mfilename);
if nargin < 1 | isempty(a)
a = mapping(mfilename,'fixed');
a = setname(a,'double');
elseif isdataset(a)
a = setdat(a,double(+a));
elseif isdatafile(a)
a = a*filtm([],'double');
else
a = double(a);
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_harris.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_harris.m
| 13,420 |
utf_8
|
39fab5bf9a6fc25ad377d6d50d407aaa
|
%IM_HARRIS Harris corner detector
%
% X = IM_HARRIS(A,N,SIGMA)
%
% INPUT
% A Datafile or dataset with images
% N Number of desired Harris points per image (default 100)
% SIGMA Smoothing size (default 3)
%
% OUTPUT
% X Dataset with a [N,3] array with for every image
% x, y and strength per Harris point.
%
% DESCRIPTION
% We use Kosevi's [1] software to find the corner points according to
% Harris [2]. On top of the Kosevi Harris point detector we run
% - multi-feature images (e.g. color images) are averaged
% - only points that are maximum in a K x K window are selected.
% If less points are found, K is iteratively reduced.
% The initial value of K is about 4*SIGMA.
% Although SIGMA can be interpreted as scaling parameter, it might be
% better to appropriately subsample images instead of using a large SIGMA.
%
% If you use this software for publications, please refer to [1] and [2].
%
% REFERENCES
% [1] P. D. Kovesi, MATLAB and Octave Functions for Computer Vision and
% Image Processing, School of Computer Science & Software Engineering,
% The University of Western Australia. Available from:
% <http://www.csse.uwa.edu.au/~pk/research/matlabfns/>.
% [2] C. Harris and M. Stephens, A combined corner and edge detector,
% Proc. 4th Alvey Vision Conf., 1988, pp. 147-151.
%
% EXAMPLE
% delfigs
% a = kimia; % take simple shapesas example
% b = gendat(a,25)*im_gray; % just 25 images at random
% c = data2im(b); % convert dataset to images for display
% x = im_harris(b,15,1); % compute maximum 15 Harris points at scale 1
% y = data2im(x); % unpack dataset with results
% for j=1:25 % show results one by one
% figure(j); imagesc(c(:,:,1,j)); colormap gray; hold on
% scatter(y(:,1,1,j),y(:,2,1,j),'r*');
% end
% showfigs
function x = im_harris(a,n,s,k)
prtrace(mfilename);
if nargin < 3 | isempty(s), s = 3; end
if nargin < 2 | isempty(n), n = 100; end
if nargin < 1 | isempty(a)
x = mapping(mfilename,'fixed',{n,s});
x = setname(x,'Harris points');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
a = im_gray(a);
x = filtim(a,mfilename,{n,s});
else
a = double(a);
if size(a,3) ~= 1
error('2D gray value image expected');
end
[mr,mc] = size(a); % here we put a border of 15 pixels around the image
aa = bord(a,NaN,15); % mirroring the border to avoid artificial corners
cc = harris(aa,s); % at the image border, finally we take the
c = resize(cc,15,mr,mc); % original image size (bord and resize are in ./private)
cdip = 1.0*dip_image(c);
fsizes = [25,21,17,13,11,9,7,5,3];
F = find(fsizes < 4*s);
fsizes = fsizes(F);
for fsize = fsizes
cmax = double(maxf(cdip,fsize)); % here we find the points that in a fsize-window
J = find(cmax == c); % are a local maximum
[Iy,Ix] = ind2sub(size(c),J); % second attempt to get rid of image border points
K = find(Iy > 3 & Ix >3 & Iy < (mr-2) & Ix < (mc-2));
J = J(K);
Z = find(cmax(J) > 0); % find non-zeros only
J = J(Z);
if length(J) > n % if we have sufficient points
break; % stop
end % otherwise, get more local maxima
end
cs = cmax(J);
[ss,R] = sort(-cs); % rank Harris points
if length(J) >= n % find x,y coordinates of first n Harris points
[Iy,Ix] = ind2sub(size(c),J(R(1:n)));
x = [Ix, Iy, -ss(1:n)];
else
x = zeros(n,3);
[Iy,Ix] = ind2sub(size(c),J(R));
x(1:length(R),:) = [Ix, Iy, -ss(1:length(R))];
end
end
return
% HARRIS - Harris corner detector
%
% Usage: cim = harris(im, sigma)
% [cim, r, c] = harris(im, sigma, thresh, radius, disp)
% [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)
%
% Arguments:
% im - image to be processed.
% sigma - standard deviation of smoothing Gaussian. Typical
% values to use might be 1-3.
% thresh - threshold (optional). Try a value ~1000.
% radius - radius of region considered in non-maximal
% suppression (optional). Typical values to use might
% be 1-3.
% disp - optional flag (0 or 1) indicating whether you want
% to display corners overlayed on the original
% image. This can be useful for parameter tuning. This
% defaults to 0
%
% Returns:
% cim - binary image marking corners.
% r - row coordinates of corner points.
% c - column coordinates of corner points.
% rsubp - If five return values are requested sub-pixel
% csubp - localization of feature points is attempted and
% returned as an additional set of floating point
% coords. Note that you may still want to use the integer
% valued coords to specify centres of correlation windows
% for feature matching.
%
% If thresh and radius are omitted from the argument list only 'cim' is returned
% as a raw corner strength image. You may then want to look at the values
% within 'cim' to determine the appropriate threshold value to use. Note that
% the Harris corner strength varies with the intensity gradient raised to the
% 4th power. Small changes in input image contrast result in huge changes in
% the appropriate threshold.
% References:
% C.G. Harris and M.J. Stephens. "A combined corner and edge detector",
% Proceedings Fourth Alvey Vision Conference, Manchester.
% pp 147-151, 1988.
%
% Alison Noble, "Descriptions of Image Surfaces", PhD thesis, Department
% of Engineering Science, Oxford University 1989, p45.
% Copyright (c) 2002-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in
% all copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% March 2002 - original version
% December 2002 - updated comments
% August 2005 - changed so that code calls nonmaxsuppts
function [cim, r, c, rsubp, csubp] = harris(im, sigma, thresh, radius, disp)
error(nargchk(2,5,nargin));
if nargin == 4
disp = 0;
end
if ~isa(im,'double')
im = double(im);
end
subpixel = nargout == 5;
d_x = [-1 0 1; -1 0 1; -1 0 1]; % Derivative masks
d_y = d_x';
Ix = conv2(im, d_x, 'same'); % Image derivatives
Iy = conv2(im, d_y, 'same');
% Generate Gaussian filter of size 6*sigma (+/- 3sigma) and of
% minimum size 1x1.
g = fspecial('gaussian',max(1,fix(6*sigma)), sigma);
Ix2 = conv2(Ix.^2, g, 'same'); % Smoothed squared image derivatives
Iy2 = conv2(Iy.^2, g, 'same');
Ixy = conv2(Ix.*Iy, g, 'same');
% Compute the Harris corner measure. Note that there are two measures
% that can be calculated. I prefer the first one below as given by
% Nobel in her thesis (reference above). The second one (commented out)
% requires setting a parameter, it is commonly suggested that k=0.04 - I
% find this a bit arbitrary and unsatisfactory.
cim = (Ix2.*Iy2 - Ixy.^2)./(Ix2 + Iy2 + eps); % My preferred measure.
% k = 0.04;
% cim = (Ix2.*Iy2 - Ixy.^2) - k*(Ix2 + Iy2).^2; % Original Harris measure.
if nargin > 2 % We should perform nonmaximal suppression and threshold
if disp % Call nonmaxsuppts to so that image is displayed
if subpixel
[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh, im);
else
[r,c] = nonmaxsuppts(cim, radius, thresh, im);
end
else % Just do the nonmaximal suppression
if subpixel
[r,c,rsubp,csubp] = nonmaxsuppts(cim, radius, thresh);
else
[r,c] = nonmaxsuppts(cim, radius, thresh);
end
end
end
% NONMAXSUPPTS - Non-maximal suppression for features/corners
%
% Non maxima suppression and thresholding for points generated by a feature
% or corner detector.
%
% Usage: [r,c] = nonmaxsuppts(cim, radius, thresh, im)
% /
% optional
%
% [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)
%
% Arguments:
% cim - corner strength image.
% radius - radius of region considered in non-maximal
% suppression. Typical values to use might
% be 1-3 pixels.
% thresh - threshold.
% im - optional image data. If this is supplied the
% thresholded corners are overlayed on this
% image. This can be useful for parameter tuning.
% Returns:
% r - row coordinates of corner points (integer valued).
% c - column coordinates of corner points.
% rsubp - If four return values are requested sub-pixel
% csubp - localization of feature points is attempted and
% returned as an additional set of floating point
% coords. Note that you may still want to use the integer
% valued coords to specify centres of correlation windows
% for feature matching.
%
% Copyright (c) 2003-2005 Peter Kovesi
% School of Computer Science & Software Engineering
% The University of Western Australia
% http://www.csse.uwa.edu.au/
%
% Permission is hereby granted, free of charge, to any person obtaining a copy
% of this software and associated documentation files (the "Software"), to deal
% in the Software without restriction, subject to the following conditions:
%
% The above copyright notice and this permission notice shall be included in all
% copies or substantial portions of the Software.
%
% The Software is provided "as is", without warranty of any kind.
% September 2003 Original version
% August 2005 Subpixel localization and Octave compatibility
function [r,c, rsubp, csubp] = nonmaxsuppts(cim, radius, thresh, im)
v = version; Octave = v(1)<'5'; % Crude Octave test
subPixel = nargout == 4; % We want sub-pixel locations
[rows,cols] = size(cim);
% Extract local maxima by performing a grey scale morphological
% dilation and then finding points in the corner strength image that
% match the dilated image and are also greater than the threshold.
sze = 2*radius+1; % Size of dilation mask.
mx = ordfilt2(cim,sze^2,ones(sze)); % Grey-scale dilate.
% Make mask to exclude points within radius of the image boundary.
bordermask = zeros(size(cim));
bordermask(radius+1:end-radius, radius+1:end-radius) = 1;
% Find maxima, threshold, and apply bordermask
cimmx = (cim==mx) & (cim>thresh) & bordermask;
[r,c] = find(cimmx); % Find row,col coords.
if subPixel % Compute local maxima to sub pixel accuracy
if ~isempty(r) % ...if we have some ponts to work with
ind = sub2ind(size(cim),r,c); % 1D indices of feature points
w = 1; % Width that we look out on each side of the feature
% point to fit a local parabola
% Indices of points above, below, left and right of feature point
indrminus1 = max(ind-w,1);
indrplus1 = min(ind+w,rows*cols);
indcminus1 = max(ind-w*rows,1);
indcplus1 = min(ind+w*rows,rows*cols);
% Solve for quadratic down rows
cy = cim(ind);
ay = (cim(indrminus1) + cim(indrplus1))/2 - cy;
by = ay + cy - cim(indrminus1);
rowshift = -w*by./(2*ay); % Maxima of quadradic
% Solve for quadratic across columns
cx = cim(ind);
ax = (cim(indcminus1) + cim(indcplus1))/2 - cx;
bx = ax + cx - cim(indcminus1);
colshift = -w*bx./(2*ax); % Maxima of quadradic
rsubp = r+rowshift; % Add subpixel corrections to original row
csubp = c+colshift; % and column coords.
else
rsubp = []; csubp = [];
end
end
if nargin==4 & ~isempty(r) % Overlay corners on supplied image.
if Octave
warning('Only able to display points under Octave');
if subPixel
plot(csubp,rsubp,'r+'), title('corners detected');
else
plot(c,r,'r+'), title('corners detected');
end
[rows,cols] = size(cim);
axis([1 cols 1 rows]); axis('equal'); axis('ij')
else
figure(1), imshow(im,[]), hold on
if subPixel
plot(csubp,rsubp,'r+'), title('corners detected');
else
plot(c,r,'r+'), title('corners detected');
end
end
end
|
github
|
jacksky64/imageProcessing-master
|
filtm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/filtm.m
| 3,963 |
utf_8
|
7a05a77f873c14f7b9776858cb33417a
|
%FILTM Mapping to filter objects in datasets and datafiles
%
% B = FILTM(A,FILTER_COMMAND,{PAR1,PAR2,....},SIZE)
% B = A*FILTM([],FILTER_COMMAND,{PAR1,PAR2,....},SIZE)
%
% INPUT
% A Dataset or datafile
% FILTER_COMMAND String with function name
% {PAR1, ... } Cell array with optional parameters to FILTER_COMMAND
% SIZE Output size of the mapping (default: input size)
%
% OUTPUT
% B Dataset or datafile of images processed by FILTER_COMMAND
%
% DESCRIPTION
% For each object stored in A a filter operation is performed as
%
% OBJECT_OUT = FILTER_COMMAND(OBJECT_IN,PAR1,PAR2,....)
%
% The results are collected and stored in B. In case A (and thereby B) is
% a datafile, execution is postponed until conversion into a dataset, or a
% call to SAVEDATAFILE or CREATEDATAFILE.
%
% EXAMPLES
% b = filtm(a,'conv2',{[-1 0 1; -1 0 1; -1 0 1],'same'});
% Performs a convolution with a horizontal gradient filter (see CONV2).
%
% There is a similar command FILTIM that is recommended for handling
% multi-band images.
%
% SEE ALSO
% DATASETS, DATAFILES, IM2OBJ, DATA2IM, IM2FEAT, DATGAUSS, DATFILT, FILTIM
% SAVEDATAFILE ,CREATEDATAFILE
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = filtm(a,command,pars,outsize)
prtrace(mfilename);
if nargin < 4, outsize = []; end
if nargin < 3, pars = {}; end
if nargin < 2
error('No command given')
end
if ~iscell(pars), pars = {pars}; end
mapname = 'dataset/file image filtering';
if isempty(a) % no data, so just mapping definition
b = mapping(mfilename,'fixed',{command,pars});
if ~isempty(outsize)
b = setsize_out(b,outsize);
end
b = setname(b,mapname);
elseif isdatafile(a) % for datafiles filters are stored
if isempty(getpostproc(a)) & ~ismapping(command)
% as preprocessing (if no postproc defined)
b = addpreproc(a,command,pars,outsize);
else % or as mapping as postprocessing
if ismapping(command) % we have already a mapping
v = command;
else % just a string, construct mapping
v = mapping(mfilename,'fixed',{command,pars});
v = setname(v,mapname);
end
if ~isempty(outsize) % user wants to set an output size (hope he has good reasons)
v = setsize_out(v,outsize); % add it to mapping
end
b = addpostproc(a,v); % store mapping
end
if ~isempty(outsize)
b = setfeatsize(b,outsize); % set featsize equal to output size
end
return
elseif isdataset(a) % are executed here
m = size(a,1);
d = +a;
imsize = getfeatsize(a);
% Perform command on first image to check whether image size stays equal
if length(imsize) == 1
imsize = [1 imsize];
end
first = execute(command,reshape(d(1,:),imsize),pars);
first = double(first); % for DipLib users
if isempty(outsize)
outsize = size(first);
end
% process all other images
out = repmat(first(:)',m,1);
for i = 2:m
ima = double(execute(command,reshape(d(i,:),imsize),pars));
sima = size(ima);
if (any(outsize ~= sima(1:length(outsize))))
error('All image sizes should be the same')
end
out(i,:) = ima(:)';
end
% store processed images in dataset
b = setdata(a,out);
b = setfeatsize(b,outsize);
elseif iscell(a)
b = cell(size(a));
n = numel(b);
s = sprintf('Filtering %i objects: ',n);
prwaitbar(n,s);
for i=1:n
prwaitbar(n,i,[s int2str(i)]);
b{i} = feval(mfilename,a{i},command,pars,outsize);
end
prwaitbar(0);
else
b = feval(command,a,pars{:});
end
return
function out = execute(command,a,pars)
exist_command = exist(command);
if isstr(command) & any([2 3 5 6] == exist_command)
out = feval(command,a,pars{:});
elseif ismapping(command)
out = map(a,command);
else
error('Filter command not found')
end
return
|
github
|
jacksky64/imageProcessing-master
|
perc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/perc.m
| 1,819 |
utf_8
|
0074226bc6558b7c32d83f440cdb313d
|
%PERC Percentile combining classifier
%
% W = PERC(V,P)
% W = V*PERC([],P)
%
% INPUT
% V Set of classifiers
% P Percentile, 0 <= P <= 100
%
% OUTPUT
% W Percentile combining classifier on V
%
% DESCRIPTION
% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the
% same classes and W is the percentile combiner: it selects the class
% defined by the percentile of the outputs of the input classifiers. This
% might also be used as A*[V1,V2,V3]*PERC([],P) in which A is a dataset to
% be classified.
%
% PERC([],0) is equal to MINC
% PERC([],50) is equal to MEDIANC
% PERC([],100) is equal to MAXC
%
% If it is desired to operate on posterior probabilities then the
% input classifiers should be extended like V = V*CLASSC;
%
% The base classifiers may be combined in a stacked way (operating
% in the same feature space by V = [V1,V2,V3, ... ] or in a parallel
% way (operating in different feature spaces) by V = [V1;V2;V3; ... ]
%
% SEE ALSO
% MAPPINGS, DATASETS, VOTEC, MAXC, MINC, MEANC, MEDIANC, PRODC,
% AVERAGEC, STACKED, PARALLEL
%
% EXAMPLES
% See PREX_COMBINING
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = perc(p1,par)
if nargin < 2 | par < 0 | par > 100
error('Percentile between 0 and 100 should be defined for percentile combiner')
end
type = 'perc'; % define the operation processed by FIXEDCC.
% define the name of the combiner.
% this is the general procedure for all possible calls of fixed combiners
% handled by FIXEDCC
name = 'Percentile combiner';
if nargin == 0
w = mapping('fixedcc','combiner',{[],type,name,par});
else
w = fixedcc(p1,[],type,name,par);
end
if isa(w,'mapping')
w = setname(w,name);
end
return
|
github
|
jacksky64/imageProcessing-master
|
mds_cs.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/mds_cs.m
| 3,083 |
utf_8
|
3146fafdcca70fc84952a465cab553ce
|
% MDS_CS Classical scaling
%
% W = MDS_CS(D,N)
%
% INPUT
% D Square dissimilarity matrix of the size M x M
% N Desired output dimensionality (optional; default: 2)
%
% OUTPUT
% W Classical scaling mapping
%
% DESCRIPTION
% A linear mapping of objects given by a symmetric distance matrix D with
% a zero diagonal onto an N-dimensional Euclidean space such that the square
% distances are preserved as much as possible.
%
% D is assumed to approximate the Euclidean distances, i.e.
% D_{ij} = sqrt(sum_k (x_i-x_j)^2).
%
%
% REFERENCES
% 1. I. Borg and P. Groenen, Modern Multidimensional Scaling, Springer Verlag, Berlin,
% 1997.
% 2. T.F. Cox and M.A.A. Cox, Multidimensional Scaling, Chapman and Hall, London, 1994.
%
% SEE ALSO
% MAPPINGS, MDS_INIT, MDS_CS
%
% Copyright: Elzbieta Pekalska, Robert P.W. Duin, [email protected], 2000-2003
% Faculty of Applied Sciences, Delft University of Technology
%
function W = mds_cs (D,n)
if nargin < 2, n = 2; end
if nargin < 1 | isempty(D)
W = mapping(mfilename,n);
W = setname(W,'Classical MDS');
return
end
[m,mm] = size(D);
if (isa(D,'dataset') | isa(D,'double'))
if isa(n,'mapping')
% The projection is already defined; apply it to new data
w = getdata(n);
[m,n] = size(D);
if isa(D,'dataset'),
lab = getlab(D);
D = +D;
else
lab = [];
end
D = remove_nan(D);
D = D.^2;
Q = w{1};
me = w{2};
L = w{3};
Z = -repmat(1/n,n,n);
Z(1:n+1:end) = Z(1:n+1:end) + 1; % Z = eye(n) - ones(n,n)/n
data = -0.5 * (D - me(ones(m,1),:)) * Z * Q * diag(sqrt(abs(L))./L);
if ~isempty(lab),
W = dataset(data,lab);
else
W = data;
end
return;
end
end
% Definition of the projection; we are here only if there is no projection yet
if ~issym(D,1e-12),
error('Matrix should be symmetric.')
end
D = remove_nan(D);
D = +D.^2;
B = -repmat(1/m,m,m);
B(1:m+1:end) = B(1:m+1:end) + 1; % B = eye(m) - ones(m,m)/m
B = -0.5 * B * D * B; % B is now the matrix of inner products
ok = 0;
p = 1;
k = min (p*n,m);
options.disp = 0;
options.isreal = 1;
options.issym = 1;
while ~ok & k <= m, % Find k largest eigenvalues
k = min (p*n,m);
[V,S,U] = eigs(B,k,'lm',options);
s = diag(real(S));
[ss,I] = sort(-s);
ok = sum(s>0) >= n;
p = p+1;
end
if ~ok & k == m,
error ('The wanted configuration cannot be found.');
end
J = I(1:n);
W = mapping(mfilename,'trained',{V(:,J), mean(D,2)', s(J)},[],m,length(J));
W = setname(W,'Classical MDS');
return
function D = remove_nan(D)
% Remove all appearing NaN's by replacing them by the nearest neighbors.
%
[m,mm] = size(D);
nanindex = find(isnan(D(:)));
if ~isempty(nanindex),
for i=1:m
K = find(isnan(D(i,:)));
I = 1:mm;
[md,kk] = min(D(i,:));
if md < eps,
I(kk) = [];
end
D(i,K) = min(D(i,I));
end
% check whether the diagonal is of all zeros
if length(intersect(find(D(:) < eps), 1:m+1:(m*m))) >= m,
D = (D+D')/2;
end
end
|
github
|
jacksky64/imageProcessing-master
|
rsquared.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rsquared.m
| 727 |
utf_8
|
c4f5d33e644e6c2cdbbdc3edefb6c7e4
|
%RSQUARED R^2 statistic
%
% E = RSQUARED(X,W)
% E = RSQUARED(X*W)
% E = X*W*RSQUARED
%
% INPUT
% X Regression dataset
% W Regression mapping
%
% OUTPUT
% E The R^2-statistic
%
% DESCRIPTION
% Compute the R^2 statistic of regression W on dataset X.
%
% SEE ALSO
% TESTR
% Copyright: D.M.J. Tax, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function r2 = rsquared(x,w)
if nargin==0
r2 = mapping(mfilename,'fixed');
return
elseif nargin==1
y = gettargets(x);
yhat = +x(:,1);
meany = mean(y);
r2 = (sum((yhat-meany).^2))/(sum((y-meany).^2));
else
ismapping(w);
istrained(w);
r2 = feval(mfilename, x*w);
end
|
github
|
jacksky64/imageProcessing-master
|
im_skel.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_skel.m
| 816 |
utf_8
|
8b6fef0e8819522166a1b00bf7a945ca
|
%IM_SKEL Skeleton of binary images stored in a dataset (DIP_Image)
%
% B = IM_SKEL(A)
% B = A*IM_SKEL
%
% INPUT
% A Dataset with binary object images dataset
%
% OUTPUT
% B Dataset with skeleton images
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE, BSKELETON
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_berosion(a)
prtrace(mfilename);
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed');
b = setname(b,'Image skeleton');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename);
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = dip_image(a,'bin');
b = bskeleton(a,0,'natural');
end
return
|
github
|
jacksky64/imageProcessing-master
|
klm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/klm.m
| 1,967 |
utf_8
|
d875ae891450009ebf5dfea7d03bb079
|
%KLM Karhunen-Loeve Mapping (PCA or MCA of mean covariance matrix)
%
% [W,FRAC] = KLM(A,N)
% [W,N] = KLM(A,FRAC)
%
% INPUT
% A Dataset
% N or FRAC Number of dimensions (>= 1) or fraction of variance (< 1)
% to retain; if > 0, perform PCA; otherwise MCA.
% Default: N = inf.
%
% OUTPUT
% W Affine Karhunen-Loeve mapping
% FRAC or N Fraction of variance or number of dimensions retained.
%
% DESCRIPTION
% The Karhunen-Loeve Mapping performs a principal component analysis
% (PCA) or minor component analysis (MCA) on the mean class covariance
% matrix (weighted by the class prior probabilities). It finds a
% rotation of the dataset A to an N-dimensional linear subspace such
% that at least (for PCA) or at most (for MCA) a fraction FRAC of the
% total variance is preserved.
%
% PCA is applied when N (or FRAC) >= 0; MCA when N (or FRAC) < 0. If N
% is given (abs(N) >= 1), FRAC is optimised. If FRAC is given
% (abs(FRAC) < 1), N is optimised.
%
% Objects in a new dataset B can be mapped by B*W, W*B or by
% A*KLM([],N)*B. Default (N = inf): the features are decorrelated and
% ordered, but no feature reduction is performed.
%
% ALTERNATIVE
%
% V = KLM(A,0)
%
% Returns the cummulative fraction of the explained variance. V(N) is
% the cumulative fraction of the explained variance by using N
% eigenvectors.
%
% Use PCA for a principal component analysis on the total data
% covariance. Use FISHERM for optimizing the linear class
% separability (LDA).
%
% This function is basically a wrapper around pcaklm.m.
%
% SEE ALSO
% MAPPINGS, DATASETS, PCAKLM, PCLDC, KLLDC, PCA, FISHERM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: klm.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function [w,truefrac] = klm (varargin)
prtrace(mfilename);
[w,truefrac] = pcaklm(mfilename,varargin{:});
return
|
github
|
jacksky64/imageProcessing-master
|
im_gray.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_gray.m
| 1,529 |
utf_8
|
f259e1fe56cc90cab8d8e3ac4efe0e7f
|
%IM_GRAY Conversion of multi-band images into gray images
%
% B = IM_GRAY(A,V)
% B = A*IM_GRAY([],V)
%
% INPUT
% A Multiband image or dataset with multi-band images as objects
% V Weight vector, one weight per band. Default: equal weights.
%
% OUTPUT
% B Output image or dataset.
%
% DESCRIPTION
% The multi-band components in the image A (3rd dimension) or in the
% objects in the dataset A are weigthed (default: equal weights) and
% averaged.
%
% SEE ALSO
% MAPPINGS, DATASETS, DATAFILES
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_gray(a,v)
prtrace(mfilename,2);
if nargin < 2, v = []; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{v});
b = setname(b,'Color-to-gray conversion');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtm(a,mfilename,v);
imsize = getfeatsize(a);
b = setfeatsize(b,imsize(1:2));
else
a = double(a);
imsize = size(a);
if isempty(v)
if length(imsize) == 3
b = mean(a,3);
b = squeeze(b);
elseif length(imsize) == 2
b = a;
else
error('Illegal image size')
end
else
if length(imsize) == 2
b = a;
else
b = zeros(imsize(1),imsize(2),size(a,1));
for i=1:size(a,1)
for j=1:size(im,3)
b(:,:,i) =b(:,:,i) + b(:,:,j,i)*v(j);
end
end
end
end
end
return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.