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
|
garrickbrazil/SDS-RCNN-master
|
kernelTracker.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/videos/kernelTracker.m
| 9,315 |
utf_8
|
4a7d0235f1e518ab5f1c9f1b5450b3f0
|
function [allRct, allSim, allIc] = kernelTracker( I, prm )
% Kernel Tracker from Comaniciu, Ramesh and Meer PAMI 2003.
%
% Implements the algorithm described in "Kernel-Based Object Tracking" by
% Dorin Comaniciu, Visvanathan Ramesh and Peter Meer, PAMI 25, 564-577,
% 2003. This is a fast tracking algorithm that utilizes a histogram
% representation of an object (in this implementation we use color
% histograms, as in the original work). The idea is given a histogram q in
% frame t, find histogram p in frame t+1 that is most similar to q. It
% turns out that this can be formulated as a mean shift problem. Here, the
% kernel is fixed to the Epanechnikov kernel.
%
% This implementation uses mex files to optimize speed, it is significantly
% faster than real time for a single object on a 2GHz standard laptop (as
% of 2007).
%
% If I==[], toy data is created. If rctS==0, the user is queried to
% specify the first rectangle. rctE, denoting the object location in the
% last frame, can optionally be specified. If rctE is given, the model
% histogram at fraction r of the video is (1-r)*histS+r*histE where histS
% and histE are the model histograms from the first and last frame. If
% rctE==0 rectangle in final frame is queried, if rectE==-1 it is not used.
%
% Let T denote the length of the video. Returned values are of length t,
% where t==T if the object was tracked through the whole sequence (ie sim
% does not fall below simThr), otherwise t<=T is equal to the last frame in
% which obj was found. You can test if the object was tracked using:
% success = (size(allRct,1)==size(I,4));
%
% USAGE
% [allRct, allIc, allSim] = kernelTracker( [I], [prm] )
%
% INPUTS
% I - MxNx3xT input video
% [prm]
% .rctS - [0] rectangle denoting initial object location
% .rctE - [-1] rectangle denoting final object location
% .dispFlag - [1] show interactive display
% .scaleSrch - [1] if true search over scale
% .nBit - [4] n=2^nBit, color histograms are [n x n x n]
% .simThr - [.7] sim thr for when obj is considered lost
% .scaleDel - [.9] multiplicative diff between consecutive scales
%
% OUTPUTS
% allRct - [t x 4] array of t locations [x,y,wd,ht]
% allSim - [1 x t] array of similarity measures during tracking
% allIc - [1 x t] cell array of cropped windows containing obj
%
% EXAMPLE
% disp('Select a rectangular region for tracking');
% [allRct,allSim,allIc] = kernelTracker();
% figure(2); clf; plot(allRct);
% figure(3); clf; montage2(allIc,struct('hasChn',true));
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.22
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% get parameters (set defaults)
if( nargin<1 ); I=[]; end;
if( nargin<2 ); prm=struct(); end;
dfs = {'scaleSrch',1, 'nBit',4, 'simThr',.7, ...
'dispFlag',1, 'scaleDel',.9, 'rctS',0, 'rctE',-1 };
prm = getPrmDflt( prm, dfs );
scaleSrch=prm.scaleSrch; nBit=prm.nBit; simThr=prm.simThr;
dispFlag=prm.dispFlag; scaleDel=prm.scaleDel;
rctS=prm.rctS; rctE=prm.rctE;
if(isempty(I)); I=toyData(100,1); end;
%%% get rctS and rectE if necessary
rctProp = {'EdgeColor','g','Curvature',[1 1],'LineWidth',2};
if(rctS==0); figure(1); clf; imshow(I(:,:,:,1)); rctS=getrect; end
if(rctE==0); figure(1); clf; imshow(I(:,:,:,end)); rctE=getrect; end
%%% precompute kernels for all relevant scales
rctS=round(rctS); rctS(3:4)=rctS(3:4)-mod(rctS(3:4),2);
pos1 = rctS(1:2)+rctS(3:4)/2; wd=rctS(3); ht=rctS(4);
[mRows,nCols,~,nFrame] = size(I);
nScaleSm = max(1,floor(log(max(10/wd,10/ht))/log(scaleDel)));
nScaleLr = max(1,floor(-log(min(nCols/wd,mRows/ht)/2)/log(scaleDel)));
nScale = nScaleSm+nScaleLr+1; scale = nScaleSm+1;
kernel = repmat( buildKernel(wd,ht), [1 nScale] );
for s=1:nScale
r = power(scaleDel,s-1-nScaleSm);
kernel(s) = buildKernel( wd/r, ht/r );
end
%%% build model histogram for rctS
[Ic,Qc] = cropWindow( I(:,:,:,1), nBit, pos1, wd, ht );
qS = buildHist( Qc, kernel(scale), nBit );
%%% optionally build model histogram for rctE
if(length(rctE)==4);
rctE=round(rctE); rctE(3:4)=rctE(3:4)-mod(rctE(3:4),2);
posE = rctE(1:2)+rctE(3:4)/2; wdE=rctE(3); htE=rctE(4);
kernelE = buildKernel(wdE,htE);
[Ic,Qc] = cropWindow( I(:,:,:,end), nBit, posE, wdE, htE ); %end
qE = buildHist( Qc, kernelE, nBit );
else
qE = qS;
end
%%% setup display
if( dispFlag )
figure(1); clf; hImg=imshow(I(:,:,:,1));
hR = rectangle('Position', rctS, rctProp{:} );
pause(.1);
end
%%% main loop
pos = pos1;
allRct = zeros(nFrame,4); allRct(1,:)=rctS;
allIc = cell(1,nFrame); allIc{1}=Ic;
allSim = zeros(1,nFrame);
for frm = 1:nFrame
Icur = I(:,:,:,frm);
% current model (linearly interpolate)
r=(frm-1)/nFrame; q = qS*(1-r) + qE*r;
if( scaleSrch )
% search over scale
best={}; bestSim=-1; pos1=pos;
for s=max(1,scale-1):min(nScale,scale+1)
[p,pos,Ic,sim]=kernelTracker1(Icur,q,pos1,kernel(s),nBit);
if( sim>bestSim ); best={p,pos,Ic,s}; bestSim=sim; end;
end
[~,pos,Ic,scale]=deal(best{:});
wd=kernel(scale).wd; ht=kernel(scale).ht;
else
% otherwise just do meanshift once
[~,pos,Ic,bestSim]=kernelTracker1(Icur,q,pos,kernel(scale),nBit);
end
% record results
if( bestSim<simThr ); break; end;
rctC=[pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
allIc{frm}=Ic; allRct(frm,:)=rctC;
allSim(frm)=bestSim;
% display
if( dispFlag )
set(hImg,'CData',Icur); title(['bestSim=' num2str(bestSim)]);
delete(hR); hR=rectangle('Position', rctC, rctProp{:} );
if(0); waitforbuttonpress; else drawnow; end
end
end
%%% finalize & display
if( bestSim<simThr ); frm=frm-1; end;
allIc=allIc(1:frm); allRct=allRct(1:frm,:); allSim=allSim(1:frm);
if( dispFlag )
if( bestSim<simThr ); disp('lost target'); end
disp( ['final sim = ' num2str(bestSim) ] );
end
end
function [p,pos,Ic,sim] = kernelTracker1( I, q, pos, kernel, nBit )
mRows=size(I,1); nCols=size(I,2);
wd=kernel.wd; wd2=wd/2;
ht=kernel.ht; ht2=ht/2;
xs=kernel.xs; ys=kernel.ys;
for iter=1:1000
posPrev = pos;
% check if pos in bounds
rct = [pos(1)-wd/2 pos(2)-ht/2 wd, ht ];
if( rct(1)<1 || rct(2)<1 || (rct(1)+wd)>nCols || (rct(2)+ht)>mRows )
pos=posPrev; p=[]; Ic=[]; sim=eps; return;
end
% crop window / compute histogram
[Ic,Qc] = cropWindow( I, nBit, pos, wd, ht );
p = buildHist( Qc, kernel, nBit );
if( iter==20 ); break; end;
% compute meanshift step
w = ktComputeW_c( Qc, q, p, nBit );
posDel = [sum(xs.*w)*wd2, sum(ys.*w)*ht2] / (sum(w)+eps);
posDel = round(posDel+.1);
if(all(posDel==0)); break; end;
pos = pos + posDel;
end
locs=p>0; sim=sum( sqrt(q(locs).*p(locs)) );
end
function kernel = buildKernel( wd, ht )
wd = round(wd/2)*2; xs = linspace(-1,1,wd);
ht = round(ht/2)*2; ys = linspace(-1,1,ht);
[ys,xs] = ndgrid(ys,xs); xs=xs(:); ys=ys(:);
xMag = ys.*ys + xs.*xs; xMag(xMag>1) = 1;
K = 2/pi * (1-xMag); sumK=sum(K);
kernel = struct( 'K',K, 'sumK',sumK, 'xs',xs, 'ys',ys, 'wd',wd, 'ht',ht );
end
function p = buildHist( Qc, kernel, nBit )
p = ktHistcRgb_c( Qc, kernel.K, nBit ) / kernel.sumK;
if(0); p=gaussSmooth(p,.5,'same',2); p=p*(1/sum(p(:))); end;
end
function [Ic,Qc] = cropWindow( I, nBit, pos, wd, ht )
row = pos(2)-ht/2; col = pos(1)-wd/2;
Ic = I(row:row+ht-1,col:col+wd-1,:);
if(nargout==2); Qc=bitshift(reshape(Ic,[],3),nBit-8); end;
end
function I = toyData( n, sigma )
I1 = imresize(imread('peppers.png'),[256 256],'bilinear');
I=ones(512,512,3,n,'uint8')*100;
pos = round(gaussSmooth(randn(2,n)*80,[0 4]))+128;
for i=1:n
I((1:256)+pos(1,i),(1:256)+pos(2,i),:,i)=I1;
I1 = uint8(double(I1) + randn(size(I1))*sigma);
end;
I=I((1:256)+128,(1:256)+128,:,:);
end
% % debugging code
% if( debug )
% figure(1);
% subplot(2,3,2); image( Ic ); subplot(2,3,1); image(Icur);
% rectangle('Position', posToRct(pos0,wd,ht), rctProp{:} );
% subplot(2,3,3); imagesc( reshape(w,wd,ht), [0 5] ); colormap gray;
% subplot(2,3,4); montage2( q ); subplot(2,3,5); montage2( p1 );
% waitforbuttonpress;
% end
% % search over 9 locations (with fixed scale)
% if( locSrch )
% best={}; bestSim=0.0; pos1=pos;
% for lr=-1:1
% for ud=-1:1
% posSt = pos1 + [wd*lr ht*ud];
% [p,pos,Ic,sim] = kernelTracker1(Icur,q,posSt,kernel(scale),nBit);
% if( sim>bestSim ); best={p,pos,Ic}; bestSim=sim; end;
% end
% end
% [p,pos,Ic]=deal(best{:});
% end
%%% background histogram -- seems kind of useless, removed
% if( 0 )
% bgSiz = 3; bgImp = 2;
% rctBgStr = max([1 1],rctS(1:2)-rctS(3:4)*(bgSiz/2-.5));
% rctBgEnd = min([nCols mRows],rctS(1:2)+rctS(3:4)*(bgSiz/2+.5));
% rctBg = [rctBgStr rctBgEnd-rctBgStr+1];
% posBg = rctBg(1:2)+rctBg(3:4)/2; wdBg=rctBg(3); htBg=rctBg(4);
% [IcBg,QcBg] = cropWindow( I(:,:,:,1), nBit, posBg, wdBg, htBg );
% wtBg = double( reshape(kernel.K,ht,wd)==0 );
% pre=rctS(1:2)-rctBg(1:2); pst=rctBg(3:4)-rctS(3:4)-pre;
% wtBg = padarray( wtBg, fliplr(pre), 1, 'pre' );
% wtBg = padarray( wtBg, fliplr(pst), 1, 'post' );
% pBg = buildHist( QcBg, wtBg, [], nBit );
% pWts = min( 1, max(pBg(:))/bgImp./pBg );
% if(0); montage2(pWts); impixelinfo; return; end
% else
% pWts=[];
% end;
% if(~isempty(pWts)); p = p .* pWts; end; % in buildHistogram
|
github
|
garrickbrazil/SDS-RCNN-master
|
seqIo.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/videos/seqIo.m
| 17,019 |
utf_8
|
9c631b324bb527372ec3eed3416c5dcc
|
function out = seqIo( fName, action, varargin )
% Utilities for reading and writing seq files.
%
% A seq file is a series of concatentated image frames with a fixed size
% header. It is essentially the same as merging a directory of images into
% a single file. seq files are convenient for storing videos because: (1)
% no video codec is required, (2) seek is instant and exact, (3) seq files
% can be read on any operating system. The main drawback is that each frame
% is encoded independently, resulting in increased file size. The advantage
% over storing as a directory of images is that a single large file is
% created. Currently, either uncompressed, jpg or png compressed frames
% are supported. The seq file format is modeled after the Norpix seq format
% (in fact this reader can be used to read some Norpix seq files). The
% actual work of reading/writing seq files is done by seqReaderPlugin and
% seqWriterPlugin (there is no need to call those functions directly).
%
% seqIo contains a number of utility functions for working with seq files.
% The format for accessing the various utility functions is:
% out = seqIo( fName, 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help seqIo>action".
%
% Create interface sr for reading seq files.
% sr = seqIo( fName, 'reader', [cache] )
% Create interface sw for writing seq files.
% sw = seqIo( fName, 'writer', info )
% Get info about seq file.
% info = seqIo( fName, 'getInfo' )
% Crop sub-sequence from seq file.
% seqIo( fName, 'crop', tName, frames )
% Extract images from seq file to target directory or array.
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
% Create seq file from an array or directory of images or from an AVI file.
% seqIo( fName, 'frImgs', info, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
% seqIo( fName, 'convert', tName, imgFun, varargin )
% Replace header of seq file with provided info.
% seqIo( fName, 'newHeader', info )
% Create interface sr for reading dual seq files.
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% USAGE
% out = seqIo( fName, action, varargin )
%
% INPUTS
% fName - seq file to open
% action - controls action (see above)
% varargin - additional inputs (see above)
%
% OUTPUTS
% out - depends on action (see above)
%
% EXAMPLE
%
% See also seqIo>reader, seqIo>writer, seqIo>getInfo, seqIo>crop,
% seqIo>toImgs, seqIo>frImgs, seqIo>convert, seqIo>newHeader,
% seqIo>readerDual, seqPlayer, seqReaderPlugin, seqWriterPlugin
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch lower(action)
case {'reader','r'}, out = reader( fName, varargin{:} );
case {'writer','w'}, out = writer( fName, varargin{:} );
case 'getinfo', out = getInfo( fName );
case 'crop', crop( fName, varargin{:} ); out=1;
case 'toimgs', out = toImgs( fName, varargin{:} );
case 'frimgs', frImgs( fName, varargin{:} ); out=1;
case 'convert', convert( fName, varargin{:} ); out=1;
case 'newheader', newHeader( fName, varargin{:} ); out=1;
case {'readerdual','rdual'}, out=readerDual(fName,varargin{:});
otherwise, error('seqIo unknown action: ''%s''',action);
end
end
function sr = reader( fName, cache )
% Create interface sr for reading seq files.
%
% Create interface sr to seq file with the following commands:
% sr.close(); % Close seq file (sr is useless after).
% [I,ts]=sr.getframe(); % Get current frame (returns [] if invalid).
% [I,ts]=sr.getframeb(); % Get current frame with no decoding.
% ts = sr.getts(); % Return timestamps for all frames.
% info = sr.getinfo(); % Return struct with info about video.
% [I,ts]=sr.getnext(); % Shortcut for next() followed by getframe().
% out = sr.next(); % Go to next frame (out=0 on fail).
% out = sr.seek(frame); % Go to specified frame (out=0 on fail).
% out = sr.step(delta); % Go to current frame+delta (out=0 on fail).
%
% If cache>0, reader() will cache frames in memory, so that calls to
% getframe() can avoid disk IO for cached frames (note that only frames
% returned by getframe() are cached). This is useful if the same frames are
% accessed repeatedly. When the cache is full, the frame in the cache
% accessed least recently is discarded. Memory requirements are
% proportional to cache size.
%
% USAGE
% sr = seqIo( fName, 'reader', [cache] )
%
% INPUTS
% fName - seq file name
% cache - [0] size of cache
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqReaderPlugin
if(nargin<2 || isempty(cache)), cache=0; end
if( cache>0 ), [as, fs, Is, ts, inds]=deal([]); end
r=@seqReaderPlugin; s=r('open',int32(-1),fName);
sr = struct( 'close',@() r('close',s), 'getframe',@getframe, ...
'getframeb',@() r('getframeb',s), 'getts',@() r('getts',s), ...
'getinfo',@() r('getinfo',s), 'getnext',@() r('getnext',s), ...
'next',@() r('next',s), 'seek',@(f) r('seek',s,f), ...
'step',@(d) r('step',s,d));
function [I,t] = getframe()
% if not using cache simply call 'getframe' and done
if(cache<=0), [I,t]=r('getframe',s); return; end
% if cache initialized and frame in cache perform lookup
f=r('getinfo',s); f=f.curFrame; i=find(f==fs,1);
if(i), as=as+1; as(i)=0; t=ts(i); I=Is(inds{:},i); return; end
% if image not in cache add (and possibly initialize)
[I,t]=r('getframe',s); if(0), fprintf('reading frame %i\n',f); end
if(isempty(Is)), Is=zeros([size(I) cache],class(I));
as=ones(1,cache); fs=-as; ts=as; inds=repmat({':'},1,ndims(I)); end
[~,i]=max(as); as(i)=0; fs(i)=f; ts(i)=t; Is(inds{:},i)=I;
end
end
function sw = writer( fName, info )
% Create interface sw for writing seq files.
%
% Create interface sw to seq file with the following commands:
% sw.close(); % Close seq file (sw is useless after).
% sw.addframe(I,[ts]); % Writes video frame (and timestamp)
% sw.addframeb(bytes); % Writes video frame with no encoding.
% info = sw.getinfo(); % Return struct with info about video.
%
% The following params must be specified in struct 'info' upon opening:
% width - frame width
% height - frame height
% fps - frames per second
% quality - [80] compression quality (0 to 100)
% codec - string representing codec, options include:
% 'monoraw'/'imageFormat100' - black/white uncompressed
% 'raw'/'imageFormat200' - color (BGR) uncompressed
% 'monojpg'/'imageFormat102' - black/white jpg compressed
% 'jpg'/'imageFormat201' - color jpg compressed
% 'monopng'/'imageFormat001' - black/white png compressed
% 'png'/'imageFormat002' - color png compressed
%
% USAGE
% sw = seqIo( fName, 'writer', info )
%
% INPUTS
% fName - seq file name
% info - see above
%
% OUTPUTS
% sw - interface for writing seq file
%
% EXAMPLE
%
% See also seqIo, seqWriterPlugin
w=@seqWriterPlugin; s=w('open',int32(-1),fName,info);
sw = struct( 'close',@() w('close',s), 'getinfo',@() w('getinfo',s), ...
'addframe',@(varargin) w('addframe',s,varargin{:}), ...
'addframeb',@(varargin) w('addframeb',s,varargin{:}) );
end
function info = getInfo( fName )
% Get info about seq file.
%
% USAGE
% info = seqIo( fName, 'getInfo' )
%
% INPUTS
% fName - seq file name
%
% OUTPUTS
% info - information struct
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sr.close();
end
function crop( fName, tName, frames )
% Crop sub-sequence from seq file.
%
% Frame indices are 0 indexed. frames need not be consecutive and can
% contain duplicates. An index of -1 indicates a blank (all 0) frame. If
% contiguous subset of frames is cropped timestamps are preserved.
%
% USAGE
% seqIo( fName, 'crop', tName, frames )
%
% INPUTS
% fName - seq file name
% tName - cropped seq file name
% frames - frame indices (0 indexed)
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
sr=reader(fName); info=sr.getinfo(); sw=writer(tName,info);
frames=frames(:)'; pad=sr.getnext(); pad(:)=0;
kp=frames>=0 & frames<info.numFrames; if(~all(kp)), frames=frames(kp);
warning('piotr:seqIo:crop','%i out of bounds frames',sum(~kp)); end
ordered=all(frames(2:end)==frames(1:end-1)+1);
n=length(frames); k=0; tid=ticStatus;
for f=frames
if(f<0), sw.addframe(pad); continue; end
sr.seek(f); [I,ts]=sr.getframeb(); k=k+1; tocStatus(tid,k/n);
if(ordered), sw.addframeb(I,ts); else sw.addframeb(I); end
end; sw.close(); sr.close();
end
function Is = toImgs( fName, tDir, skip, f0, f1, ext )
% Extract images from seq file to target directory or array.
%
% USAGE
% Is = seqIo( fName, 'toImgs', [tDir], [skip], [f0], [f1], [ext] )
%
% INPUTS
% fName - seq file name
% tDir - [] target directory (if empty extract images to array)
% skip - [1] skip between written frames
% f0 - [0] first frame to write
% f1 - [numFrames-1] last frame to write
% ext - [] optionally save as given type (slow, reconverts)
%
% OUTPUTS
% Is - if isempty(tDir) outputs image array (else Is=[])
%
% EXAMPLE
%
% See also seqIo
if(nargin<2 || isempty(tDir)), tDir=[]; end
if(nargin<3 || isempty(skip)), skip=1; end
if(nargin<4 || isempty(f0)), f0=0; end
if(nargin<5 || isempty(f1)), f1=inf; end
if(nargin<6 || isempty(ext)), ext=''; end
sr=reader(fName); info=sr.getinfo(); f1=min(f1,info.numFrames-1);
frames=f0:skip:f1; n=length(frames); tid=ticStatus; k=0;
% output images to array
if(isempty(tDir))
I=sr.getnext(); d=ndims(I); assert(d==2 || d==3);
try Is=zeros([size(I) n],class(I)); catch e; sr.close(); throw(e); end
for k=1:n, sr.seek(frames(k)); I=sr.getframe(); tocStatus(tid,k/n);
if(d==2), Is(:,:,k)=I; else Is(:,:,:,k)=I; end; end
sr.close(); return;
end
% output images to directory
if(~exist(tDir,'dir')), mkdir(tDir); end; Is=[];
for frame=frames
f=[tDir '/I' int2str2(frame,5) '.']; sr.seek(frame);
if(~isempty(ext)), I=sr.getframe(); imwrite(I,[f ext]); else
I=sr.getframeb(); f=fopen([f info.ext],'w');
if(f<=0), sr.close(); assert(false); end
fwrite(f,I); fclose(f);
end; k=k+1; tocStatus(tid,k/n);
end; sr.close();
end
function frImgs( fName, info, varargin )
% Create seq file from an array or directory of images or from an AVI file.
%
% For info, if converting from array, only codec (e.g., 'jpg') and fps must
% be specified while width and height and determined automatically. If
% converting from AVI, fps is also determined automatically.
%
% USAGE
% seqIo( fName, 'frImgs', info, varargin )
%
% INPUTS
% fName - seq file name
% info - defines codec, etc, see seqIo>writer
% varargin - additional params (struct or name/value pairs)
% .aviName - [] if specified create seq from avi file
% .Is - [] if specified create seq from image array
% .sDir - [] source directory
% .skip - [1] skip between frames
% .name - ['I'] base name of images
% .nDigits - [5] number of digits for filename index
% .f0 - [0] first frame to read
% .f1 - [10^6] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo, seqIo>writer
dfs={'aviName','','Is',[],'sDir',[],'skip',1,'name','I',...
'nDigits',5,'f0',0,'f1',10^6};
[aviName,Is,sDir,skip,name,nDigits,f0,f1] ...
= getPrmDflt(varargin,dfs,1);
if(~isempty(aviName))
if(exist('mmread.m','file')==2) % use external mmread function
% mmread requires full pathname, which is obtained via 'which'. But,
% 'which' can fail (maltab bug), so best to just pass in full pathname
t=which(aviName); if(~isempty(t)), aviName=t; end
V=mmread(aviName); n=V.nrFramesTotal;
info.height=V.height; info.width=V.width; info.fps=V.rate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(V.frames(f).cdata); tocStatus(tid,f/n); end
sw.close();
else % use matlab mmreader function
emsg=['mmreader.m failed to load video. In general mmreader.m is ' ...
'known to have many issues, especially on Linux. I suggest ' ...
'installing the similarly named mmread toolbox from Micah ' ...
'Richert, available at Matlab Central. If mmread is installed, ' ...
'seqIo will automatically use mmread instead of mmreader.'];
try V=mmreader(aviName); catch %#ok<DMMR,CTCH>
error('piotr:seqIo:frImgs',emsg); end; n=V.NumberOfFrames;
info.height=V.Height; info.width=V.Width; info.fps=V.FrameRate;
sw=writer(fName,info); tid=ticStatus('creating seq from avi');
for f=1:n, sw.addframe(read(V,f)); tocStatus(tid,f/n); end
sw.close();
end
elseif( isempty(Is) )
assert(exist(sDir,'dir')==7); sw=writer(fName,info); info=sw.getinfo();
frmStr=sprintf('%s/%s%%0%ii.%s',sDir,name,nDigits,info.ext);
for frame = f0:skip:f1
f=sprintf(frmStr,frame); if(~exist(f,'file')), break; end
f=fopen(f,'r'); if(f<=0), sw.close(); assert(false); end
I=fread(f); fclose(f); sw.addframeb(I);
end; sw.close();
if(frame==f0), warning('No images found.'); end %#ok<WNTAG>
else
nd=ndims(Is); if(nd==2), nd=3; end; assert(nd<=4); nFrm=size(Is,nd);
info.height=size(Is,1); info.width=size(Is,2); sw=writer(fName,info);
if(nd==3), for f=1:nFrm, sw.addframe(Is(:,:,f)); end; end
if(nd==4), for f=1:nFrm, sw.addframe(Is(:,:,:,f)); end; end
sw.close();
end
end
function convert( fName, tName, imgFun, varargin )
% Convert seq file by applying imgFun(I) to each frame I.
%
% USAGE
% seqIo( fName, 'convert', tName, imgFun, varargin )
%
% INPUTS
% fName - seq file name
% tName - converted seq file name
% imgFun - function to apply to each image
% varargin - additional params (struct or name/value pairs)
% .info - [] info for target seq file
% .skip - [1] skip between frames
% .f0 - [0] first frame to read
% .f1 - [inf] last frame to read
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
dfs={'info',[],'skip',1,'f0',0,'f1',inf};
[info,skip,f0,f1]=getPrmDflt(varargin,dfs,1);
assert(~strcmp(tName,fName)); sr=reader(fName); infor=sr.getinfo();
if(isempty(info)), info=infor; end; n=infor.numFrames; f1=min(f1,n-1);
I=sr.getnext(); I=imgFun(I); info.width=size(I,2); info.height=size(I,1);
sw=writer(tName,info); tid=ticStatus('converting seq');
frames=f0:skip:f1; n=length(frames); k=0;
for f=frames, sr.seek(f); [I,ts]=sr.getframe(); I=imgFun(I);
if(skip==1), sw.addframe(I,ts); else sw.addframe(I); end
k=k+1; tocStatus(tid,k/n);
end; sw.close(); sr.close();
end
function newHeader( fName, info )
% Replace header of seq file with provided info.
%
% Can be used if the file fName has a corrupt header. Automatically tries
% to compute number of frames in fName. No guarantees that it will work.
%
% USAGE
% seqIo( fName, 'newHeader', info )
%
% INPUTS
% fName - seq file name
% info - info for target seq file
%
% OUTPUTS
%
% EXAMPLE
%
% See also seqIo
[d,n]=fileparts(fName); if(isempty(d)), d='.'; end
fName=[d '/' n]; tName=[fName '-new' datestr(now,30)];
if(exist([fName '-seek.mat'],'file')); delete([fName '-seek.mat']); end
srp=@seqReaderPlugin; hr=srp('open',int32(-1),fName,info); tid=ticStatus;
info=srp('getinfo',hr); sw=writer(tName,info); n=info.numFrames;
for f=1:n, srp('next',hr); [I,ts]=srp('getframeb',hr);
sw.addframeb(I,ts); tocStatus(tid,f/n); end
srp('close',hr); sw.close();
end
function sr = readerDual( fNames, cache )
% Create interface sr for reading dual seq files.
%
% Wrapper for two seq files of the same image dims and roughly the same
% frame counts that are treated as a single reader object. getframe()
% returns the concatentation of the two frames. For videos of different
% frame counts, the first video serves as the "dominant" video and the
% frame count of the second video is adjusted accordingly. Same general
% usage as in reader, but the only supported operations are: close(),
% getframe(), getinfo(), and seek().
%
% USAGE
% sr = seqIo( fNames, 'readerDual', [cache] )
%
% INPUTS
% fNames - two seq file names
% cache - [0] size of cache (see seqIo>reader)
%
% OUTPUTS
% sr - interface for reading seq file
%
% EXAMPLE
%
% See also seqIo, seqIo>reader
if(nargin<2 || isempty(cache)), cache=0; end
s1=reader(fNames{1}, cache); i1=s1.getinfo();
s2=reader(fNames{2}, cache); i2=s2.getinfo();
info=i1; info.width=i1.width+i2.width;
if( i1.width~=i2.width || i1.height~=i2.height )
s1.close(); s2.close(); error('Mismatched videos'); end
if( i1.numFrames~=i2.numFrames )
warning('seq files of different lengths'); end %#ok<WNTAG>
frame2=@(f) round(f/(i1.numFrames-1)*(i2.numFrames-1));
sr=struct('close',@() min(s1.close(),s2.close()), ...
'getframe',@getframe, 'getinfo',@() info, ...
'seek',@(f) s1.seek(f) & s2.seek(frame2(f)) );
function [I,t] = getframe()
[I1,t]=s1.getframe(); I2=s2.getframe(); I=[I1 I2]; end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
seqReaderPlugin.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/videos/seqReaderPlugin.m
| 9,617 |
utf_8
|
ad8f912634cafe13df6fc7d67aeff05a
|
function varargout = seqReaderPlugin( cmd, h, varargin )
% Plugin for seqIo and videoIO to allow reading of seq files.
%
% Do not call directly, use as plugin for seqIo or videoIO instead.
% The following is a list of commands available (srp=seqReaderPlugin):
% h = srp('open',h,fName) % Open a seq file for reading (h ignored).
% h = srp('close',h); % Close seq file (output h is -1).
% [I,ts] =srp('getframe',h) % Get current frame (returns [] if invalid).
% [I,ts] =srp('getframeb',h) % Get current frame with no decoding.
% ts = srp('getts',h) % Return timestamps for all frames.
% info = srp('getinfo',h) % Return struct with info about video.
% [I,ts] =srp('getnext',h) % Shortcut for 'next' followed by 'getframe'.
% out = srp('next',h) % Go to next frame (out=0 on fail).
% out = srp('seek',h,frame) % Go to specified frame (out=0 on fail).
% out = srp('step',h,delta) % Go to current frame+delta (out=0 on fail).
%
% USAGE
% varargout = seqReaderPlugin( cmd, h, varargin )
%
% INPUTS
% cmd - string indicating operation to perform
% h - unique identifier for open seq file
% varargin - additional options (vary according to cmd)
%
% OUTPUTS
% varargout - output (varies according to cmd)
%
% EXAMPLE
%
% See also SEQIO, SEQWRITERPLUGIN
%
% Piotr's Computer Vision Matlab Toolbox Version 3.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% persistent variables to keep track of all loaded .seq files
persistent h1 hs cs fids infos tNms;
if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end
nIn=nargin-2; in=varargin; o2=[]; cmd=lower(cmd);
% open seq file
if(strcmp(cmd,'open'))
chk(nIn,1,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1;
[pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end
if(nIn==1), info=[]; else info=in{2}; end
fName=[pth filesep name]; cs(h)=-1;
[infos{h},fids(h),tNms{h}]=open(fName,info); return;
end
% Get the handle for this instance
[v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end
c=cs(h); fid=fids(h); info=infos{h}; tNm=tNms{h};
% close seq file
if(strcmp(cmd,'close'))
chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)];
hs=hs(kp); cs=cs(kp); fids=fids(kp); infos=infos(kp);
tNms=tNms(kp); if(exist(tNm,'file')), delete(tNm); end; return;
end
% perform appropriate operation
switch( cmd )
case 'getframe', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'getframeb', chk(nIn,0); [o1,o2]=getFrame(c,fid,info,tNm,0);
case 'getts', chk(nIn,0); o1=getTs(0:info.numFrames-1,fid,info);
case 'getinfo', chk(nIn,0); o1=info; o1.curFrame=c;
case 'getnext', chk(nIn,0); c=c+1; [o1,o2]=getFrame(c,fid,info,tNm,1);
case 'next', chk(nIn,0); [c,o1]=valid(c+1,info);
case 'seek', chk(nIn,1); [c,o1]=valid(in{1},info);
case 'step', chk(nIn,1); [c,o1]=valid(c+in{1},info);
otherwise, error(['Unrecognized command: "' cmd '"']);
end
cs(h)=c; varargout={o1,o2};
end
function chk(nIn,nMin,nMax)
if(nargin<3), nMax=nMin; end
if(nIn>0 && nMin==0 && nMax==0), error(['"' cmd '" takes no args.']); end
if(nIn<nMin||nIn>nMax), error(['Incorrect num args for "' cmd '".']); end
end
function success = getImgFile( fName )
% create local copy of fName which is in a imagesci/private
fName = [fName '.' mexext]; s = filesep; success = 1;
sName = [fileparts(which('imread.m')) s 'private' s fName];
tName = [fileparts(mfilename('fullpath')) s 'private' s fName];
if(~exist(tName,'file')), success=copyfile(sName,tName); end
end
function [info, fid, tNm] = open( fName, info )
% open video for reading, get header
if(exist([fName '.seq'],'file')==0)
error('seq file not found: %s.seq',fName); end
fid=fopen([fName '.seq'],'r','l');
if(isempty(info)), info=readHeader(fid); else
info.numFrames=0; fseek(fid,1024,'bof'); end
switch(info.imageFormat)
case {100,200}, ext='raw';
case {101 }, ext='brgb8';
case {102,201}, ext='jpg';
case {103 }, ext ='jbrgb';
case {001,002}, ext='png';
otherwise, error('unknown format');
end; info.ext=ext; s=1;
if(any(strcmp(ext,{'jpg','jbrgb'}))), s=getImgFile('rjpg8c'); end
if(strcmp(ext,'png')), s=getImgFile('png');
if(s), info.readImg=@(nm) png('read',nm,[]); end; end
if(strcmp(ext,'png') && ~s), s=getImgFile('pngreadc');
if(s), info.readImg=@(nm) pngreadc(nm,[],false); end; end
if(~s), error('Cannot find Matlab''s source image reader'); end
% generate unique temporary name
[~,tNm]=fileparts(fName); t=clock; t=mod(t(end),1);
tNm=sprintf('tmp_%s_%15i.%s',tNm,round((t+rand)/2*1e15),ext);
% compute seek info for compressed images
if(any(strcmp(ext,{'raw','brgb8'}))), assert(info.numFrames>0); else
oName=[fName '-seek.mat']; n=info.numFrames; if(n==0), n=10^7; end
if(exist(oName,'file')==2), load(oName); info.seek=seek; else %#ok<NODEF>
tid=ticStatus('loading seek info',.1,5); seek=zeros(n,1); seek(1)=1024;
extra=8; % extra bytes after image data (8 for ts, then 0 or 8 empty)
for i=2:n
s=seek(i-1)+fread(fid,1,'uint32')+extra; valid=fseek(fid,s,'bof')==0;
if(i==2 && valid), if(fread(fid,1,'uint32')~=0), fseek(fid,-4,'cof');
else extra=extra+8; s=s+8; valid=fseek(fid,s,'bof')==0; end; end
if(valid), seek(i)=s; tocStatus(tid,i/n);
else n=i-1; seek=seek(1:n); tocStatus(tid,1); break; end
end; if(info.numFrames==0), info.numFrames=n; end
try save(oName,'seek'); catch; end; info.seek=seek; %#ok<CTCH>
end
end
% compute frame rate from timestamps as stored fps may be incorrect
n=min(100,info.numFrames); if(n==1), return; end
ts = getTs( 0:(n-1), fid, info );
ds=ts(2:end)-ts(1:end-1); ds=ds(abs(ds-median(ds))<.005);
if(~isempty(ds)), info.fps=1/mean(ds); end
end
function [frame,v] = valid( frame, info )
v=(frame>=0 && frame<info.numFrames);
end
function [I,ts] = getFrame( frame, fid, info, tNm, decode )
% get frame image (I) and timestamp (ts) at which frame was recorded
nCh=info.imageBitDepth/8; ext=info.ext;
if(frame<0 || frame>=info.numFrames), I=[]; ts=[]; return; end
switch ext
case {'raw','brgb8'}
% read in an uncompressed image (assume imageBitDepthReal==8)
fseek(fid,1024+frame*info.trueImageSize,'bof');
I = fread(fid,info.imageSizeBytes,'*uint8');
if( decode )
% reshape appropriately for mxn or mxnx3 RGB image
siz = [info.height info.width nCh];
if(nCh==1), I=reshape(I,siz(2),siz(1))'; else
I = permute(reshape(I,siz(3),siz(2),siz(1)),[3,2,1]);
end
if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end
if(strcmp(ext,'brgb8')), I=demosaic(I,'bggr'); end
end
case {'jpg','jbrgb'}
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .jpg (not that much overhead)
assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=rjpg8c(tNm);
if(strcmp(ext,'jbrgb')), I=demosaic(I,'bggr'); end
end
case 'png'
fseek(fid,info.seek(frame+1),'bof'); nBytes=fread(fid,1,'uint32');
I = fread(fid,nBytes-4,'*uint8');
if( decode )
% write/read to/from temporary .png (not that much overhead)
for t=0:99, fw=fopen(tNm,'w'); if(fw>=0), break; end; pause(.01); end
if(fw==-1), error(['unable to write: ' tNm]); end
fwrite(fw,I); fclose(fw); I=info.readImg(tNm);
I=permute(I,ndims(I):-1:1);
end
otherwise, assert(false);
end
if(nargout==2), ts=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000; end
end
function ts = getTs( frames, fid, info )
% get timestamps (ts) at which frames were recorded
n=length(frames); ts=nan(1,n);
for i=1:n, frame=frames(i);
if(frame<0 || frame>=info.numFrames), continue; end
switch info.ext
case {'raw','brgb8'} % uncompressed
fseek(fid,1024+frame*info.trueImageSize+info.imageSizeBytes,'bof');
case {'jpg','png','jbrgb'} % compressed
fseek(fid,info.seek(frame+1),'bof');
fseek(fid,fread(fid,1,'uint32')-4,'cof');
otherwise, assert(false);
end
ts(i)=fread(fid,1,'uint32')+fread(fid,1,'uint16')/1000;
end
end
function info = readHeader( fid )
% see streampix manual for info on header
fseek(fid,0,'bof');
% check that header is not all 0's (a common error)
[tmp,n]=fread(fid,1024); if(n<1024), error('no header'); end
if(all(tmp==0)), error('fully empty header'); end; fseek(fid,0,'bof');
% first 4 bytes store OxFEED, next 24 store 'Norpix seq '
if( ~strcmp(sprintf('%X',fread(fid,1,'uint32')),'FEED') || ...
~strcmp(char(fread(fid,10,'uint16'))','Norpix seq') ) %#ok<FREAD>
error('invalid header');
end; fseek(fid,4,'cof');
% next 8 bytes for version and header size (1024), then 512 for descr
version=fread(fid,1,'int32'); assert(fread(fid,1,'uint32')==1024);
descr=char(fread(fid,256,'uint16'))'; %#ok<FREAD>
% read in more info
tmp=fread(fid,9,'uint32'); assert(tmp(8)==0);
fps = fread(fid,1,'float64'); codec=['imageFormat' int2str2(tmp(6),3)];
% store information in info struct
info=struct( 'width',tmp(1), 'height',tmp(2), 'imageBitDepth',tmp(3), ...
'imageBitDepthReal',tmp(4), 'imageSizeBytes',tmp(5), ...
'imageFormat',tmp(6), 'numFrames',tmp(7), 'trueImageSize', tmp(9),...
'fps',fps, 'seqVersion',version, 'codec',codec, 'descr',descr, ...
'nHiddenFinalFrames',0 );
assert(info.imageBitDepthReal==8);
% seek to end of header
fseek(fid,432,'cof');
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
pcaApply.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/pcaApply.m
| 3,320 |
utf_8
|
a06fc0e54d85930cbc0536c874ac63b7
|
function varargout = pcaApply( X, U, mu, k )
% Companion function to pca.
%
% Use pca.m to retrieve the principal components U and the mean mu from a
% set of vectors x, then use pcaApply to get the first k coefficients of
% x in the space spanned by the columns of U. See pca for general usage.
%
% If x is large, pcaApply first splits and processes x in parts. This
% allows pcaApply to work even for very large arrays.
%
% This may prove useful:
% siz=size(X); k=100; Uim=reshape(U(:,1:k),[siz(1:end-1) k ]);
%
% USAGE
% [ Yk, Xhat, avsq ] = pcaApply( X, U, mu, k )
%
% INPUTS
% X - data for which to get PCA coefficients
% U - returned by pca.m
% mu - returned by pca.m
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCAVISUALIZE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% sizes / dimensions
siz = size(X); nd = ndims(X); [D,r] = size(U);
if(D==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
n = siz(end);
% some error checking
if(prod(siz(1:end-1))~=D); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if(k>r); warning(['k set to ' int2str(r)]); k=r; end; %#ok<WNTAG>
% If X is small simply call pcaApply1 once.
% OW break up X and call pcaApply1 multiple times and recombine.
maxWidth = ceil( (10^7) / D );
if( maxWidth > n )
varargout = cell(1,nargout);
[varargout{:}] = pcaApply1( X, U, mu, k );
else
inds = {':'}; inds = inds(:,ones(1,nd-1));
Yk = zeros( k, n ); Xhat = zeros( siz );
avsq = 0; avsqOrig = 0; last = 0;
if( nargout==3 ); out=cell(1,4); else out=cell(1,nargout); end;
while(last < n)
first=last+1; last=min(first+maxWidth-1,n);
Xi = X(inds{:}, first:last);
[out{:}] = pcaApply1( Xi, U, mu, k );
Yk(:,first:last) = out{1};
if( nargout>=2 ); Xhat(inds{:},first:last)=out{2}; end;
if( nargout>=3 ); avsq=avsq+out{3}; avsqOrig=avsqOrig+out{4}; end;
end;
varargout = {Yk, Xhat, avsq/avsqOrig};
end
function [ Yk, Xhat, avsq, avsqOrig ] = pcaApply1( X, U, mu, k )
% sizes / dimensions
siz = size(X); nd = ndims(X); [D,r] = size(U);
if(D==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
n = siz(end);
% subtract mean, then flatten X
Xorig = X;
muRep = repmat(mu, [ones(1,nd-1), n ] );
X = X - muRep;
X = reshape( X, D, n );
% Find Yk, the first k coefficients of X in the new basis
if( r<=k ); Uk=U; else Uk=U(:,1:k); end;
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + muRep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if( nargout==3 ); avsq=avsq/avsqOrig; end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
forestTrain.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/forestTrain.m
| 6,138 |
utf_8
|
de534e2a010f452a7b13167dbf9df239
|
function forest = forestTrain( data, hs, varargin )
% Train random forest classifier.
%
% Dimensions:
% M - number trees
% F - number features
% N - number input vectors
% H - number classes
%
% USAGE
% forest = forestTrain( data, hs, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% hs - [Nx1] or {Nx1} target output labels in [1,H]
% varargin - additional params (struct or name/value pairs)
% .M - [1] number of trees to train
% .H - [max(hs)] number of classes
% .N1 - [5*N/M] number of data points for training each tree
% .F1 - [sqrt(F)] number features to sample for each node split
% .split - ['gini'] options include 'gini', 'entropy' and 'twoing'
% .minCount - [1] minimum number of data points to allow split
% .minChild - [1] minimum number of data points allowed at child nodes
% .maxDepth - [64] maximum depth of tree
% .dWts - [] weights used for sampling and weighing each data point
% .fWts - [] weights used for sampling features
% .discretize - [] optional function mapping structured to class labels
% format: [hsClass,hBest] = discretize(hsStructured,H);
%
% OUTPUTS
% forest - learned forest model struct array w the following fields
% .fids - [Kx1] feature ids for each node
% .thrs - [Kx1] threshold corresponding to each fid
% .child - [Kx1] index of child for each node
% .distr - [KxH] prob distribution at each node
% .hs - [Kx1] or {Kx1} most likely label at each node
% .count - [Kx1] number of data points at each node
% .depth - [Kx1] depth of each node
%
% EXAMPLE
% N=10000; H=5; d=2; [xs0,hs0,xs1,hs1]=demoGenData(N,N,H,d,1,1);
% xs0=single(xs0); xs1=single(xs1);
% pTrain={'maxDepth',50,'F1',2,'M',150,'minChild',5};
% tic, forest=forestTrain(xs0,hs0,pTrain{:}); toc
% hsPr0 = forestApply(xs0,forest);
% hsPr1 = forestApply(xs1,forest);
% e0=mean(hsPr0~=hs0); e1=mean(hsPr1~=hs1);
% fprintf('errors trn=%f tst=%f\n',e0,e1); figure(1);
% subplot(2,2,1); visualizeData(xs0,2,hs0);
% subplot(2,2,2); visualizeData(xs0,2,hsPr0);
% subplot(2,2,3); visualizeData(xs1,2,hs1);
% subplot(2,2,4); visualizeData(xs1,2,hsPr1);
%
% See also forestApply, fernsClfTrain
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get additional parameters and fill in remaining parameters
dfs={ 'M',1, 'H',[], 'N1',[], 'F1',[], 'split','gini', 'minCount',1, ...
'minChild',1, 'maxDepth',64, 'dWts',[], 'fWts',[], 'discretize','' };
[M,H,N1,F1,splitStr,minCount,minChild,maxDepth,dWts,fWts,discretize] = ...
getPrmDflt(varargin,dfs,1);
[N,F]=size(data); assert(length(hs)==N); discr=~isempty(discretize);
minChild=max(1,minChild); minCount=max([1 minCount minChild]);
if(isempty(H)), H=max(hs); end; assert(discr || all(hs>0 & hs<=H));
if(isempty(N1)), N1=round(5*N/M); end; N1=min(N,N1);
if(isempty(F1)), F1=round(sqrt(F)); end; F1=min(F,F1);
if(isempty(dWts)), dWts=ones(1,N,'single'); end; dWts=dWts/sum(dWts);
if(isempty(fWts)), fWts=ones(1,F,'single'); end; fWts=fWts/sum(fWts);
split=find(strcmpi(splitStr,{'gini','entropy','twoing'}))-1;
if(isempty(split)), error('unknown splitting criteria: %s',splitStr); end
% make sure data has correct types
if(~isa(data,'single')), data=single(data); end
if(~isa(hs,'uint32') && ~discr), hs=uint32(hs); end
if(~isa(fWts,'single')), fWts=single(fWts); end
if(~isa(dWts,'single')), dWts=single(dWts); end
% train M random trees on different subsets of data
prmTree = {H,F1,minCount,minChild,maxDepth,fWts,split,discretize};
for i=1:M
if(N==N1), data1=data; hs1=hs; dWts1=dWts; else
d=wswor(dWts,N1,4); data1=data(d,:); hs1=hs(d);
dWts1=dWts(d); dWts1=dWts1/sum(dWts1);
end
tree = treeTrain(data1,hs1,dWts1,prmTree);
if(i==1), forest=tree(ones(M,1)); else forest(i)=tree; end
end
end
function tree = treeTrain( data, hs, dWts, prmTree )
% Train single random tree.
[H,F1,minCount,minChild,maxDepth,fWts,split,discretize]=deal(prmTree{:});
N=size(data,1); K=2*N-1; discr=~isempty(discretize);
thrs=zeros(K,1,'single'); distr=zeros(K,H,'single');
fids=zeros(K,1,'uint32'); child=fids; count=fids; depth=fids;
hsn=cell(K,1); dids=cell(K,1); dids{1}=uint32(1:N); k=1; K=2;
while( k < K )
% get node data and store distribution
dids1=dids{k}; dids{k}=[]; hs1=hs(dids1); n1=length(hs1); count(k)=n1;
if(discr), [hs1,hsn{k}]=feval(discretize,hs1,H); hs1=uint32(hs1); end
if(discr), assert(all(hs1>0 & hs1<=H)); end; pure=all(hs1(1)==hs1);
if(~discr), if(pure), distr(k,hs1(1))=1; hsn{k}=hs1(1); else
distr(k,:)=histc(hs1,1:H)/n1; [~,hsn{k}]=max(distr(k,:)); end; end
% if pure node or insufficient data don't train split
if( pure || n1<=minCount || depth(k)>maxDepth ), k=k+1; continue; end
% train split and continue
fids1=wswor(fWts,F1,4); data1=data(dids1,fids1);
[~,order1]=sort(data1); order1=uint32(order1-1);
[fid,thr,gain]=forestFindThr(data1,hs1,dWts(dids1),order1,H,split);
fid=fids1(fid); left=data(dids1,fid)<thr; count0=nnz(left);
if( gain>1e-10 && count0>=minChild && (n1-count0)>=minChild )
child(k)=K; fids(k)=fid-1; thrs(k)=thr;
dids{K}=dids1(left); dids{K+1}=dids1(~left);
depth(K:K+1)=depth(k)+1; K=K+2;
end; k=k+1;
end
% create output model struct
K=1:K-1; if(discr), hsn={hsn(K)}; else hsn=[hsn{K}]'; end
tree=struct('fids',fids(K),'thrs',thrs(K),'child',child(K),...
'distr',distr(K,:),'hs',hsn,'count',count(K),'depth',depth(K));
end
function ids = wswor( prob, N, trials )
% Fast weighted sample without replacement. Alternative to:
% ids=datasample(1:length(prob),N,'weights',prob,'replace',false);
M=length(prob); assert(N<=M); if(N==M), ids=1:N; return; end
if(all(prob(1)==prob)), ids=randperm(M,N); return; end
cumprob=min([0 cumsum(prob)],1); assert(abs(cumprob(end)-1)<.01);
cumprob(end)=1; [~,ids]=histc(rand(N*trials,1),cumprob);
[s,ord]=sort(ids); K(ord)=[1; diff(s)]~=0; ids=ids(K);
if(length(ids)<N), ids=wswor(cumprob,N,trials*2); end
ids=ids(1:N)';
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
fernsRegTrain.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/fernsRegTrain.m
| 5,914 |
utf_8
|
b9ed2d87a22cb9cbb1e2632495ddaf1d
|
function [ferns,ysPr] = fernsRegTrain( data, ys, varargin )
% Train boosted fern regressor.
%
% Boosted regression using random ferns as the weak regressor. See "Greedy
% function approximation: A gradient boosting machine", Friedman, Annals of
% Statistics 2001, for more details on boosted regression.
%
% A few notes on the parameters: 'type' should in general be set to 'res'
% (the 'ave' version is an undocumented variant that only performs well
% under limited conditions). 'loss' determines the loss function being
% optimized, in general the 'L2' version is the most robust and effective.
% 'reg' is a regularization term for the ferns, a low value such as .01 can
% improve results. Setting the learning rate 'eta' is crucial in order to
% achieve good performance, especially on noisy data. In general, eta
% should decreased as M is increased.
%
% Dimensions:
% M - number ferns
% R - number repeats
% S - fern depth
% N - number samples
% F - number features
%
% USAGE
% [ferns,ysPr] = fernsRegTrain( data, hs, [varargin] )
%
% INPUTS
% data - [NxF] N length F feature vectors
% ys - [Nx1] target output values
% varargin - additional params (struct or name/value pairs)
% .type - ['res'] options include {'res','ave'}
% .loss - ['L2'] options include {'L1','L2','exp'}
% .S - [2] fern depth (ferns are exponential in S)
% .M - [50] number ferns (same as number phases)
% .R - [10] number repetitions per fern
% .thrr - [0 1] range for randomly generated thresholds
% .reg - [0.01] fern regularization term in [0,1]
% .eta - [1] learning rate in [0,1] (not used if type='ave')
% .verbose - [0] if true output info to display
%
% OUTPUTS
% ferns - learned fern model w the following fields
% .fids - [MxS] feature ids for each fern for each depth
% .thrs - [MxS] threshold corresponding to each fid
% .ysFern - [2^SxM] stored values at fern leaves
% .loss - loss(ys,ysGt) computes loss of ys relateive to ysGt
% ysPr - [Nx1] predicted output values
%
% EXAMPLE
% %% generate toy data
% N=1000; sig=.5; f=@(x) cos(x*pi*4)+(x+1).^2;
% xs0=rand(N,1); ys0=f(xs0)+randn(N,1)*sig;
% xs1=rand(N,1); ys1=f(xs1)+randn(N,1)*sig;
% %% train and apply fern regressor
% prm=struct('type','res','loss','L2','eta',.05,...
% 'thrr',[-1 1],'reg',.01,'S',2,'M',1000,'R',3,'verbose',0);
% tic, [ferns,ysPr0] = fernsRegTrain(xs0,ys0,prm); toc
% tic, ysPr1 = fernsRegApply( xs1, ferns ); toc
% fprintf('errors train=%f test=%f\n',...
% ferns.loss(ysPr0,ys0),ferns.loss(ysPr1,ys1));
% %% visualize results
% figure(1); clf; hold on; plot(xs0,ys0,'.b'); plot(xs0,ysPr0,'.r');
% figure(2); clf; hold on; plot(xs1,ys1,'.b'); plot(xs1,ysPr1,'.r');
%
% See also fernsRegApply, fernsInds
%
% Piotr's Computer Vision Matlab Toolbox Version 2.50
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get/check parameters
dfs={'type','res','loss','L2','S',2,'M',50,'R',10,'thrr',[0 1],...
'reg',0.01,'eta',1,'verbose',0};
[type,loss,S,M,R,thrr,reg,eta,verbose]=getPrmDflt(varargin,dfs,1);
type=type(1:3); assert(any(strcmp(type,{'res','ave'})));
assert(any(strcmp(loss,{'L1','L2','exp'}))); N=length(ys);
if(strcmp(type,'ave')), eta=1; end
% train stagewise regressor (residual or average)
fids=zeros(M,S,'uint32'); thrs=zeros(M,S);
ysSum=zeros(N,1); ysFern=zeros(2^S,M);
for m=1:M
% train R random ferns using different losses, keep best
if(strcmp(type,'ave')), d=m; else d=1; end
ysTar=d*ys-ysSum; best={};
if(strcmp(loss,'L1')), e=sum(abs(ysTar));
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,sign(ysTar),S,thrr,reg);
a=medianw(ysTar./ys1,abs(ys1)); ysFern1=ysFern1*a; ys1=ys1*a;
e1=sum(abs(ysTar-ys1));
if(e1<=e), e=e1; best={fids1,thrs1,ysFern1,ys1}; end
end
elseif(strcmp(loss,'L2')), e=sum(ysTar.^2);
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,ysTar,S,thrr,reg);
e1=sum((ysTar-ys1).^2);
if(e1<=e), e=e1; best={fids1,thrs1,ysFern1,ys1}; end
end
elseif(strcmp(loss,'exp')), e=sum(exp(ysTar/d)+exp(-ysTar/d));
ysDeriv=exp(ysTar/d)-exp(-ysTar/d);
for r=1:R
[fids1,thrs1,ysFern1,ys1]=trainFern(data,ysDeriv,S,thrr,reg);
e1=inf; if(m==1), aBst=1; end; aMin=aBst/5; aMax=aBst*5;
for phase=1:3, aDel=(aMax-aMin)/10;
for a=aMin:aDel:aMax
eTmp=sum(exp((ysTar-a*ys1)/d)+exp((a*ys1-ysTar)/d));
if(eTmp<e1), a1=a; e1=eTmp; end
end; aMin=a1-aDel; aMax=a1+aDel;
end; ysFern1=ysFern1*a1; ys1=ys1*a1;
if(e1<=e), e=e1; aBst=a1; best={fids1,thrs1,ysFern1,ys1}; end
end
end
% store results and update sums
assert(~isempty(best)); [fids1,thrs1,ysFern1,ys1]=deal(best{:});
fids(m,:)=fids1; thrs(m,:)=thrs1;
ysFern(:,m)=ysFern1*eta; ysSum=ysSum+ys1*eta;
if(verbose), fprintf('phase=%i error=%f\n',m,e); end
end
% create output struct
if(strcmp(type,'ave')), d=M; else d=1; end; clear data;
ferns=struct('fids',fids,'thrs',thrs,'ysFern',ysFern/d); ysPr=ysSum/d;
switch loss
case 'L1', ferns.loss=@(ys,ysGt) mean(abs(ys-ysGt));
case 'L2', ferns.loss=@(ys,ysGt) mean((ys-ysGt).^2);
case 'exp', ferns.loss=@(ys,ysGt) mean(exp(ys-ysGt)+exp(ysGt-ys))-2;
end
end
function [fids,thrs,ysFern,ysPr] = trainFern( data, ys, S, thrr, reg )
% Train single random fern regressor.
[N,F]=size(data); mu=sum(ys)/N; ys=ys-mu;
fids = uint32(floor(rand(1,S)*F+1));
thrs = rand(1,S)*(thrr(2)-thrr(1))+thrr(1);
inds = fernsInds(data,fids,thrs);
ysFern=zeros(2^S,1); cnts=zeros(2^S,1);
for n=1:N, ind=inds(n);
ysFern(ind)=ysFern(ind)+ys(n);
cnts(ind)=cnts(ind)+1;
end
ysFern = ysFern ./ max(cnts+reg*N,eps) + mu;
ysPr = ysFern(inds);
end
function m = medianw(x,w)
% Compute weighted median of x.
[x,ord]=sort(x(:)); w=w(ord);
[~,ind]=max(cumsum(w)>=sum(w)/2);
m = x(ind);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
rbfDemo.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/rbfDemo.m
| 2,929 |
utf_8
|
14cc64fb77bcac3edec51cf6b84ab681
|
function rbfDemo( dataType, noiseSig, scale, k, cluster, show )
% Demonstration of rbf networks for regression.
%
% See rbfComputeBasis for discussion of rbfs.
%
% USAGE
% rbfDemo( dataType, noiseSig, scale, k, cluster, show )
%
% INPUTS
% dataType - 0: 1D sinusoid
% 1: 2D sinusoid
% 2: 2D stretched sinusoid
% noiseSig - std of idd gaussian noise
% scale - see rbfComputeBasis
% k - see rbfComputeBasis
% cluster - see rbfComputeBasis
% show - figure to use for display (no display if == 0)
%
% OUTPUTS
%
% EXAMPLE
% rbfDemo( 0, .2, 2, 5, 0, 1 );
% rbfDemo( 1, .2, 2, 50, 0, 3 );
% rbfDemo( 2, .2, 5, 50, 0, 5 );
%
% See also RBFCOMPUTEBASIS, RBFCOMPUTEFTRS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%%% generate trn/tst data
if( 1 )
[Xtrn,ytrn] = rbfToyData( 500, noiseSig, dataType );
[Xtst,ytst] = rbfToyData( 100, noiseSig, dataType );
end;
%%% trn/apply rbfs
rbfBasis = rbfComputeBasis( Xtrn, k, cluster, scale, show );
rbfWeight = rbfComputeFtrs(Xtrn,rbfBasis) \ ytrn;
yTrnRes = rbfComputeFtrs(Xtrn,rbfBasis) * rbfWeight;
yTstRes = rbfComputeFtrs(Xtst,rbfBasis) * rbfWeight;
%%% get relative errors
fracErrorTrn = sum((ytrn-yTrnRes).^2) / sum(ytrn.^2);
fracErrorTst = sum((ytst-yTstRes).^2) / sum(ytst.^2);
%%% display output
display(fracErrorTst);
display(fracErrorTrn);
display(rbfBasis);
%%% visualize surface
minX = min([Xtrn; Xtst],[],1); maxX = max([Xtrn; Xtst],[],1);
if( size(Xtrn,2)==1 )
xs = linspace( minX, maxX, 1000 )';
ys = rbfComputeFtrs(xs,rbfBasis) * rbfWeight;
figure(show+1); clf; hold on; plot( xs, ys );
plot( Xtrn, ytrn, '.b' ); plot( Xtst, ytst, '.r' );
elseif( size(Xtrn,2)==2 )
xs1 = linspace(minX(1),maxX(1),25);
xs2 = linspace(minX(2),maxX(2),25);
[xs1,xs2] = ndgrid( xs1, xs2 );
ys = rbfComputeFtrs([xs1(:) xs2(:)],rbfBasis) * rbfWeight;
figure(show+1); clf; surf( xs1, xs2, reshape(ys,size(xs1)) ); hold on;
plot3( Xtrn(:,1), Xtrn(:,2), ytrn, '.b' );
plot3( Xtst(:,1), Xtst(:,2), ytst, '.r' );
end
function [X,y] = rbfToyData( N, noiseSig, dataType )
% Toy data for rbfDemo.
%
% USAGE
% [X,y] = rbfToyData( N, noiseSig, dataType )
%
% INPUTS
% N - number of points
% dataType - 0: 1D sinusoid
% 1: 2D sinusoid
% 2: 2D stretched sinusoid
% noiseSig - std of idd gaussian noise
%
% OUTPUTS
% X - [N x d] N points of d dimensions each
% y - [1 x N] value at example i
%%% generate data
if( dataType==0 )
X = rand( N, 1 ) * 10;
y = sin( X );
elseif( dataType==1 )
X = rand( N, 2 ) * 10;
y = sin( X(:,1)+X(:,2) );
elseif( dataType==2 )
X = rand( N, 2 ) * 10;
y = sin( X(:,1)+X(:,2) );
X(:,2) = X(:,2) * 5;
else
error('unknown dataType');
end
y = y + randn(size(y))*noiseSig;
|
github
|
garrickbrazil/SDS-RCNN-master
|
pdist2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/pdist2.m
| 5,162 |
utf_8
|
768ff9e8818251f756c8325368ee7d90
|
function D = pdist2( X, Y, metric )
% Calculates the distance between sets of vectors.
%
% Let X be an m-by-p matrix representing m points in p-dimensional space
% and Y be an n-by-p matrix representing another set of points in the same
% space. This function computes the m-by-n distance matrix D where D(i,j)
% is the distance between X(i,:) and Y(j,:). This function has been
% optimized where possible, with most of the distance computations
% requiring few or no loops.
%
% The metric can be one of the following:
%
% 'euclidean' / 'sqeuclidean':
% Euclidean / SQUARED Euclidean distance. Note that 'sqeuclidean'
% is significantly faster.
%
% 'chisq'
% The chi-squared distance between two vectors is defined as:
% d(x,y) = sum( (xi-yi)^2 / (xi+yi) ) / 2;
% The chi-squared distance is useful when comparing histograms.
%
% 'cosine'
% Distance is defined as the cosine of the angle between two vectors.
%
% 'emd'
% Earth Mover's Distance (EMD) between positive vectors (histograms).
% Note for 1D, with all histograms having equal weight, there is a simple
% closed form for the calculation of the EMD. The EMD between histograms
% x and y is given by the sum(abs(cdf(x)-cdf(y))), where cdf is the
% cumulative distribution function (computed simply by cumsum).
%
% 'L1'
% The L1 distance between two vectors is defined as: sum(abs(x-y));
%
%
% USAGE
% D = pdist2( X, Y, [metric] )
%
% INPUTS
% X - [m x p] matrix of m p-dimensional vectors
% Y - [n x p] matrix of n p-dimensional vectors
% metric - ['sqeuclidean'], 'chisq', 'cosine', 'emd', 'euclidean', 'L1'
%
% OUTPUTS
% D - [m x n] distance matrix
%
% EXAMPLE
% % simple example where points cluster well
% [X,IDX] = demoGenData(100,0,5,4,10,2,0);
% D = pdist2( X, X, 'sqeuclidean' );
% distMatrixShow( D, IDX );
% % comparison to pdist
% n=500; d=200; r=100; X=rand(n,d);
% tic, for i=1:r, D1 = pdist( X, 'euclidean' ); end, toc
% tic, for i=1:r, D2 = pdist2( X, X, 'euclidean' ); end, toc
% D1=squareform(D1); del=D1-D2; sum(abs(del(:)))
%
% See also pdist, distMatrixShow
%
% Piotr's Computer Vision Matlab Toolbox Version 2.52
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(metric) ); metric=0; end;
switch metric
case {0,'sqeuclidean'}
D = distEucSq( X, Y );
case 'euclidean'
D = sqrt(distEucSq( X, Y ));
case 'L1'
D = distL1( X, Y );
case 'cosine'
D = distCosine( X, Y );
case 'emd'
D = distEmd( X, Y );
case 'chisq'
D = distChiSq( X, Y );
otherwise
error(['pdist2 - unknown metric: ' metric]);
end
D = max(0,D);
end
function D = distL1( X, Y )
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yi = yi( mOnes, : );
D(:,i) = sum( abs( X-yi),2 );
end
end
function D = distCosine( X, Y )
p=size(X,2);
XX = sqrt(sum(X.*X,2)); X = X ./ XX(:,ones(1,p));
YY = sqrt(sum(Y.*Y,2)); Y = Y ./ YY(:,ones(1,p));
D = 1 - X*Y';
end
function D = distEmd( X, Y )
Xcdf = cumsum(X,2);
Ycdf = cumsum(Y,2);
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
ycdf = Ycdf(i,:);
ycdfRep = ycdf( mOnes, : );
D(:,i) = sum(abs(Xcdf - ycdfRep),2);
end
end
function D = distChiSq( X, Y )
% note: supposedly it's possible to implement this without a loop!
m = size(X,1); n = size(Y,1);
mOnes = ones(1,m); D = zeros(m,n);
for i=1:n
yi = Y(i,:); yiRep = yi( mOnes, : );
s = yiRep + X; d = yiRep - X;
D(:,i) = sum( d.^2 ./ (s+eps), 2 );
end
D = D/2;
end
function D = distEucSq( X, Y )
Yt = Y';
XX = sum(X.*X,2);
YY = sum(Yt.*Yt,1);
D = bsxfun(@plus,XX,YY)-2*X*Yt;
end
%%%% code from Charles Elkan with variables renamed
% function D = distEucSq( X, Y )
% m = size(X,1); n = size(Y,1);
% D = sum(X.^2, 2) * ones(1,n) + ones(m,1) * sum(Y.^2, 2)' - 2.*X*Y';
% end
%%% LOOP METHOD - SLOW
% [m p] = size(X);
% [n p] = size(Y);
% D = zeros(m,n);
% onesM = ones(m,1);
% for i=1:n
% y = Y(i,:);
% d = X - y(onesM,:);
% D(:,i) = sum( d.*d, 2 );
% end
%%% PARALLEL METHOD THAT IS SUPER SLOW (slower than loop)!
% % From "MATLAB array manipulation tips and tricks" by Peter J. Acklam
% Xb = permute(X, [1 3 2]);
% Yb = permute(Y, [3 1 2]);
% D = sum( (Xb(:,ones(1,n),:) - Yb(ones(1,m),:,:)).^2, 3);
%%% USELESS FOR EVEN VERY LARGE ARRAYS X=16000x1000!! and Y=100x1000
% call recursively to save memory
% if( (m+n)*p > 10^5 && (m>1 || n>1))
% if( m>n )
% X1 = X(1:floor(end/2),:);
% X2 = X((floor(end/2)+1):end,:);
% D1 = distEucSq( X1, Y );
% D2 = distEucSq( X2, Y );
% D = cat( 1, D1, D2 );
% else
% Y1 = Y(1:floor(end/2),:);
% Y2 = Y((floor(end/2)+1):end,:);
% D1 = distEucSq( X, Y1 );
% D2 = distEucSq( X, Y2 );
% D = cat( 2, D1, D2 );
% end
% return;
% end
%%% L1 COMPUTATION WITH LOOP OVER p, FAST FOR SMALL p.
% function D = distL1( X, Y )
%
% m = size(X,1); n = size(Y,1); p = size(X,2);
% mOnes = ones(1,m); nOnes = ones(1,n); D = zeros(m,n);
% for i=1:p
% yi = Y(:,i); yi = yi( :, mOnes );
% xi = X(:,i); xi = xi( :, nOnes );
% D = D + abs( xi-yi' );
% end
|
github
|
garrickbrazil/SDS-RCNN-master
|
pca.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/pca.m
| 3,244 |
utf_8
|
848f2eb05c18a6e448e9d22af27b9422
|
function [U,mu,vars] = pca( X )
% Principal components analysis (alternative to princomp).
%
% A simple linear dimensionality reduction technique. Use to create an
% orthonormal basis for the points in R^d such that the coordinates of a
% vector x in this basis are of decreasing importance. Instead of using all
% d basis vectors to specify the location of x, using only the first k<d
% still gives a vector xhat that is close to x.
%
% This function operates on arrays of arbitrary dimension, by first
% converting the arrays to vectors. If X is m+1 dimensional, say of size
% [d1 x d2 x...x dm x n], then the first m dimensions of X are combined. X
% is flattened to be 2 dimensional: [dxn], with d=prod(di). Once X is
% converted to 2 dimensions of size dxn, each column represents a single
% observation, and each row is a different variable. Note that this is the
% opposite of many matlab functions such as princomp. If X is MxNxn, then
% X(:,:,i) represents the ith observation (useful for stack of n images),
% likewise for n videos X is MxNxKxn. If X is very large, it is sampled
% before running PCA. Use this function to retrieve the basis U. Use
% pcaApply to retrieve that basis coefficients for a novel vector x. Use
% pcaVisualize(X,...) for visualization of approximated X.
%
% To calculate residuals:
% residuals = cumsum(vars/sum(vars)); plot(residuals,'-.')
%
% USAGE
% [U,mu,vars] = pca( X )
%
% INPUTS
% X - [d1 x ... x dm x n], treated as n [d1 x ... x dm] elements
%
% OUTPUTS
% U - [d x r], d=prod(di), each column is a principal component
% mu - [d1 x ... x dm] mean of X
% vars - sorted eigenvalues corresponding to eigenvectors in U
%
% EXAMPLE
% load pcaData;
% [U,mu,vars] = pca( I3D1(:,:,1:12) );
% [Y,Xhat,avsq] = pcaApply( I3D1(:,:,1), U, mu, 5 );
% pcaVisualize( U, mu, vars, I3D1, 13, [0:12], [], 1 );
% Xr = pcaRandVec( U, mu, vars, 1, 25, 0, 3 );
%
% See also princomp, pcaApply, pcaVisualize, pcaRandVec, visualizeData
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% set X to be zero mean, then flatten
d=size(X); n=d(end); d=prod(d(1:end-1));
if(~isa(X,'double')), X=double(X); end
if(n==1); mu=X; U=zeros(d,1); vars=0; return; end
mu = mean( X, ndims(X) );
X = bsxfun(@minus,X,mu)/sqrt(n-1);
X = reshape( X, d, n );
% make sure X not too large or SVD slow O(min(d,n)^2.5)
m=2500; if( min(d,n)>m ), X=X(:,randperm(n,m)); n=m; end
% get principal components using the SVD of X: X=U*S*V'
if( 0 )
[U,S]=svd(X,'econ'); vars=diag(S).^2;
elseif( d>n )
[~,SS,V]=robustSvd(X'*X); vars=diag(SS);
U = X * V * diag(1./sqrt(vars));
else
[~,SS,U]=robustSvd(X*X'); vars=diag(SS);
end
% discard low variance prinicipal components
K=vars>1e-30; vars=vars(K); U=U(:,K);
end
function [U,S,V] = robustSvd( X, trials )
% Robust version of SVD more likely to always converge.
% [Converge issues only seem to appear on Matlab 2013a in Windows.]
if(nargin<2), trials=100; end
try [U,S,V] = svd(X); catch
if(trials<=0), error('svd did not converge'); end
n=numel(X); j=randi(n); X(j)=X(j)+eps;
[U,S,V]=robustSvd(X,trials-1);
end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
kmeans2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/classify/kmeans2.m
| 5,251 |
utf_8
|
f941053f03c3e9eda40389a4cc64ee00
|
function [ IDX, C, d ] = kmeans2( X, k, varargin )
% Fast version of kmeans clustering.
%
% Cluster the N x p matrix X into k clusters using the kmeans algorithm. It
% returns the cluster memberships for each data point in the N x 1 vector
% IDX and the K x p matrix of cluster means in C.
%
% This function is in some ways less general than Matlab's kmeans.m (for
% example it only uses euclidian distance), but it has some options that
% the Matlab version does not (for example, it has a notion of outliers and
% min-cluster size). It is also many times faster than matlab's kmeans.
% General kmeans help can be found in help for the matlab implementation of
% kmeans. Note that the although the names and conventions for this
% algorithm are taken from Matlab's implementation, there are slight
% alterations (for example, IDX==-1 is used to indicate outliers).
%
% IDX is a n-by-1 vector used to indicated cluster membership. Let X be a
% set of n points. Then the ID of X - or IDX is a column vector of length
% n, where each element is an integer indicating the cluster membership of
% the corresponding element in X. IDX(i)=c indicates that the ith point in
% X belongs to cluster c. Cluster labels range from 1 to k, and thus
% k=max(IDX) is typically the number of clusters IDX divides X into. The
% cluster label "-1" is reserved for outliers. IDX(i)==-1 indicates that
% the given point does not belong to any of the discovered clusters. Note
% that matlab's version of kmeans does not have outliers.
%
% USAGE
% [ IDX, C, d ] = kmeans2( X, k, [varargin] )
%
% INPUTS
% X - [n x p] matrix of n p-dim vectors.
% k - maximum nuber of clusters (actual number may be smaller)
% prm - additional params (struct or name/value pairs)
% .k - [] alternate way of specifying k (if not given above)
% .nTrial - [1] number random restarts
% .maxIter - [100] max number of iterations
% .display - [0] Whether or not to display algorithm status
% .rndSeed - [] random seed for kmeans; useful for replicability
% .outFrac - [0] max frac points that can be treated as outliers
% .minCl - [1] min cluster size (smaller clusters get eliminated)
% .metric - [] metric for pdist2
% .C0 - [] initial cluster centers for first trial
%
% OUTPUTS
% IDX - [n x 1] cluster membership (see above)
% C - [k x p] matrix of centroid locations C(j,:) = mean(X(IDX==j,:))
% d - [1 x k] d(j) is sum of distances from X(IDX==j,:) to C(j,:)
% sum(d) is a typical measure of the quality of a clustering
%
% EXAMPLE
%
% See also DEMOCLUSTER
%
% Piotr's Computer Vision Matlab Toolbox Version 3.24
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get input args
dfs = {'nTrial',1, 'maxIter',100, 'display',0, 'rndSeed',[],...
'outFrac',0, 'minCl',1, 'metric',[], 'C0',[],'k',k };
[nTrial,maxt,dsp,rndSeed,outFrac,minCl,metric,C0,k] = ...
getPrmDflt(varargin,dfs); assert(~isempty(k) && k>0);
% error checking
if(k<1); error('k must be greater than 1'); end
if(~ismatrix(X) || any(size(X)==0)); error('Illegal X'); end
if(outFrac<0 || outFrac>=1), error('outFrac must be in [0,1)'); end
nOut = floor( size(X,1)*outFrac );
% initialize random seed if specified
if(~isempty(rndSeed)); rand('state',rndSeed); end; %#ok<RAND>
% run kmeans2main nTrial times
bd=inf; t0=clock;
for i=1:nTrial, t1=clock; if(i>1), C0=[]; end
if(dsp), fprintf('kmeans2 iter %i/%i step: ',i,nTrial); end
[IDX,C,d]=kmeans2main(X,k,nOut,minCl,maxt,dsp,metric,C0);
if(sum(d)<sum(bd)), bIDX=IDX; bC=C; bd=d; end
if(dsp), fprintf(' d=%f t=%fs\n',sum(d),etime(clock,t1)); end
end
IDX=bIDX; C=bC; d=bd; k=max(IDX);
if(dsp), fprintf('k=%i d=%f t=%fs\n',k,sum(d),etime(clock,t0)); end
% sort IDX to have biggest clusters have lower indicies
cnts = zeros(1,k); for i=1:k; cnts(i) = sum( IDX==i ); end
[~,order] = sort( -cnts ); C = C(order,:); d = d(order);
IDX2=IDX; for i=1:k; IDX2(IDX==order(i))=i; end; IDX = IDX2;
end
function [IDX,C,d] = kmeans2main( X, k, nOut, minCl, maxt, dsp, metric, C )
% initialize cluster centers to be k random X points
[N,p] = size(X); k = min(k,N); t=0;
IDX = ones(N,1); oldIDX = zeros(N,1);
if(isempty(C)), C = X(randperm(N,k),:)+randn(k,p)/1e5; end
% MAIN LOOP: loop until the cluster assigments do not change
if(dsp), nDg=ceil(log10(maxt-1)); fprintf(int2str2(0,nDg)); end
while( any(oldIDX~=IDX) && t<maxt )
% assign each point to closest cluster center
oldIDX=IDX; D=pdist2(X,C,metric); [mind,IDX]=min(D,[],2);
% do not use most distant nOut elements in computation of centers
mind1=sort(mind); thr=mind1(end-nOut); IDX(mind>thr)=-1;
% Recalculate means based on new assignment, discard small clusters
k0=0; C=zeros(k,p);
for IDx=1:k
ids=find(IDX==IDx); nCl=size(ids,1);
if( nCl<minCl ), IDX(ids)=-1; continue; end
k0=k0+1; IDX(ids)=k0; C(k0,:)=sum(X(ids,:),1)/nCl;
end
if(k0>0), k=k0; C=C(1:k,:); else k=1; C=X(randint2(1,1,[1 N]),:); end
t=t+1; if(dsp), fprintf([repmat('\b',[1 nDg]) int2str2(t,nDg)]); end
end
% record within-cluster sums of point-to-centroid distances
d=zeros(1,k); for i=1:k, d(i)=sum(mind(IDX==i)); end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
acfModify.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/detector/acfModify.m
| 4,202 |
utf_8
|
7a49406d51e7a9431b8fd472be0476e8
|
function detector = acfModify( detector, varargin )
% Modify aggregate channel features object detector.
%
% Takes an object detector trained by acfTrain() and modifies it. Only
% certain modifications are allowed to the detector and the detector should
% never be modified directly (this may cause the detector to be invalid and
% cause segmentation faults). Any valid modification to a detector after it
% is trained should be performed using acfModify().
%
% The parameters 'nPerOct', 'nOctUp', 'nApprox', 'lambdas', 'pad', 'minDs'
% modify the channel feature pyramid created (see help of chnsPyramid.m for
% more details) and primarily control the scales used. The parameters
% 'pNms', 'stride', 'cascThr' and 'cascCal' modify the detector behavior
% (see help of acfTrain.m for more details). Finally, 'rescale' can be
% used to rescale the trained detector (this change is irreversible).
%
% USAGE
% detector = acfModify( detector, pModify )
%
% INPUTS
% detector - detector trained via acfTrain
% pModify - parameters (struct or name/value pairs)
% .nPerOct - [] number of scales per octave
% .nOctUp - [] number of upsampled octaves to compute
% .nApprox - [] number of approx. scales to use
% .lambdas - [] coefficients for power law scaling (see BMVC10)
% .pad - [] amount to pad channels (along T/B and L/R)
% .minDs - [] minimum image size for channel computation
% .pNms - [] params for non-maximal suppression (see bbNms.m)
% .stride - [] spatial stride between detection windows
% .cascThr - [] constant cascade threshold (affects speed/accuracy)
% .cascCal - [] cascade calibration (affects speed/accuracy)
% .rescale - [] rescale entire detector by given ratio
%
% OUTPUTS
% detector - modified object detector
%
% EXAMPLE
%
% See also chnsPyramid, bbNms, acfTrain, acfDetect
%
% Piotr's Computer Vision Matlab Toolbox Version 3.20
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get parameters (and copy to detector and pPyramid structs)
opts=detector.opts; p=opts.pPyramid;
dfs={ 'nPerOct',p.nPerOct, 'nOctUp',p.nOctUp, 'nApprox',p.nApprox, ...
'lambdas',p.lambdas, 'pad',p.pad, 'minDs',p.minDs, 'pNms',opts.pNms, ...
'stride',opts.stride,'cascThr',opts.cascThr,'cascCal',0,'rescale',1 };
[p.nPerOct,p.nOctUp,p.nApprox,p.lambdas,p.pad,p.minDs,opts.pNms,...
opts.stride,opts.cascThr,cascCal,rescale] = getPrmDflt(varargin,dfs,1);
% finalize pPyramid and opts
p.complete=0; p.pChns.complete=0; p=chnsPyramid([],p); p=p.pPyramid;
p.complete=1; p.pChns.complete=1; shrink=p.pChns.shrink;
opts.stride=max(1,round(opts.stride/shrink))*shrink;
opts.pPyramid=p; detector.opts=opts;
% calibrate and rescale detector
detector.clf.hs = detector.clf.hs+cascCal;
if(rescale~=1), detector=detectorRescale(detector,rescale); end
end
function detector = detectorRescale( detector, rescale )
% Rescale detector by ratio rescale.
opts=detector.opts; shrink=opts.pPyramid.pChns.shrink;
bh=opts.modelDsPad(1)/shrink; bw=opts.modelDsPad(2)/shrink;
opts.stride=max(1,round(opts.stride*rescale/shrink))*shrink;
modelDsPad=round(opts.modelDsPad*rescale/shrink)*shrink;
rescale=modelDsPad./opts.modelDsPad; opts.modelDsPad=modelDsPad;
opts.modelDs=round(opts.modelDs.*rescale); detector.opts=opts;
bh1=opts.modelDsPad(1)/shrink; bw1=opts.modelDsPad(2)/shrink;
% move 0-indexed (x,y) location of each lookup feature
clf=detector.clf; fids=clf.fids; is=find(clf.child>0);
fids=double(fids(is)); n=length(fids); loc=zeros(n,3);
loc(:,3)=floor(fids/bh/bw); fids=fids-loc(:,3)*bh*bw;
loc(:,2)=floor(fids/bh); fids=fids-loc(:,2)*bh; loc(:,1)=fids;
loc(:,1)=min(bh1-1,round(loc(:,1)*rescale(1)));
loc(:,2)=min(bw1-1,round(loc(:,2)*rescale(2)));
fids = loc(:,3)*bh1*bw1 + loc(:,2)*bh1 + loc(:,1);
clf.fids(is)=int32(fids);
% rescale thrs for all features (fpdw trick)
nChns=[detector.info.nChns]; assert(max(loc(:,3))<sum(nChns));
k=[]; for i=1:length(nChns), k=[k ones(1,nChns(i))*i]; end %#ok<AGROW>
lambdas=opts.pPyramid.lambdas; lambdas=sqrt(prod(rescale)).^-lambdas(k);
clf.thrs(is)=clf.thrs(is).*lambdas(loc(:,3)+1)'; detector.clf=clf;
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
acfDetect.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/detector/acfDetect.m
| 3,659 |
utf_8
|
cf1384311b16371be6fa4715140e5c81
|
function bbs = acfDetect( I, detector, fileName )
% Run aggregate channel features object detector on given image(s).
%
% The input 'I' can either be a single image (or filename) or a cell array
% of images (or filenames). In the first case, the return is a set of bbs
% where each row has the format [x y w h score] and score is the confidence
% of detection. If the input is a cell array, the output is a cell array
% where each element is a set of bbs in the form above (in this case a
% parfor loop is used to speed execution). If 'fileName' is specified, the
% bbs are saved to a comma separated text file and the output is set to
% bbs=1. If saving detections for multiple images the output is stored in
% the format [imgId x y w h score] and imgId is a one-indexed image id.
%
% A cell of detectors trained with the same channels can be specified,
% detected bbs from each detector are concatenated. If using multiple
% detectors and opts.pNms.separate=1 then each bb has a sixth element
% bbType=j, where j is the j-th detector, see bbNms.m for details.
%
% USAGE
% bbs = acfDetect( I, detector, [fileName] )
%
% INPUTS
% I - input image(s) of filename(s) of input image(s)
% detector - detector(s) trained via acfTrain
% fileName - [] target filename (if specified return is 1)
%
% OUTPUTS
% bbs - [nx5] array of bounding boxes or cell array of bbs
%
% EXAMPLE
%
% See also acfTrain, acfModify, bbGt>loadAll, bbNms
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% run detector on every image
if(nargin<3), fileName=''; end; multiple=iscell(I);
if(~isempty(fileName) && exist(fileName,'file')), bbs=1; return; end
if(~multiple), bbs=acfDetectImg(I,detector); else
n=length(I); bbs=cell(n,1);
parfor i=1:n, bbs{i}=acfDetectImg(I{i},detector); end
end
% write results to disk if fileName specified
if(isempty(fileName)), return; end
d=fileparts(fileName); if(~isempty(d)&&~exist(d,'dir')), mkdir(d); end
if( multiple ) % add image index to each bb and flatten result
for i=1:n, bbs{i}=[ones(size(bbs{i},1),1)*i bbs{i}]; end
bbs=cell2mat(bbs);
end
dlmwrite(fileName,bbs); bbs=1;
end
function bbs = acfDetectImg( I, detector )
% Run trained sliding-window object detector on given image.
Ds=detector; if(~iscell(Ds)), Ds={Ds}; end; nDs=length(Ds);
opts=Ds{1}.opts; pPyramid=opts.pPyramid; pNms=opts.pNms;
imreadf=opts.imreadf; imreadp=opts.imreadp;
shrink=pPyramid.pChns.shrink; pad=pPyramid.pad;
separate=nDs>1 && isfield(pNms,'separate') && pNms.separate;
% read image and compute features (including optionally applying filters)
if(all(ischar(I))), I=feval(imreadf,I,imreadp{:}); end
P=chnsPyramid(I,pPyramid); bbs=cell(P.nScales,nDs);
if(isfield(opts,'filters') && ~isempty(opts.filters)), shrink=shrink*2;
for i=1:P.nScales, fs=opts.filters; C=repmat(P.data{i},[1 1 size(fs,4)]);
for j=1:size(C,3), C(:,:,j)=conv2(C(:,:,j),fs(:,:,j),'same'); end
P.data{i}=imResample(C,.5);
end
end
% apply sliding window classifiers
for i=1:P.nScales
for j=1:nDs, opts=Ds{j}.opts;
modelDsPad=opts.modelDsPad; modelDs=opts.modelDs;
bb = acfDetect1(P.data{i},Ds{j}.clf,shrink,...
modelDsPad(1),modelDsPad(2),opts.stride,opts.cascThr);
shift=(modelDsPad-modelDs)/2-pad;
bb(:,1)=(bb(:,1)+shift(2))/P.scaleshw(i,2);
bb(:,2)=(bb(:,2)+shift(1))/P.scaleshw(i,1);
bb(:,3)=modelDs(2)/P.scales(i);
bb(:,4)=modelDs(1)/P.scales(i);
if(separate), bb(:,6)=j; end; bbs{i,j}=bb;
end
end; bbs=cat(1,bbs{:});
if(~isempty(pNms)), bbs=bbNms(bbs,pNms); end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
acfSweeps.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/detector/acfSweeps.m
| 10,731 |
utf_8
|
db60505e8ee70092d7967ff95c483db8
|
function acfSweeps
% Parameter sweeps for ACF pedestrian detector.
%
% Running the parameter sweeps requires altering internal flags.
% The sweeps are not well documented, use at your own discretion.
%
% Piotr's Computer Vision Matlab Toolbox Version 3.50
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% specify type and location of cluster (see fevalDistr.m)
rtDir=[fileparts(fileparts(fileparts(mfilename('fullpath')))) '/data/'];
pDistr={'type','parfor'}; if(0), matlabpool('open',11); end
% define all parameter sweeps
expNms = {'FtrsColorSpace','FtrsChnTypes','FtrsGradColorChn',...
'FtrsGradNormRad','FtrsGradNormConst','FtrsGradOrients',...
'FtrsGradSoftBins','FtrsSmoothIm','FtrsSmoothChns','FtrsShrink',...
'DetModelDs','DetModelDsPad','DetStride','DetNumOctaves',...
'DetNumApprox','DetLambda','DetCascThr','DetCascCal','DetNmsThr',...
'TrnNumWeak','TrnNumBoot','TrnDepth','TrnNumBins','TrnFracFtrs',...
'DataNumPos','DataNumNeg','DataNumNegAcc','DataNumNegPer',...
'DataNumPosStump','DataJitterTran','DataJitterRot'};
expNms=expNms(:); T = 10;
[opts,lgd,lbl]=createExp(rtDir,expNms);
% run training and testing jobs
[jobsTrn,jobsTst] = createJobs( rtDir, opts, T ); N=length(expNms);
fprintf('nTrain = %i; nTest = %i\n',length(jobsTrn),length(jobsTst));
tic, s=fevalDistr('acfTrain',jobsTrn,pDistr); assert(s==1); toc
tic, s=fevalDistr('acfTest',jobsTst,pDistr); assert(s==1); toc
% create plots for all experiments
for e=1:N, plotExps(rtDir,expNms{e},opts{e},lgd{e},lbl{e},T); end
end
function plotExps( rtDir, expNm, opts, lgd, lbl, T )
% data location and parameters for plotting
plDir=[rtDir 'sweeps/plots/']; if(~exist(plDir,'dir')), mkdir(plDir); end
diary([plDir 'sweeps.txt']); disp([expNm ' [' lbl ']']); N=length(lgd);
pLoad=struct('squarify',{{3,.41}},'hRng',[0 inf]);
pTest=struct('name','', 'imgDir',[rtDir 'Inria/test/pos'],...
'gtDir',[rtDir 'Inria/test/posGt'], 'pLoad',pLoad);
pTest=repmat(pTest,N,T); for e=1:N, for t=1:T,
pTest(e,t).name=[opts(e).name 'T' int2str2(t,2)]; end; end
% get all miss rates and display error
miss=zeros(N,T); parfor e=1:N*T, miss(e)=acfTest(pTest(e)); end
stds=std(miss,0,2); R=mean(miss,2); msg=' %.2f +/- %.2f [%s]\n';
for e=1:N, fprintf(msg,R(e)*100,stds(e)*100,lgd{e}); end
% plot sweeps
figPrp = {'Units','Pixels','Position',[800 600 800 400]};
figure(1); clf; set(1,figPrp{:}); set(gca,'FontSize',24); clr=[0 .69 .94];
pPl1={'LineWidth',3,'MarkerSize',15,'Color',clr,'MarkerFaceColor',clr};
pPl2=pPl1; clr=[1 .75 0]; pPl2{6}=clr; pPl2{8}=clr;
for e=1:N, if(lgd{e}(end)=='*'), def=e; end; end; lgd{def}(end)=[];
plot(R,'-d',pPl1{:}); hold on; plot(def,R(def),'d',pPl2{:}); e=.001;
ylabel('MR'); axis([.5 N+.5 min([R; .15]) max([R; .3])+e]);
if(isempty(lbl)), imLabel(lgd,'bottom',30,{'FontSize',24}); lgd=[]; end
xlabel(lbl); set(gca,'XTick',1:N,'XTickLabel',lgd);
% save plot
fFig=[plDir expNm]; diary('off');
for t=1:25, try savefig(fFig,1,'png'); break; catch, pause(1), end; end
end
function [jobsTrn,jobsTst] = createJobs( rtDir, opts, T )
% Prepare all jobs (one train and one test job per set of opts).
opts=[opts{:}]; N=length(opts); NT=N*T;
opts=repmat(opts,1,T); nms=cell(1,NT);
jobsTrn=cell(1,NT); doneTrn=zeros(1,NT);
jobsTst=cell(1,NT); doneTst=zeros(1,NT);
pLoad=struct('squarify',{{3,.41}},'hRng',[0 inf]);
pTest=struct('name','', 'imgDir',[rtDir 'Inria/test/pos'],...
'gtDir',[rtDir 'Inria/test/posGt'], 'pLoad',pLoad);
for e=1:NT
t=ceil(e/N); opts(e).seed=(t-1)*100000+1;
nm=[opts(e).name 'T' int2str2(t,2)];
opts(e).name=nm; pTest.name=nm; nms{e}=nm;
doneTrn(e)=exist([nm 'Detector.mat'],'file')==2; jobsTrn{e}={opts(e)};
doneTst(e)=exist([nm 'Dets.txt'],'file')==2; jobsTst{e}={pTest};
end
[~,kp]=unique(nms,'stable');
doneTrn=doneTrn(kp); jobsTrn=jobsTrn(kp); jobsTrn=jobsTrn(~doneTrn);
doneTst=doneTst(kp); jobsTst=jobsTst(kp); jobsTst=jobsTst(~doneTst);
end
function [opts,lgd,lbl] = createExp( rtDir, expNm )
% if expNm is a cell, call recursively and return
if( iscell(expNm) )
N=length(expNm); opts=cell(1,N); lgd=cell(1,N); lbl=lgd;
for e=1:N, [opts{e},lgd{e},lbl{e}]=createExp(rtDir,expNm{e}); end; return
end
% default params for detectorTrain.m
dataDir=[rtDir 'Inria/'];
opts=acfTrain(); opts.modelDs=[100 41]; opts.modelDsPad=[128 64];
opts.posGtDir=[dataDir 'train/posGt']; opts.nWeak=[32 128 512 2048];
opts.posImgDir=[dataDir 'train/pos']; opts.pJitter=struct('flip',1);
opts.negImgDir=[dataDir 'train/neg']; opts.pBoost.pTree.fracFtrs=1/16;
if(~exist([rtDir 'sweeps/res/'],'dir')), mkdir([rtDir 'sweeps/res/']); end
opts.pBoost.pTree.nThreads=1;
% setup experiments (N sets of params)
optsDefault=opts; N=100; lgd=cell(1,N); ss=lgd; lbl=''; O=ones(1,N);
pChns=opts.pPyramid.pChns(O); pPyramid=opts.pPyramid(O); opts=opts(O);
switch expNm
case 'FtrsColorSpace'
N=8; clrs={'Gray','rgb','hsv','luv'};
for e=1:N, pChns(e).pColor.colorSpace=clrs{mod(e-1,4)+1}; end
for e=5:N, pChns(e).pGradMag.enabled=0; end
for e=5:N, pChns(e).pGradHist.enabled=0; end
ss=[clrs clrs]; for e=1:4, ss{e}=[ss{e} '+G+H']; end
ss=upper(ss); lgd=ss;
case 'FtrsChnTypes'
nms={'LUV+','G+','H+'}; N=7;
for e=1:N
en=false(1,3); for i=1:3, en(i)=bitget(uint8(e),i); end
pChns(e).pColor.enabled=en(1); pChns(e).pGradMag.enabled=en(2);
pChns(e).pGradHist.enabled=en(3);
nm=[nms{en}]; nm=nm(1:end-1); lgd{e}=nm; ss{e}=nm;
end
case 'FtrsGradColorChn'
lbl='gradient color channel';
N=4; ss={'Max','L','U','V'}; lgd=ss;
for e=1:N, pChns(e).pGradMag.colorChn=e-1; end
case 'FtrsGradNormRad'
lbl='norm radius';
vs=[0 1 2 5 10]; N=length(vs);
for e=1:N, pChns(e).pGradMag.normRad=vs(e); end
case 'FtrsGradNormConst'
lbl='norm constant x 10^3';
vs=[1 2 5 10 20 50 100]; N=length(vs);
for e=1:N, pChns(e).pGradMag.normConst=vs(e)/1000; end
case 'FtrsGradOrients'
lbl='# orientations';
vs=[2 4 6 8 10 12]; N=length(vs);
for e=1:N, pChns(e).pGradHist.nOrients=vs(e); end
case 'FtrsGradSoftBins'
lbl='use soft bins';
vs=[0 1]; N=length(vs);
for e=1:N, pChns(e).pGradHist.softBin=vs(e); end
case 'FtrsSmoothIm'
lbl='image smooth radius';
vs=[0 50 100 200]; N=length(vs);
for e=1:N, pChns(e).pColor.smooth=vs(e)/100; end
for e=1:N, lgd{e}=num2str(vs(e)/100); end
case 'FtrsSmoothChns'
lbl='channel smooth radius';
vs=[0 50 100 200]; N=length(vs);
for e=1:N, pPyramid(e).smooth=vs(e)/100; end
for e=1:N, lgd{e}=num2str(vs(e)/100); end
case 'FtrsShrink'
lbl='channel shrink';
vs=2.^(1:4); N=length(vs);
for e=1:N, pChns(e).shrink=vs(e); end
case 'DetModelDs'
lbl='model height';
rs=1.1.^(-2:2); vs=round(100*rs); ws=round(41*rs); N=length(vs);
for e=1:N, opts(e).modelDs=[vs(e) ws(e)]; end
for e=1:N, opts(e).modelDsPad=opts(e).modelDs+[28 23]; end
case 'DetModelDsPad'
lbl='padded model height';
rs=1.1.^(-2:2); vs=round(128*rs); ws=round(64*rs); N=length(vs);
for e=1:N, opts(e).modelDsPad=[vs(e) ws(e)]; end
case 'DetStride'
lbl='detector stride';
vs=4:4:16; N=length(vs);
for e=1:N, opts(e).stride=vs(e); end
case 'DetNumOctaves'
lbl='# scales per octave';
vs=2.^(0:5); N=length(vs);
for e=1:N, pPyramid(e).nPerOct=vs(e); pPyramid(e).nApprox=vs(e)-1; end
case 'DetNumApprox'
lbl='# approx scales';
vs=2.^(0:5)-1; N=length(vs);
for e=1:N, pPyramid(e).nApprox=vs(e); end
case 'DetLambda'
lbl='lambda x 100';
vs=-45:15:70; N=length(vs);
for e=[1:4 6:N], pPyramid(e).lambdas=[0 vs(e) vs(e)]/100; end
for e=1:N, lgd{e}=int2str(vs(e)); end; vs=vs+100;
case 'DetCascThr'
lbl='cascade threshold';
vs=[-.5 -1 -2 -5 -10]; N=length(vs);
for e=1:N, opts(e).cascThr=vs(e); end
for e=1:N, lgd{e}=num2str(vs(e)); end; vs=vs*-10;
case 'DetCascCal'
lbl='cascade offset x 10^4';
vs=[5 10 20 50 100 200 500]; N=length(vs);
for e=1:N, opts(e).cascCal=vs(e)/1e4; end
case 'DetNmsThr'
lbl='nms overlap';
vs=25:10:95; N=length(vs);
for e=1:N, opts(e).pNms.overlap=vs(e)/1e2; end
for e=1:N, lgd{e}=['.' num2str(vs(e))]; end
case 'TrnNumWeak'
lbl='# decision trees / x';
vs=2.^(0:3); N=length(vs);
for e=1:N, opts(e).nWeak=opts(e).nWeak/vs(e); end
case 'TrnNumBoot'
lbl='bootstrap schedule';
vs={5:1:11,5:2:11,3:1:11,3:2:11}; N=length(vs);
ss={'5-1-11','5-2-11','3-1-11','3-2-11'}; lgd=ss;
for e=1:N, opts(e).nWeak=2.^vs{e}; end
case 'TrnDepth'
lbl='tree depth';
vs=1:5; N=length(vs);
for e=1:N, opts(e).pBoost.pTree.maxDepth=vs(e); end
case 'TrnNumBins'
lbl='# bins';
vs=2.^(4:8); N=length(vs);
for e=1:N, opts(e).pBoost.pTree.nBins=vs(e); end
case 'TrnFracFtrs'
lbl='fraction features';
vs=2.^(1:8); N=length(vs);
for e=1:N, opts(e).pBoost.pTree.fracFtrs=1/vs(e); end
case 'DataNumPos'
lbl='# pos examples';
vs=[2.^(6:9) inf]; N=length(vs);
for e=1:N-1, opts(e).nPos=vs(e); end
case 'DataNumNeg'
lbl='# neg examples';
vs=[5 10 25 50 100 250]*100; N=length(vs);
for e=1:N, opts(e).nNeg=vs(e); end
case 'DataNumNegAcc'
lbl='# neg examples total';
vs=[25 50 100 250 500]*100; N=length(vs);
for e=1:N, opts(e).nAccNeg=vs(e); end
case 'DataNumNegPer'
lbl='# neg example / image';
vs=[5 10 25 50 100]; N=length(vs);
for e=1:N, opts(e).nPerNeg=vs(e); end
case 'DataNumPosStump'
lbl='# pos examples (stumps)';
vs=[2.^(6:9) 1237 1237]; N=length(vs); lgd{N}='1237*';
for e=1:N-1, opts(e).nPos=vs(e); opts(e).pBoost.pTree.maxDepth=1; end
case 'DataJitterTran'
lbl='translational jitter';
vs=[0 1 2 4]; N=length(vs); opts(1).pJitter=struct('flip',1);
for e=2:N, opts(e).pJitter=struct('flip',1,'nTrn',3,'mTrn',vs(e)); end
for e=1:N, lgd{e}=['+/-' int2str(vs(e))]; end
case 'DataJitterRot'
lbl='rotational jitter';
vs=[0 2 4 8]; N=length(vs);
for e=2:N, opts(e).pJitter=struct('flip',1,'nPhi',3,'mPhi',vs(e)); end
for e=1:N, lgd{e}=['+/-' int2str(vs(e))]; end
otherwise, error('invalid exp: %s',expNm);
end
% produce final set of opts and find default opts
for e=1:N, if(isempty(lgd{e})), lgd{e}=int2str(vs(e)); end; end
for e=1:N, if(isempty(ss{e})), ss{e}=int2str2(vs(e),5); end; end
O=1:N; opts=opts(O); lgd=lgd(O); ss=ss(O); d=0;
for e=1:N, pPyramid(e).pChns=pChns(e); opts(e).pPyramid=pPyramid(e); end
for e=1:N, if(isequal(optsDefault,opts(e))), d=e; break; end; end
if(d==0), disp(expNm); assert(false); end
for e=1:N, opts(e).name=[rtDir 'sweeps/res/' expNm ss{e}]; end
lgd{d}=[lgd{d} '*']; opts(d).name=[rtDir 'sweeps/res/Default'];
if(0), disp([ss' lgd']'); end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
bbGt.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/detector/bbGt.m
| 34,046 |
utf_8
|
69e66c9a0cc143fb9a794fbc9233246e
|
function varargout = bbGt( action, varargin )
% Bounding box (bb) annotations struct, evaluation and sampling routines.
%
% bbGt gives access to two types of routines:
% (1) Data structure for storing bb image annotations.
% (2) Routines for evaluating the Pascal criteria for object detection.
%
% The bb annotation stores bb for objects of interest with additional
% information per object, such as occlusion information. The underlying
% data structure is simply a Matlab stuct array, one struct per object.
% This annotation format is an alternative to the annotation format used
% for the PASCAL object challenges (in addition routines for loading PASCAL
% format data are provided, see bbLoad()).
%
% Each object struct has the following fields:
% lbl - a string label describing object type (eg: 'pedestrian')
% bb - [l t w h]: bb indicating predicted object extent
% occ - 0/1 value indicating if bb is occluded
% bbv - [l t w h]: bb indicating visible region (may be [0 0 0 0])
% ign - 0/1 value indicating bb was marked as ignore
% ang - [0-360] orientation of bb in degrees
%
% Note: although orientation (angle) is stored for each bb, for now it is
% not being used during evaluation or sampling.
%
% bbGt contains a number of utility functions, accessed using:
% outputs = bbGt( 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help bbGt>action".
%
%%% (1) Data structure for storing bb image annotations.
% Create annotation of n empty objects.
% objs = bbGt( 'create', [n] );
% Save bb annotation to text file.
% objs = bbGt( 'bbSave', objs, fName )
% Load bb annotation from text file and filter.
% [objs,bbs] = bbGt( 'bbLoad', fName, [pLoad] )
% Get object property 'name' (in a standard array).
% vals = bbGt( 'get', objs, name )
% Set object property 'name' (with a standard array).
% objs = bbGt( 'set', objs, name, vals )
% Draw an ellipse for each labeled object.
% hs = draw( objs, pDraw )
%
%%% (2) Routines for evaluating the Pascal criteria for object detection.
% Get all corresponding files in given directories.
% [fs,fs0] = bbGt('getFiles', dirs, [f0], [f1] )
% Copy corresponding files into given directories.
% fs = bbGt( 'copyFiles', fs, dirs )
% Load all ground truth and detection bbs in given directories.
% [gt0,dt0] = bbGt( 'loadAll', gtDir, [dtDir], [pLoad] )
% Evaluates detections against ground truth data.
% [gt,dt] = bbGt( 'evalRes', gt0, dt0, [thr], [mul] )
% Display evaluation results for given image.
% [hs,hImg] = bbGt( 'showRes' I, gt, dt, varargin )
% Compute ROC or PR based on outputs of evalRes on multiple images.
% [xs,ys,ref] = bbGt( 'compRoc', gt, dt, roc, ref )
% Extract true or false positives or negatives for visualization.
% [Is,scores,imgIds] = bbGt( 'cropRes', gt, dt, imFs, varargin )
% Computes (modified) overlap area between pairs of bbs.
% oa = bbGt( 'compOas', dt, gt, [ig] )
% Optimized version of compOas for a single pair of bbs.
% oa = bbGt( 'compOa', dt, gt, ig )
%
% USAGE
% varargout = bbGt( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also bbApply, bbLabeler, bbGt>create, bbGt>bbSave, bbGt>bbLoad,
% bbGt>get, bbGt>set, bbGt>draw, bbGt>getFiles, bbGt>copyFiles,
% bbGt>loadAll, bbGt>evalRes, bbGt>showRes, bbGt>compRoc, bbGt>cropRes,
% bbGt>compOas, bbGt>compOa
%
% Piotr's Computer Vision Matlab Toolbox Version 3.26
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function objs = create( n )
% Create annotation of n empty objects.
%
% USAGE
% objs = bbGt( 'create', [n] )
%
% INPUTS
% n - [1] number of objects to create
%
% OUTPUTS
% objs - annotation of n 'empty' objects
%
% EXAMPLE
% objs = bbGt('create')
%
% See also bbGt
o=struct('lbl','','bb',[0 0 0 0],'occ',0,'bbv',[0 0 0 0],'ign',0,'ang',0);
if(nargin<1 || n==1), objs=o; return; end; objs=o(ones(n,1));
end
function objs = bbSave( objs, fName )
% Save bb annotation to text file.
%
% USAGE
% objs = bbGt( 'bbSave', objs, fName )
%
% INPUTS
% objs - objects to save
% fName - name of text file
%
% OUTPUTS
% objs - objects to save
%
% EXAMPLE
%
% See also bbGt, bbGt>bbLoad
vers=3; fid=fopen(fName,'w'); assert(fid>0);
fprintf(fid,'%% bbGt version=%i\n',vers);
objs=set(objs,'bb',round(get(objs,'bb')));
objs=set(objs,'bbv',round(get(objs,'bbv')));
objs=set(objs,'ang',round(get(objs,'ang')));
for i=1:length(objs)
o=objs(i); bb=o.bb; bbv=o.bbv;
fprintf(fid,['%s' repmat(' %i',1,11) '\n'],o.lbl,...
bb,o.occ,bbv,o.ign,o.ang);
end
fclose(fid);
end
function [objs,bbs] = bbLoad( fName, varargin )
% Load bb annotation from text file and filter.
%
% FORMAT: Specify 'format' to indicate the format of the ground truth.
% format=0 is the default format (created by bbSave/bbLabeler). format=1 is
% the PASCAL VOC format. Loading ground truth in this format requires
% 'VOCcode/' to be in directory path. It's part of VOCdevkit available from
% the PASCAL VOC: http://pascallin.ecs.soton.ac.uk/challenges/VOC/. Objects
% labeled as either 'truncated' or 'occluded' using the PASCAL definitions
% have the 'occ' flag set to true. Objects labeled as 'difficult' have the
% 'ign' flag set to true. 'class' is used for 'lbl'. format=2 is the
% ImageNet detection format and requires the ImageNet Dev Kit.
%
% FILTERING: After loading, the objects can be filtered. First, only
% objects with lbl in lbls or ilbls or returned. For each object, obj.ign
% is set to 1 if it was already at 1, if its label was in ilbls, or if any
% object property is outside of the specified range. The ignore flag is
% used during training and testing so that objects with certain properties
% (such as very small or heavily occluded objects) are excluded. The range
% for each property is a two element vector, [0 inf] by default; a property
% value v is inside the range if v>=rng(1) && v<=rng(2). Tested properties
% include height (h), width (w), area (a), aspect ratio (ar), orientation
% (o), extent x-coordinate (x), extent y-coordinate (y), and fraction
% visible (v). The last property is computed as the visible object area
% divided by the total area, except if o.occ==0, in which case v=1, or
% all(o.bbv==o.bb), which indicates the object may be barely visible, in
% which case v=0 (note that v~=1 in this case).
%
% RETURN: In addition to outputting the objs, bbLoad() can return the
% corresponding bounding boxes (bbs) in an [nx5] array where each row is of
% the form [x y w h ignore], [x y w h] is the bb and ignore=obj.ign. For
% oriented bbs, the extent of the bb is returned, where the extent is the
% smallest axis aligned bb containing the oriented bb. If the oriented bb
% was labeled as a rectangle as opposed to an ellipse, the tightest bb will
% usually increase slightly in size due to the corners of the rectangle
% sticking out beyond the ellipse bounds. The 'ellipse' flag controls how
% an oriented bb is converted to a regular bb. Specifically, set ellipse=1
% if an ellipse tightly delineates the object and 0 if a rectangle does.
% Finally, if 'squarify' is not empty the (non-ignore) bbs are converted to
% a fixed aspect ratio using bbs=bbApply('squarify',bbs,squarify{:}).
%
% USAGE
% [objs,bbs] = bbGt( 'bbLoad', fName, [pLoad] )
%
% INPUTS
% fName - name of text file
% pLoad - parameters (struct or name/value pairs)
% .format - [0] gt format 0:default, 1:PASCAL, 2:ImageNet
% .ellipse - [1] controls how oriented bb is converted to regular bb
% .squarify - [] controls optional reshaping of bbs to fixed aspect ratio
% .lbls - [] return objs with these labels (or [] to return all)
% .ilbls - [] return objs with these labels but set to ignore
% .hRng - [] range of acceptable obj heights
% .wRng - [] range of acceptable obj widths
% .aRng - [] range of acceptable obj areas
% .arRng - [] range of acceptable obj aspect ratios
% .oRng - [] range of acceptable obj orientations (angles)
% .xRng - [] range of x coordinates of bb extent
% .yRng - [] range of y coordinates of bb extent
% .vRng - [] range of acceptable obj occlusion levels
%
% OUTPUTS
% objs - loaded objects
% bbs - [nx5] array containg ground truth bbs [x y w h ignore]
%
% EXAMPLE
%
% See also bbGt, bbGt>bbSave
% get parameters
df={'format',0,'ellipse',1,'squarify',[],'lbls',[],'ilbls',[],'hRng',[],...
'wRng',[],'aRng',[],'arRng',[],'oRng',[],'xRng',[],'yRng',[],'vRng',[]};
[format,ellipse,sqr,lbls,ilbls,hRng,wRng,aRng,arRng,oRng,xRng,yRng,vRng]...
= getPrmDflt(varargin,df,1);
% load objs
if( format==0 )
% load objs stored in default format
fId=fopen(fName);
if(fId==-1), error(['unable to open file: ' fName]); end; v=0;
try v=textscan(fId,'%% bbGt version=%d'); v=v{1}; catch, end %#ok<CTCH>
if(isempty(v)), v=0; end
% read in annotation (m is number of fields for given version v)
if(all(v~=[0 1 2 3])), error('Unknown version %i.',v); end
frmt='%s %d %d %d %d %d %d %d %d %d %d %d';
ms=[10 10 11 12]; m=ms(v+1); frmt=frmt(1:2+(m-1)*3);
in=textscan(fId,frmt); for i=2:m, in{i}=double(in{i}); end; fclose(fId);
% create objs struct from read in fields
n=length(in{1}); objs=create(n);
for i=1:n, objs(i).lbl=in{1}{i}; objs(i).occ=in{6}(i); end
bb=[in{2} in{3} in{4} in{5}]; bbv=[in{7} in{8} in{9} in{10}];
for i=1:n, objs(i).bb=bb(i,:); objs(i).bbv=bbv(i,:); end
if(m>=11), for i=1:n, objs(i).ign=in{11}(i); end; end
if(m>=12), for i=1:n, objs(i).ang=in{12}(i); end; end
elseif( format==1 )
% load objs stored in PASCAL VOC format
if(exist('PASreadrecord.m','file')~=2)
error('bbLoad() requires the PASCAL VOC code.'); end
os=PASreadrecord(fName); os=os.objects;
n=length(os); objs=create(n);
if(~isfield(os,'occluded')), for i=1:n, os(i).occluded=0; end; end
for i=1:n
bb=os(i).bbox; bb(3)=bb(3)-bb(1); bb(4)=bb(4)-bb(2); objs(i).bb=bb;
objs(i).lbl=os(i).class; objs(i).ign=os(i).difficult;
objs(i).occ=os(i).occluded || os(i).truncated;
if(objs(i).occ), objs(i).bbv=bb; end
end
elseif( format==2 )
if(exist('VOCreadxml.m','file')~=2)
error('bbLoad() requires the ImageNet dev code.'); end
os=VOCreadxml(fName); os=os.annotation;
if(isfield(os,'object')), os=os.object; else os=[]; end
n=length(os); objs=create(n);
for i=1:n
bb=os(i).bndbox; bb=str2double({bb.xmin bb.ymin bb.xmax bb.ymax});
bb(3)=bb(3)-bb(1); bb(4)=bb(4)-bb(2); objs(i).bb=bb;
objs(i).lbl=os(i).name;
end
else error('bbLoad() unknown format: %i',format);
end
% only keep objects whose lbl is in lbls or ilbls
if(~isempty(lbls) || ~isempty(ilbls)), K=true(n,1);
for i=1:n, K(i)=any(strcmp(objs(i).lbl,[lbls ilbls])); end
objs=objs(K); n=length(objs);
end
% filter objs (set ignore flags)
for i=1:n, objs(i).ang=mod(objs(i).ang,360); end
if(~isempty(ilbls)), for i=1:n, v=objs(i).lbl;
objs(i).ign = objs(i).ign || any(strcmp(v,ilbls)); end; end
if(~isempty(xRng)), for i=1:n, v=objs(i).bb(1);
objs(i).ign = objs(i).ign || v<xRng(1) || v>xRng(2); end; end
if(~isempty(xRng)), for i=1:n, v=objs(i).bb(1)+objs(i).bb(3);
objs(i).ign = objs(i).ign || v<xRng(1) || v>xRng(2); end; end
if(~isempty(yRng)), for i=1:n, v=objs(i).bb(2);
objs(i).ign = objs(i).ign || v<yRng(1) || v>yRng(2); end; end
if(~isempty(yRng)), for i=1:n, v=objs(i).bb(2)+objs(i).bb(4);
objs(i).ign = objs(i).ign || v<yRng(1) || v>yRng(2); end; end
if(~isempty(wRng)), for i=1:n, v=objs(i).bb(3);
objs(i).ign = objs(i).ign || v<wRng(1) || v>wRng(2); end; end
if(~isempty(hRng)), for i=1:n, v=objs(i).bb(4);
objs(i).ign = objs(i).ign || v<hRng(1) || v>hRng(2); end; end
if(~isempty(oRng)), for i=1:n, v=objs(i).ang; if(v>180), v=v-360; end
objs(i).ign = objs(i).ign || v<oRng(1) || v>oRng(2); end; end
if(~isempty(aRng)), for i=1:n, v=objs(i).bb(3)*objs(i).bb(4);
objs(i).ign = objs(i).ign || v<aRng(1) || v>aRng(2); end; end
if(~isempty(arRng)), for i=1:n, v=objs(i).bb(3)/objs(i).bb(4);
objs(i).ign = objs(i).ign || v<arRng(1) || v>arRng(2); end; end
if(~isempty(vRng)), for i=1:n, o=objs(i); bb=o.bb; bbv=o.bbv; %#ok<ALIGN>
if(~o.occ || all(bbv==0)), v=1; elseif(all(bbv==bb)), v=0; else
v=(bbv(3)*bbv(4))/(bb(3)*bb(4)); end
objs(i).ign = objs(i).ign || v<vRng(1) || v>vRng(2); end
end
% finally get extent of each bounding box (not trivial if ang~=0)
if(nargout<=1), return; end; if(n==0), bbs=zeros(0,5); return; end
bbs=double([reshape([objs.bb],4,[]); [objs.ign]]'); ign=bbs(:,5)==1;
for i=1:n, bbs(i,1:4)=bbExtent(bbs(i,1:4),objs(i).ang,ellipse); end
if(~isempty(sqr)), bbs(~ign,:)=bbApply('squarify',bbs(~ign,:),sqr{:}); end
function bb = bbExtent( bb, ang, ellipse )
% get bb that fully contains given oriented bb
if(~ang), return; end
if( ellipse ) % get bb that encompases ellipse (tighter)
x=bbApply('getCenter',bb); a=bb(4)/2; b=bb(3)/2; ang=ang-90;
rx=(a*cosd(ang))^2+(b*sind(ang))^2; rx=abs(rx/sqrt(rx));
ry=(a*sind(ang))^2+(b*cosd(ang))^2; ry=abs(ry/sqrt(ry));
bb=[x(1)-rx x(2)-ry 2*rx 2*ry];
else % get bb that encompases rectangle (looser)
c=cosd(ang); s=sind(ang); R=[c -s; s c]; rs=bb(3:4)/2;
x0=-rs(1); x1=rs(1); y0=-rs(2); y1=rs(2); pc=bb(1:2)+rs;
p=[x0 y0; x1 y0; x1 y1; x0 y1]*R'+pc(ones(4,1),:);
x0=min(p(:,1)); x1=max(p(:,1)); y0=min(p(:,2)); y1=max(p(:,2));
bb=[x0 y0 x1-x0 y1-y0];
end
end
end
function vals = get( objs, name )
% Get object property 'name' (in a standard array).
%
% USAGE
% vals = bbGt( 'get', objs, name )
%
% INPUTS
% objs - [nx1] struct array of objects
% name - property name ('lbl','bb','occ',etc.)
%
% OUTPUTS
% vals - [nxk] array of n values (k=1 or 4)
%
% EXAMPLE
%
% See also bbGt, bbGt>set
nObj=length(objs); if(nObj==0), vals=[]; return; end
switch name
case 'lbl', vals={objs.lbl}';
case 'bb', vals=reshape([objs.bb]',4,[])';
case 'occ', vals=[objs.occ]';
case 'bbv', vals=reshape([objs.bbv]',4,[])';
case 'ign', vals=[objs.ign]';
case 'ang', vals=[objs.ang]';
otherwise, error('unkown type %s',name);
end
end
function objs = set( objs, name, vals )
% Set object property 'name' (with a standard array).
%
% USAGE
% objs = bbGt( 'set', objs, name, vals )
%
% INPUTS
% objs - [nx1] struct array of objects
% name - property name ('lbl','bb','occ',etc.)
% vals - [nxk] array of n values (k=1 or 4)
%
% OUTPUTS
% objs - [nx1] struct array of updated objects
%
% EXAMPLE
%
% See also bbGt, bbGt>get
nObj=length(objs);
switch name
case 'lbl', for i=1:nObj, objs(i).lbl=vals{i}; end
case 'bb', for i=1:nObj, objs(i).bb=vals(i,:); end
case 'occ', for i=1:nObj, objs(i).occ=vals(i); end
case 'bbv', for i=1:nObj, objs(i).bbv=vals(i,:); end
case 'ign', for i=1:nObj, objs(i).ign=vals(i); end
case 'ang', for i=1:nObj, objs(i).ang=vals(i); end
otherwise, error('unkown type %s',name);
end
end
function hs = draw( objs, varargin )
% Draw an ellipse for each labeled object.
%
% USAGE
% hs = bbGt( 'draw', objs, pDraw )
%
% INPUTS
% objs - [nx1] struct array of objects
% pDraw - parameters (struct or name/value pairs)
% .col - ['g'] color or [nx1] array of colors
% .lw - [2] line width
% .ls - ['-'] line style
%
% OUTPUTS
% hs - [nx1] handles to drawn graphic objects
%
% EXAMPLE
%
% See also bbGt
dfs={'col',[],'lw',2,'ls','-'};
[col,lw,ls]=getPrmDflt(varargin,dfs,1);
n=length(objs); hold on; hs=zeros(n,4);
if(isempty(col)), if(n==1), col='g'; else col=hsv(n); end; end
tProp={'FontSize',10,'color','w','FontWeight','bold',...
'VerticalAlignment','bottom'};
for i=1:n
bb=objs(i).bb; ci=col(i,:);
hs(i,1)=text(bb(1),bb(2),objs(i).lbl,tProp{:});
x=bbApply('getCenter',bb); r=bb(3:4)/2; a=objs(i).ang/180*pi-pi/2;
[hs(i,2),hs(i,3),hs(i,4)]=plotEllipse(x(2),x(1),r(2),r(1),a,ci,[],lw,ls);
end; hold off;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [fs,fs0] = getFiles( dirs, f0, f1 )
% Get all corresponding files in given directories.
%
% The first dir in 'dirs' serves as the baseline dir. getFiles() returns
% all files in the baseline dir and all corresponding files in the
% remaining dirs to the files in the baseline dir, in the same order. Two
% files are in correspondence if they have the same base name (regardless
% of extension). For example, given a file named "name.jpg", a
% corresponding file may be named "name.txt" or "name.jpg.txt". Every file
% in the baseline dir must have a matching file in the remaining dirs.
%
% USAGE
% [fs,fs0] = bbGt('getFiles', dirs, [f0], [f1] )
%
% INPUTS
% dirs - {1xm} list of m directories
% f0 - [1] index of first file in baseline dir to use
% f1 - [inf] index of last file in baseline dir to use
%
% OUTPUTS
% fs - {mxn} list of full file names in each dir
% fs0 - {1xn} list of file names without path or extensions
%
% EXAMPLE
%
% See also bbGt
if(nargin<2 || isempty(f0)), f0=1; end
if(nargin<3 || isempty(f1)), f1=inf; end
m=length(dirs); assert(m>0); sep=filesep;
for d=1:m, dir1=dirs{d}; dir1(dir1=='\')=sep; dir1(dir1=='/')=sep;
if(dir1(end)==sep), dir1(end)=[]; end; dirs{d}=dir1; end
[fs0,fs1] = getFiles0(dirs{1},f0,f1,sep);
n1=length(fs0); fs=cell(m,n1); fs(1,:)=fs1;
for d=2:m, fs(d,:)=getFiles1(dirs{d},fs0,sep); end
function [fs0,fs1] = getFiles0( dir1, f0, f1, sep )
% get fs1 in dir1 (and fs0 without path or extension)
fs1=dir([dir1 sep '*']); fs1={fs1.name}; fs1=fs1(3:end);
fs1=fs1(f0:min(f1,end)); fs0=fs1; n=length(fs0);
if(n==0), error('No files found in baseline dir %s.',dir1); end
for i=1:n, fs1{i}=[dir1 sep fs0{i}]; end
n=length(fs0); for i=1:n, f=fs0{i};
f(find(f=='.',1,'first'):end)=[]; fs0{i}=f; end
end
function fs1 = getFiles1( dir1, fs0, sep )
% get fs1 in dir1 corresponding to fs0
n=length(fs0); fs1=cell(1,n); i2=0; i1=0;
fs2=dir(dir1); fs2={fs2.name}; n2=length(fs2);
eMsg='''%s'' has no corresponding file in %s.';
for i0=1:n, r=length(fs0{i0}); match=0;
while(i2<n2), i2=i2+1; if(strcmpi(fs0{i0},fs2{i2}(1:min(end,r))))
i1=i1+1; fs1{i1}=fs2{i2}; match=1; break; end; end
if(~match), error(eMsg,fs0{i0},dir1); end
end
for i1=1:n, fs1{i1}=[dir1 sep fs1{i1}]; end
end
end
function fs = copyFiles( fs, dirs )
% Copy corresponding files into given directories.
%
% Useful for splitting data into training, validation and testing sets.
% See also bbGt>getFiles for obtaining a set of corresponding files.
%
% USAGE
% fs = bbGt( 'copyFiles', fs, dirs )
%
% INPUTS
% fs - {mxn} list of full file names in each dir
% dirs - {1xm} list of m target directories
%
% OUTPUTS
% fs - {mxn} list of full file names of copied files
%
% EXAMPLE
%
% See also bbGt, bbGt>getFiles
[m,n]=size(fs); assert(numel(dirs)==m); if(n==0), return; end
for d=1:m
if(~exist(dirs{d},'dir')), mkdir(dirs{d}); end
for i=1:n, f=fs{d,i}; j=[0 find(f=='/' | f=='\')]; j=j(end);
fs{d,i}=[dirs{d} '/' f(j+1:end)]; copyfile(f,fs{d,i}); end
end
end
function [gt0,dt0] = loadAll( gtDir, dtDir, pLoad )
% Load all ground truth and detection bbs in given directories.
%
% Loads each ground truth (gt) annotation in gtDir and the corresponding
% detection (dt) in dtDir. gt and dt files must correspond according to
% getFiles(). Alternatively, dtDir may be a filename of a single text file
% that contains the detection results across all images.
%
% Each dt should be a text file where each row contains 5 numbers
% representing a bb (left/top/width/height/score). If dtDir is a text file,
% it should contain the detection results across the full set of images. In
% this case each row in the text file should have an extra leading column
% specifying the image id: (imgId/left/top/width/height/score).
%
% The output of this function can be used in bbGt>evalRes().
%
% USAGE
% [gt0,dt0] = bbGt( 'loadAll', gtDir, [dtDir], [pLoad] )
%
% INPUTS
% gtDir - location of ground truth
% dtDir - [] optional location of detections
% pLoad - {} params for bbGt>bbLoad() (determine format/filtering)
%
% OUTPUTS
% gt0 - {1xn} loaded ground truth bbs (each is a mx5 array of bbs)
% dt0 - {1xn} loaded detections (each is a mx5 array of bbs)
%
% EXAMPLE
%
% See also bbGt, bbGt>getFiles, bbGt>evalRes
% get list of files
if(nargin<2), dtDir=[]; end
if(nargin<3), pLoad={}; end
if(isempty(dtDir)), fs=getFiles({gtDir}); gtFs=fs(1,:); else
dtFile=length(dtDir)>4 && strcmp(dtDir(end-3:end),'.txt');
if(dtFile), dirs={gtDir}; else dirs={gtDir,dtDir}; end
fs=getFiles(dirs); gtFs=fs(1,:);
if(dtFile), dtFs=dtDir; else dtFs=fs(2,:); end
end
% load ground truth
persistent keyPrv gtPrv; key={gtDir,pLoad}; n=length(gtFs);
if(isequal(key,keyPrv)), gt0=gtPrv; else gt0=cell(1,n);
for i=1:n, [~,gt0{i}]=bbLoad(gtFs{i},pLoad); end
gtPrv=gt0; keyPrv=key;
end
% load detections
if(isempty(dtDir) || nargout<=1), dt0=cell(0); return; end
if(iscell(dtFs)), dt0=cell(1,n);
for i=1:n, dt1=load(dtFs{i},'-ascii');
if(numel(dt1)==0), dt1=zeros(0,5); end; dt0{i}=dt1(:,1:5); end
else
dt1=load(dtFs,'-ascii'); if(numel(dt1)==0), dt1=zeros(0,6); end
ids=dt1(:,1); assert(max(ids)<=n);
dt0=cell(1,n); for i=1:n, dt0{i}=dt1(ids==i,2:6); end
end
end
function [gt,dt] = evalRes( gt0, dt0, thr, mul )
% Evaluates detections against ground truth data.
%
% Uses modified Pascal criteria that allows for "ignore" regions. The
% Pascal criteria states that a ground truth bounding box (gtBb) and a
% detected bounding box (dtBb) match if their overlap area (oa):
% oa(gtBb,dtBb) = area(intersect(gtBb,dtBb)) / area(union(gtBb,dtBb))
% is over a sufficient threshold (typically .5). In the modified criteria,
% the dtBb can match any subregion of a gtBb set to "ignore". Choosing
% gtBb' in gtBb that most closely matches dtBb can be done by using
% gtBb'=intersect(dtBb,gtBb). Computing oa(gtBb',dtBb) is equivalent to
% oa'(gtBb,dtBb) = area(intersect(gtBb,dtBb)) / area(dtBb)
% For gtBb set to ignore the above formula for oa is used.
%
% Highest scoring detections are matched first. Matches to standard,
% (non-ignore) gtBb are preferred. Each dtBb and gtBb may be matched at
% most once, except for ignore-gtBb which can be matched multiple times.
% Unmatched dtBb are false-positives, unmatched gtBb are false-negatives.
% Each match between a dtBb and gtBb is a true-positive, except matches
% between dtBb and ignore-gtBb which do not affect the evaluation criteria.
%
% In addition to taking gt/dt results on a single image, evalRes() can take
% cell arrays of gt/dt bbs, in which case evaluation proceeds on each
% element. Use bbGt>loadAll() to load gt/dt for multiple images.
%
% Each gt/dt output row has a flag match that is either -1/0/1:
% for gt: -1=ignore, 0=fn [unmatched], 1=tp [matched]
% for dt: -1=ignore, 0=fp [unmatched], 1=tp [matched]
%
% USAGE
% [gt, dt] = bbGt( 'evalRes', gt0, dt0, [thr], [mul] )
%
% INPUTS
% gt0 - [mx5] ground truth array with rows [x y w h ignore]
% dt0 - [nx5] detection results array with rows [x y w h score]
% thr - [.5] the threshold on oa for comparing two bbs
% mul - [0] if true allow multiple matches to each gt
%
% OUTPUTS
% gt - [mx5] ground truth results [x y w h match]
% dt - [nx6] detection results [x y w h score match]
%
% EXAMPLE
%
% See also bbGt, bbGt>compOas, bbGt>loadAll
% get parameters
if(nargin<3 || isempty(thr)), thr=.5; end
if(nargin<4 || isempty(mul)), mul=0; end
% if gt0 and dt0 are cell arrays run on each element in turn
if( iscell(gt0) && iscell(dt0) ), n=length(gt0);
assert(length(dt0)==n); gt=cell(1,n); dt=gt;
for i=1:n, [gt{i},dt{i}] = evalRes(gt0{i},dt0{i},thr,mul); end; return;
end
% check inputs
if(isempty(gt0)), gt0=zeros(0,5); end
if(isempty(dt0)), dt0=zeros(0,5); end
assert( size(dt0,2)==5 ); nd=size(dt0,1);
assert( size(gt0,2)==5 ); ng=size(gt0,1);
% sort dt highest score first, sort gt ignore last
[~,ord]=sort(dt0(:,5),'descend'); dt0=dt0(ord,:);
[~,ord]=sort(gt0(:,5),'ascend'); gt0=gt0(ord,:);
gt=gt0; gt(:,5)=-gt(:,5); dt=dt0; dt=[dt zeros(nd,1)];
% Attempt to match each (sorted) dt to each (sorted) gt
oa = compOas( dt(:,1:4), gt(:,1:4), gt(:,5)==-1 );
for d=1:nd
bstOa=thr; bstg=0; bstm=0; % info about best match so far
for g=1:ng
% if this gt already matched, continue to next gt
m=gt(g,5); if( m==1 && ~mul ), continue; end
% if dt already matched, and on ignore gt, nothing more to do
if( bstm~=0 && m==-1 ), break; end
% compute overlap area, continue to next gt unless better match made
if(oa(d,g)<bstOa), continue; end
% match successful and best so far, store appropriately
bstOa=oa(d,g); bstg=g; if(m==0), bstm=1; else bstm=-1; end
end; g=bstg; m=bstm;
% store type of match for both dt and gt
if(m==-1), dt(d,6)=m; elseif(m==1), gt(g,5)=m; dt(d,6)=m; end
end
end
function [hs,hImg] = showRes( I, gt, dt, varargin )
% Display evaluation results for given image.
%
% USAGE
% [hs,hImg] = bbGt( 'showRes', I, gt, dt, varargin )
%
% INPUTS
% I - image to display, image filename, or []
% gt - first output of evalRes()
% dt - second output of evalRes()
% varargin - additional parameters (struct or name/value pairs)
% .evShow - [1] if true show results of evaluation
% .gtShow - [1] if true show ground truth
% .dtShow - [1] if true show detections
% .cols - ['krg'] colors for ignore/mistake/correct
% .gtLs - ['-'] line style for gt bbs
% .dtLs - ['--'] line style for dt bbs
% .lw - [3] line width
%
% OUTPUTS
% hs - handles to bbs and text labels
% hImg - handle for image graphics object
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
dfs={'evShow',1,'gtShow',1,'dtShow',1,'cols','krg',...
'gtLs','-','dtLs','--','lw',3};
[evShow,gtShow,dtShow,cols,gtLs,dtLs,lw]=getPrmDflt(varargin,dfs,1);
% optionally display image
if(ischar(I)), I=imread(I); end
if(~isempty(I)), hImg=im(I,[],0); title(''); end
% display bbs with or w/o color coding based on output of evalRes
hold on; hs=cell(1,1000); k=0;
if( evShow )
if(gtShow), for i=1:size(gt,1), k=k+1;
hs{k}=bbApply('draw',gt(i,1:4),cols(gt(i,5)+2),lw,gtLs); end; end
if(dtShow), for i=1:size(dt,1), k=k+1;
hs{k}=bbApply('draw',dt(i,1:5),cols(dt(i,6)+2),lw,dtLs); end; end
else
if(gtShow), k=k+1; hs{k}=bbApply('draw',gt(:,1:4),cols(3),lw,gtLs); end
if(dtShow), k=k+1; hs{k}=bbApply('draw',dt(:,1:5),cols(3),lw,dtLs); end
end
hs=[hs{:}]; hold off;
end
function [xs,ys,score,ref] = compRoc( gt, dt, roc, ref )
% Compute ROC or PR based on outputs of evalRes on multiple images.
%
% ROC="Receiver operating characteristic"; PR="Precision Recall"
% Also computes result at reference points (ref):
% which for ROC curves is the *detection* rate at reference *FPPI*
% which for PR curves is the *precision* at reference *recall*
% Note, FPPI="false positive per image"
%
% USAGE
% [xs,ys,score,ref] = bbGt( 'compRoc', gt, dt, roc, ref )
%
% INPUTS
% gt - {1xn} first output of evalRes() for each image
% dt - {1xn} second output of evalRes() for each image
% roc - [1] if 1 compue ROC else compute PR
% ref - [] reference points for ROC or PR curve
%
% OUTPUTS
% xs - x coords for curve: ROC->FPPI; PR->recall
% ys - y coords for curve: ROC->TP; PR->precision
% score - detection scores corresponding to each (x,y)
% ref - recall or precision at each reference point
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
% get additional parameters
if(nargin<3 || isempty(roc)), roc=1; end
if(nargin<4 || isempty(ref)), ref=[]; end
% convert to single matrix, discard ignore bbs
nImg=length(gt); assert(length(dt)==nImg);
gt=cat(1,gt{:}); gt=gt(gt(:,5)~=-1,:);
dt=cat(1,dt{:}); dt=dt(dt(:,6)~=-1,:);
% compute results
if(size(dt,1)==0), xs=0; ys=0; score=0; ref=ref*0; return; end
m=length(ref); np=size(gt,1); score=dt(:,5); tp=dt(:,6);
[score,order]=sort(score,'descend'); tp=tp(order);
fp=double(tp~=1); fp=cumsum(fp); tp=cumsum(tp);
if( roc )
xs=fp/nImg; ys=tp/np; xs1=[-inf; xs]; ys1=[0; ys];
for i=1:m, j=find(xs1<=ref(i)); ref(i)=ys1(j(end)); end
else
xs=tp/np; ys=tp./(fp+tp); xs1=[xs; inf]; ys1=[ys; 0];
for i=1:m, j=find(xs1>=ref(i)); ref(i)=ys1(j(1)); end
end
end
function [Is,scores,imgIds] = cropRes( gt, dt, imFs, varargin )
% Extract true or false positives or negatives for visualization.
%
% USAGE
% [Is,scores,imgIds] = bbGt( 'cropRes', gt, dt, imFs, varargin )
%
% INPUTS
% gt - {1xN} first output of evalRes() for each image
% dt - {1xN} second output of evalRes() for each image
% imFs - {1xN} name of each image
% varargin - additional parameters (struct or name/value pairs)
% .dims - ['REQ'] target dimensions for extracted windows
% .pad - [0] padding amount for cropping
% .type - ['fp'] one of: 'fp', 'fn', 'tp', 'dt'
% .n - [100] max number of windows to extract
% .show - [1] figure for displaying results (or 0)
% .fStr - ['%0.1f'] label{i}=num2str(score(i),fStr)
% .embed - [0] if true embed dt/gt bbs into cropped windows
%
% OUTPUTS
% Is - [dimsxn] extracted image windows
% scores - [1xn] detection score for each bb unless 'fn'
% imgIds - [1xn] image id for each cropped window
%
% EXAMPLE
%
% See also bbGt, bbGt>evalRes
dfs={'dims','REQ','pad',0,'type','fp','n',100,...
'show',1,'fStr','%0.1f','embed',0};
[dims,pad,type,n,show,fStr,embed]=getPrmDflt(varargin,dfs,1);
N=length(imFs); assert(length(gt)==N && length(dt)==N);
% crop patches either in gt or dt according to type
switch type
case 'fn', bbs=gt; keep=@(bbs) bbs(:,5)==0;
case 'fp', bbs=dt; keep=@(bbs) bbs(:,6)==0;
case 'tp', bbs=dt; keep=@(bbs) bbs(:,6)==1;
case 'dt', bbs=dt; keep=@(bbs) bbs(:,6)>=0;
otherwise, error('unknown type: %s',type);
end
% create ids that will map each bb to correct name
ms=zeros(1,N); for i=1:N, ms(i)=size(bbs{i},1); end; cms=[0 cumsum(ms)];
ids=zeros(1,sum(ms)); for i=1:N, ids(cms(i)+1:cms(i+1))=i; end
% flatten bbs and keep relevent subset
bbs=cat(1,bbs{:}); K=keep(bbs); bbs=bbs(K,:); ids=ids(K); n=min(n,sum(K));
% reorder bbs appropriately
if(~strcmp(type,'fn')), [~,ord]=sort(bbs(:,5),'descend'); else
if(size(bbs,1)<n), ord=randperm(size(bbs,1)); else ord=1:n; end; end
bbs=bbs(ord(1:n),:); ids=ids(ord(1:n));
% extract patches from each image
if(n==0), Is=[]; scores=[]; imgIds=[]; return; end;
Is=cell(1,n); scores=zeros(1,n); imgIds=zeros(1,n);
if(any(pad>0)), dims1=dims.*(1+pad); rs=dims1./dims; dims=dims1; end
if(any(pad>0)), bbs=bbApply('resize',bbs,rs(1),rs(2)); end
for i=1:N
locs=find(ids==i); if(isempty(locs)), continue; end; I=imread(imFs{i});
if( embed )
if(any(strcmp(type,{'fp','dt'}))), bbs1=gt{i};
else bbs1=dt{i}(:,[1:4 6]); end
I=bbApply('embed',I,bbs1(bbs1(:,5)==0,1:4),'col',[255 0 0]);
I=bbApply('embed',I,bbs1(bbs1(:,5)==1,1:4),'col',[0 255 0]);
end
Is1=bbApply('crop',I,bbs(locs,1:4),'replicate',dims);
for j=1:length(locs), Is{locs(j)}=Is1{j}; end;
scores(locs)=bbs(locs,5); imgIds(locs)=i;
end; Is=cell2array(Is);
% optionally display
if(~show), return; end; figure(show); pMnt={'hasChn',size(Is1{1},3)>1};
if(isempty(fStr)), montage2(Is,pMnt); title(type); return; end
ls=cell(1,n); for i=1:n, ls{i}=int2str2(imgIds(i)); end
if(~strcmp(type,'fn'))
for i=1:n, ls{i}=[ls{i} '/' num2str(scores(i),fStr)]; end; end
montage2(Is,[pMnt 'labels' {ls}]); title(type);
end
function oa = compOas( dt, gt, ig )
% Computes (modified) overlap area between pairs of bbs.
%
% Uses modified Pascal criteria with "ignore" regions. The overlap area
% (oa) of a ground truth (gt) and detected (dt) bb is defined as:
% oa(gt,dt) = area(intersect(dt,dt)) / area(union(gt,dt))
% In the modified criteria, a gt bb may be marked as "ignore", in which
% case the dt bb can can match any subregion of the gt bb. Choosing gt' in
% gt that most closely matches dt can be done using gt'=intersect(dt,gt).
% Computing oa(gt',dt) is equivalent to:
% oa'(gt,dt) = area(intersect(gt,dt)) / area(dt)
%
% USAGE
% oa = bbGt( 'compOas', dt, gt, [ig] )
%
% INPUTS
% dt - [mx4] detected bbs
% gt - [nx4] gt bbs
% ig - [nx1] 0/1 ignore flags (0 by default)
%
% OUTPUTS
% oas - [m x n] overlap area between each gt and each dt bb
%
% EXAMPLE
% dt=[0 0 10 10]; gt=[0 0 20 20];
% oa0 = bbGt('compOas',dt,gt,0)
% oa1 = bbGt('compOas',dt,gt,1)
%
% See also bbGt, bbGt>evalRes
m=size(dt,1); n=size(gt,1); oa=zeros(m,n);
if(nargin<3), ig=zeros(n,1); end
de=dt(:,[1 2])+dt(:,[3 4]); da=dt(:,3).*dt(:,4);
ge=gt(:,[1 2])+gt(:,[3 4]); ga=gt(:,3).*gt(:,4);
for i=1:m
for j=1:n
w=min(de(i,1),ge(j,1))-max(dt(i,1),gt(j,1)); if(w<=0), continue; end
h=min(de(i,2),ge(j,2))-max(dt(i,2),gt(j,2)); if(h<=0), continue; end
t=w*h; if(ig(j)), u=da(i); else u=da(i)+ga(j)-t; end; oa(i,j)=t/u;
end
end
end
function oa = compOa( dt, gt, ig )
% Optimized version of compOas for a single pair of bbs.
%
% USAGE
% oa = bbGt( 'compOa', dt, gt, ig )
%
% INPUTS
% dt - [1x4] detected bb
% gt - [1x4] gt bb
% ig - 0/1 ignore flag
%
% OUTPUTS
% oa - overlap area between gt and dt bb
%
% EXAMPLE
% dt=[0 0 10 10]; gt=[0 0 20 20];
% oa0 = bbGt('compOa',dt,gt,0)
% oa1 = bbGt('compOa',dt,gt,1)
%
% See also bbGt, bbGt>compOas
w=min(dt(3)+dt(1),gt(3)+gt(1))-max(dt(1),gt(1)); if(w<=0),oa=0; return; end
h=min(dt(4)+dt(2),gt(4)+gt(2))-max(dt(2),gt(2)); if(h<=0),oa=0; return; end
i=w*h; if(ig),u=dt(3)*dt(4); else u=dt(3)*dt(4)+gt(3)*gt(4)-i; end; oa=i/u;
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
bbApply.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/detector/bbApply.m
| 21,195 |
utf_8
|
8c02a6999a84bfb5fcbf2274b8b91a97
|
function varargout = bbApply( action, varargin )
% Functions for manipulating bounding boxes (bb).
%
% A bounding box (bb) is also known as a position vector or a rectangle
% object. It is a four element vector with the fields: [x y w h]. A set of
% n bbs can be stores as an [nx4] array, most funcitons below can handle
% either a single or multiple bbs. In addtion, typically [nxm] inputs with
% m>4 are ok (with the additional columns ignored/copied to the output).
%
% bbApply contains a number of utility functions for working with bbs. The
% format for accessing the various utility functions is:
% outputs = bbApply( 'action', inputs );
% The list of functions and help for each is given below. Also, help on
% individual subfunctions can be accessed by: "help bbApply>action".
%
% Compute area of bbs.
% bb = bbApply( 'area', bb )
% Shift center of bbs.
% bb = bbApply( 'shift', bb, xdel, ydel )
% Get center of bbs.
% cen = bbApply( 'getCenter', bb )
% Get bb at intersection of bb1 and bb2 (may be empty).
% bb = bbApply( 'intersect', bb1, bb2 )
% Get bb that is union of bb1 and bb2 (smallest bb containing both).
% bb = bbApply( 'union', bb1, bb2 )
% Resize the bbs (without moving their centers).
% bb = bbApply( 'resize', bb, hr, wr, [ar] )
% Fix bb aspect ratios (without moving the bb centers).
% bbr = bbApply( 'squarify', bb, flag, [ar] )
% Draw single or multiple bbs to image (calls rectangle()).
% hs = bbApply( 'draw', bb, [col], [lw], [ls], [prop], [ids] )
% Embed single or multiple bbs directly into image.
% I = bbApply( 'embed', I, bb, [varargin] )
% Crop image regions from I encompassed by bbs.
% [patches, bbs] = bbApply('crop',I,bb,[padEl],[dims])
% Convert bb relative to absolute coordinates and vice-versa.
% bb = bbApply( 'convert', bb, bbRef, isAbs )
% Randomly generate bbs that fall in a specified region.
% bbs = bbApply( 'random', pRandom )
% Convert weighted mask to bbs.
% bbs = bbApply('frMask',M,bbw,bbh,[thr])
% Create weighted mask encoding bb centers (or extent).
% M = bbApply('toMask',bbs,w,h,[fill],[bgrd])
%
% USAGE
% varargout = bbApply( action, varargin );
%
% INPUTS
% action - string specifying action
% varargin - depends on action, see above
%
% OUTPUTS
% varargout - depends on action, see above
%
% EXAMPLE
%
% See also bbApply>area bbApply>shift bbApply>getCenter bbApply>intersect
% bbApply>union bbApply>resize bbApply>squarify bbApply>draw bbApply>crop
% bbApply>convert bbApply>random bbApply>frMask bbApply>toMask
%
% Piotr's Computer Vision Matlab Toolbox Version 3.30
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
%#ok<*DEFNU>
varargout = cell(1,max(1,nargout));
[varargout{:}] = feval(action,varargin{:});
end
function a = area( bb )
% Compute area of bbs.
%
% USAGE
% bb = bbApply( 'area', bb )
%
% INPUTS
% bb - [nx4] original bbs
%
% OUTPUTS
% a - [nx1] area of each bb
%
% EXAMPLE
% a = bbApply('area', [0 0 10 10])
%
% See also bbApply
a=prod(bb(:,3:4),2);
end
function bb = shift( bb, xdel, ydel )
% Shift center of bbs.
%
% USAGE
% bb = bbApply( 'shift', bb, xdel, ydel )
%
% INPUTS
% bb - [nx4] original bbs
% xdel - amount to shift x coord of each bb left
% ydel - amount to shift y coord of each bb up
%
% OUTPUTS
% bb - [nx4] shifted bbs
%
% EXAMPLE
% bb = bbApply('shift', [0 0 10 10], 1, 2)
%
% See also bbApply
bb(:,1)=bb(:,1)-xdel; bb(:,2)=bb(:,2)-ydel;
end
function cen = getCenter( bb )
% Get center of bbs.
%
% USAGE
% cen = bbApply( 'getCenter', bb )
%
% INPUTS
% bb - [nx4] original bbs
%
% OUTPUTS
% cen - [nx1] centers of bbs
%
% EXAMPLE
% cen = bbApply('getCenter', [0 0 10 10])
%
% See also bbApply
cen=bb(:,1:2)+bb(:,3:4)/2;
end
function bb = intersect( bb1, bb2 )
% Get bb at intersection of bb1 and bb2 (may be empty).
%
% USAGE
% bb = bbApply( 'intersect', bb1, bb2 )
%
% INPUTS
% bb1 - [nx4] first set of bbs
% bb2 - [nx4] second set of bbs
%
% OUTPUTS
% bb - [nx4] intersection of bbs
%
% EXAMPLE
% bb = bbApply('intersect', [0 0 10 10], [5 5 10 10])
%
% See also bbApply bbApply>union
n1=size(bb1,1); n2=size(bb2,1);
if(n1==0 || n2==0), bb=zeros(0,4); return, end
if(n1==1 && n2>1), bb1=repmat(bb1,n2,1); n1=n2; end
if(n2==1 && n1>1), bb2=repmat(bb2,n1,1); n2=n1; end
assert(n1==n2);
lcsE=min(bb1(:,1:2)+bb1(:,3:4),bb2(:,1:2)+bb2(:,3:4));
lcsS=max(bb1(:,1:2),bb2(:,1:2)); empty=any(lcsE<lcsS,2);
bb=[lcsS lcsE-lcsS]; bb(empty,:)=0;
end
function bb = union( bb1, bb2 )
% Get bb that is union of bb1 and bb2 (smallest bb containing both).
%
% USAGE
% bb = bbApply( 'union', bb1, bb2 )
%
% INPUTS
% bb1 - [nx4] first set of bbs
% bb2 - [nx4] second set of bbs
%
% OUTPUTS
% bb - [nx4] intersection of bbs
%
% EXAMPLE
% bb = bbApply('union', [0 0 10 10], [5 5 10 10])
%
% See also bbApply bbApply>intersect
n1=size(bb1,1); n2=size(bb2,1);
if(n1==0 || n2==0), bb=zeros(0,4); return, end
if(n1==1 && n2>1), bb1=repmat(bb1,n2,1); n1=n2; end
if(n2==1 && n1>1), bb2=repmat(bb2,n1,1); n2=n1; end
assert(n1==n2);
lcsE=max(bb1(:,1:2)+bb1(:,3:4),bb2(:,1:2)+bb2(:,3:4));
lcsS=min(bb1(:,1:2),bb2(:,1:2));
bb=[lcsS lcsE-lcsS];
end
function bb = resize( bb, hr, wr, ar )
% Resize the bbs (without moving their centers).
%
% If wr>0 or hr>0, the w/h of each bb is adjusted in the following order:
% if(hr~=0), h=h*hr; end
% if(wr~=0), w=w*wr; end
% if(hr==0), h=w/ar; end
% if(wr==0), w=h*ar; end
% Only one of hr/wr may be set to 0, and then only if ar>0. If, however,
% hr=wr=0 and ar>0 then resizes bbs such that areas and centers are
% preserved but aspect ratio becomes ar.
%
% USAGE
% bb = bbApply( 'resize', bb, hr, wr, [ar] )
%
% INPUTS
% bb - [nx4] original bbs
% hr - ratio by which to multiply height (or 0)
% wr - ratio by which to multiply width (or 0)
% ar - [0] target aspect ratio (used only if hr=0 or wr=0)
%
% OUTPUT
% bb - [nx4] the output resized bbs
%
% EXAMPLE
% bb = bbApply('resize',[0 0 1 1],1.2,0,.5) % h'=1.2*h; w'=h'/2;
%
% See also bbApply, bbApply>squarify
if(nargin<4), ar=0; end; assert(size(bb,2)>=4);
assert((hr>0&&wr>0)||ar>0);
% preserve area and center, set aspect ratio
if(hr==0 && wr==0), a=sqrt(bb(:,3).*bb(:,4)); ar=sqrt(ar);
d=a*ar-bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d;
d=a/ar-bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; return;
end
% possibly adjust h/w based on hr/wr
if(hr~=0), d=(hr-1)*bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; end
if(wr~=0), d=(wr-1)*bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d; end
% possibly adjust h/w based on ar and NEW h/w
if(~hr), d=bb(:,3)/ar-bb(:,4); bb(:,2)=bb(:,2)-d/2; bb(:,4)=bb(:,4)+d; end
if(~wr), d=bb(:,4)*ar-bb(:,3); bb(:,1)=bb(:,1)-d/2; bb(:,3)=bb(:,3)+d; end
end
function bbr = squarify( bb, flag, ar )
% Fix bb aspect ratios (without moving the bb centers).
%
% The w or h of each bb is adjusted so that w/h=ar.
% The parameter flag controls whether w or h should change:
% flag==0: expand bb to given ar
% flag==1: shrink bb to given ar
% flag==2: use original w, alter h
% flag==3: use original h, alter w
% flag==4: preserve area, alter w and h
% If ar==1 (the default), always converts bb to a square, hence the name.
%
% USAGE
% bbr = bbApply( 'squarify', bb, flag, [ar] )
%
% INPUTS
% bb - [nx4] original bbs
% flag - controls whether w or h should change
% ar - [1] desired aspect ratio
%
% OUTPUT
% bbr - the output 'squarified' bbs
%
% EXAMPLE
% bbr = bbApply('squarify',[0 0 1 2],0)
%
% See also bbApply, bbApply>resize
if(nargin<3 || isempty(ar)), ar=1; end; bbr=bb;
if(flag==4), bbr=resize(bb,0,0,ar); return; end
for i=1:size(bb,1), p=bb(i,1:4);
usew = (flag==0 && p(3)>p(4)*ar) || (flag==1 && p(3)<p(4)*ar) || flag==2;
if(usew), p=resize(p,0,1,ar); else p=resize(p,1,0,ar); end; bbr(i,1:4)=p;
end
end
function hs = draw( bb, col, lw, ls, prop, ids )
% Draw single or multiple bbs to image (calls rectangle()).
%
% To draw bbs aligned with pixel boundaries, subtract .5 from the x and y
% coordinates (since pixel centers are located at integer locations).
%
% USAGE
% hs = bbApply( 'draw', bb, [col], [lw], [ls], [prop], [ids] )
%
% INPUTS
% bb - [nx4] standard bbs or [nx5] weighted bbs
% col - ['g'] color or [kx1] array of colors
% lw - [2] LineWidth for rectangle
% ls - ['-'] LineStyle for rectangle
% prop - [] other properties for rectangle
% ids - [ones(1,n)] id in [1,k] for each bb into colors array
%
% OUTPUT
% hs - [nx1] handles to drawn rectangles (and labels)
%
% EXAMPLE
% im(rand(3)); bbApply('draw',[1.5 1.5 1 1 .5],'g');
%
% See also bbApply, bbApply>embed, rectangle
[n,m]=size(bb); if(n==0), hs=[]; return; end
if(nargin<2 || isempty(col)), col=[]; end
if(nargin<3 || isempty(lw)), lw=2; end
if(nargin<4 || isempty(ls)), ls='-'; end
if(nargin<5 || isempty(prop)), prop={}; end
if(nargin<6 || isempty(ids)), ids=ones(1,n); end
% prepare display properties
prop=['LineWidth' lw 'LineStyle' ls prop 'EdgeColor'];
tProp={'FontSize',10,'color','w','FontWeight','bold',...
'VerticalAlignment','bottom'}; k=max(ids);
if(isempty(col)), if(k==1), col='g'; else col=hsv(k); end; end
if(size(col,1)<k), ids=ones(1,n); end; hs=zeros(1,n);
% draw rectangles and optionally labels
for b=1:n, hs(b)=rectangle('Position',bb(b,1:4),prop{:},col(ids(b),:)); end
if(m==4), return; end; hs=[hs zeros(1,n)]; bb=double(bb);
for b=1:n, hs(b+n)=text(bb(b,1),bb(b,2),num2str(bb(b,5),4),tProp{:}); end
end
function I = embed( I, bb, varargin )
% Embed single or multiple bbs directly into image.
%
% USAGE
% I = bbApply( 'embed', I, bb, varargin )
%
% INPUTS
% I - input image
% bb - [nx4] or [nx5] input bbs
% varargin - additional params (struct or name/value pairs)
% .col - [0 255 0] color for rectangle or nx3 array of colors
% .lw - [3] width for rectangle in pixels
% .fh - [35] font height (if displaying weight), may be 0
% .fcol - [255 0 0] font color or nx3 array of colors
%
% OUTPUT
% I - output image
%
% EXAMPLE
% I=imResample(imread('cameraman.tif'),2); bb=[200 70 70 90 0.25];
% J=bbApply('embed',I,bb,'col',[0 0 255],'lw',8,'fh',30); figure(1); im(J)
% K=bbApply('embed',J,bb,'col',[0 255 0],'lw',2,'fh',30); figure(2); im(K)
%
% See also bbApply, bbApply>draw, char2img
% get additional parameters
dfs={'col',[0 255 0],'lw',3,'fh',35,'fcol',[255 0 0]};
[col,lw,fh,fcol]=getPrmDflt(varargin,dfs,1);
n=size(bb,1); bb(:,1:4)=round(bb(:,1:4));
if(size(col,1)==1), col=col(ones(1,n),:); end
if(size(fcol,1)==1), fcol=fcol(ones(1,n),:); end
if( ismatrix(I) ), I=I(:,:,[1 1 1]); end
% embed each bb
x0=bb(:,1); x1=x0+bb(:,3)-1; y0=bb(:,2); y1=y0+bb(:,4)-1;
j0=floor((lw-1)/2); j1=ceil((lw-1)/2); h=size(I,1); w=size(I,2);
x00=max(1,x0-j0); x01=min(x0+j1,w); x10=max(1,x1-j0); x11=min(x1+j1,w);
y00=max(1,y0-j0); y01=min(y0+j1,h); y10=max(1,y1-j0); y11=min(y1+j1,h);
for b=1:n
for c=1:3, I([y00(b):y01(b) y10(b):y11(b)],x00(b):x11(b),c)=col(b,c); end
for c=1:3, I(y00(b):y11(b),[x00(b):x01(b) x10(b):x11(b)],c)=col(b,c); end
end
% embed text displaying bb score (inside upper-left bb corner)
if(size(bb,2)<5 || fh==0), return; end
bb(:,1:4)=intersect(bb(:,1:4),[1 1 w h]);
for b=1:n
M=char2img(sprintf('%.4g',bb(b,5)),fh); M=M{1}==0; [h,w]=size(M);
y0=bb(b,2); y1=y0+h-1; x0=bb(b,1); x1=x0+w-1;
if( x0>=1 && y0>=1 && x1<=size(I,2) && y1<=size(I,1))
Ir=I(y0:y1,x0:x1,1); Ig=I(y0:y1,x0:x1,2); Ib=I(y0:y1,x0:x1,3);
Ir(M)=fcol(b,1); Ig(M)=fcol(b,2); Ib(M)=fcol(b,3);
I(y0:y1,x0:x1,:)=cat(3,Ir,Ig,Ib);
end
end
end
function [patches, bbs] = crop( I, bbs, padEl, dims )
% Crop image regions from I encompassed by bbs.
%
% The only subtlety is that a pixel centered at location (i,j) would have a
% bb of [j-1/2,i-1/2,1,1]. The -1/2 is because pixels are located at
% integer locations. This is a Matlab convention, to confirm use:
% im(rand(3)); bbApply('draw',[1.5 1.5 1 1],'g')
% If bb contains all integer entries cropping is straightforward. If
% entries are not integers, x=round(x+.499) is used, eg 1.2 actually goes
% to 2 (since it is closer to 1.5 then .5), and likewise for y.
%
% If ~isempty(padEl), image is padded so can extract full bb region (no
% actual padding is done, this is fast). Otherwise bb is intersected with
% the image bb prior to cropping. If padEl is a string ('circular',
% 'replicate', or 'symmetric'), uses padarray to do actual padding (slow).
%
% USAGE
% [patches, bbs] = bbApply('crop',I,bb,[padEl],[dims])
%
% INPUTS
% I - image from which to crop patches
% bbs - bbs that indicate regions to crop
% padEl - [0] value to pad I or [] to indicate no padding (see above)
% dims - [] if specified resize each cropped patch to [w h]
%
% OUTPUTS
% patches - [1xn] cell of cropped image regions
% bbs - actual integer-valued bbs used to crop
%
% EXAMPLE
% I=imread('cameraman.tif'); bb=[-10 -10 100 100];
% p1=bbApply('crop',I,bb); p2=bbApply('crop',I,bb,'replicate');
% figure(1); im(I); figure(2); im(p1{1}); figure(3); im(p2{1});
%
% See also bbApply, ARRAYCROP, PADARRAY, IMRESAMPLE
% get padEl, bound bb to visible region if empty
if( nargin<3 ), padEl=0; end; h=size(I,1); w=size(I,2);
if( nargin<4 ), dims=[]; end;
if(isempty(padEl)), bbs=intersect([.5 .5 w h],bbs); end
% crop each patch in turn
n=size(bbs,1); patches=cell(1,n);
for i=1:n, [patches{i},bbs(i,1:4)]=crop1(bbs(i,1:4)); end
function [patch, bb] = crop1( bb )
% crop single patch (use arrayCrop only if necessary)
lcsS=round(bb([2 1])+.5-.001); lcsE=lcsS+round(bb([4 3]))-1;
if( any(lcsS<1) || lcsE(1)>h || lcsE(2)>w )
if( ischar(padEl) )
pt=max(0,1-lcsS(1)); pb=max(0,lcsE(1)-h);
pl=max(0,1-lcsS(2)); pr=max(0,lcsE(2)-w);
lcsS1=max(1,lcsS); lcsE1=min(lcsE,[h w]);
patch = I(lcsS1(1):lcsE1(1),lcsS1(2):lcsE1(2),:);
patch = padarray(patch,[pt pl],padEl,'pre');
patch = padarray(patch,[pb pr],padEl,'post');
else
if(ndims(I)==3); lcsS=[lcsS 1]; lcsE=[lcsE 3]; end
patch = arrayCrop(I,lcsS,lcsE,padEl);
end
else
patch = I(lcsS(1):lcsE(1),lcsS(2):lcsE(2),:);
end
bb = [lcsS([2 1]) lcsE([2 1])-lcsS([2 1])+1];
if(~isempty(dims)), patch=imResample(patch,[dims(2),dims(1)]); end
end
end
function bb = convert( bb, bbRef, isAbs )
% Convert bb relative to absolute coordinates and vice-versa.
%
% If isAbs==1, bb is assumed to be given in absolute coords, and the output
% is given in coords relative to bbRef. Otherwise, if isAbs==0, bb is
% assumed to be given in coords relative to bbRef and the output is given
% in absolute coords.
%
% USAGE
% bb = bbApply( 'convert', bb, bbRef, isAbs )
%
% INPUTS
% bb - original bb, either in abs or rel coords
% bbRef - reference bb
% isAbs - 1: bb is in abs coords, 0: bb is in rel coords
%
% OUTPUTS
% bb - converted bb
%
% EXAMPLE
% bbRef=[5 5 15 15]; bba=[10 10 5 5];
% bbr = bbApply( 'convert', bba, bbRef, 1 )
% bba2 = bbApply( 'convert', bbr, bbRef, 0 )
%
% See also bbApply
if( isAbs )
bb(1:2)=bb(1:2)-bbRef(1:2);
bb=bb./bbRef([3 4 3 4]);
else
bb=bb.*bbRef([3 4 3 4]);
bb(1:2)=bb(1:2)+bbRef(1:2);
end
end
function bbs = random( varargin )
% Randomly generate bbs that fall in a specified region.
%
% The vector dims defines the region in which bbs are generated. Specify
% dims=[height width] to generate bbs=[x y w h] such that: 1<=x<=width,
% 1<=y<=height, x+w-1<=width, y+h-1<=height. The biggest bb generated can
% be bb=[1 1 width height]. If dims is a three element vector the third
% coordinate is the depth, in this case bbs=[x y w h d] where 1<=d<=depth.
%
% A number of constraints can be specified that control the size and other
% characteristics of the generated bbs. Note that if incompatible
% constraints are specified (e.g. if the maximum width and height are both
% 5 while the minimum area is 100) no bbs will be generated. More
% generally, if fewer than n bbs are generated a warning is displayed.
%
% USAGE
% bbs = bbApply( 'random', pRandom )
%
% INPUTS
% pRandom - parameters (struct or name/value pairs)
% .n - ['REQ'] number of bbs to generate
% .dims - ['REQ'] region in which to generate bbs [height,width]
% .wRng - [1 inf] range for width of bbs (or scalar value)
% .hRng - [1 inf] range for height of bbs (or scalar value)
% .aRng - [1 inf] range for area of bbs
% .arRng - [0 inf] range for aspect ratio (width/height) of bbs
% .unique - [1] if true generate unique bbs
% .maxOverlap - [1] max overlap (intersection/union) between bbs
% .maxIter - [100] max iterations to go w/o changes before giving up
% .show - [0] if true show sample generated bbs
%
% OUTPUTS
% bbs - [nx4] array of randomly generated integer bbs
%
% EXAMPLE
% bbs=bbApply('random','n',50,'dims',[20 20],'arRng',[.5 .5],'show',1);
%
% See also bbApply
% get parameters
rng=[1 inf]; dfs={ 'n','REQ', 'dims','REQ', 'wRng',rng, 'hRng',rng, ...
'aRng',rng, 'arRng',[0 inf], 'unique',1, 'maxOverlap',1, ...
'maxIter',100, 'show',0 };
[n,dims,wRng,hRng,aRng,arRng,uniqueOnly,maxOverlap,maxIter,show] ...
= getPrmDflt(varargin,dfs,1);
if(length(hRng)==1), hRng=[hRng hRng]; end
if(length(wRng)==1), wRng=[wRng wRng]; end
if(length(dims)==3), d=5; else d=4; end
% generate random bbs satisfying constraints
bbs=zeros(0,d); ids=zeros(0,1); n1=min(n*10,1000);
M=max(dims)+1; M=M.^(0:d-1); iter=0; k=0;
tid=ticStatus('generating random bbs',1,2);
while( k<n && iter<maxIter )
ys=1+floor(rand(2,n1)*dims(1)); ys0=min(ys); ys1=max(ys); hs=ys1-ys0+1;
xs=1+floor(rand(2,n1)*dims(2)); xs0=min(xs); xs1=max(xs); ws=xs1-xs0+1;
if(d==5), ds=1+floor(rand(1,n1)*dims(3)); else ds=zeros(0,n1); end
if(arRng(1)==arRng(2)), ws=hs.*arRng(1); end
ars=ws./hs; ws=round(ws); xs1=xs0+ws-1; as=ws.*hs;
kp = ys0>0 & xs0>0 & ys1<=dims(1) & xs1<=dims(2) & ...
hs>=hRng(1) & hs<=hRng(2) & ws>=wRng(1) & ws<=wRng(2) & ...
as>=aRng(1) & as<=aRng(2) & ars>=arRng(1) & ars<=arRng(2);
bbs1=[xs0' ys0' ws' hs' ds']; bbs1=bbs1(kp,:);
k0=k; bbs=[bbs; bbs1]; k=size(bbs,1); %#ok<AGROW>
if( maxOverlap<1 && k ), bbs=bbs(1:k0,:);
for j=1:size(bbs1,1), bbs0=bbs; bb=bbs1(j,:);
if(d==5), bbs=bbs(bbs(:,5)==bb(5),:); end
if(isempty(bbs)), bbs=[bbs0; bb]; continue; end
ws1=min(bbs(:,1)+bbs(:,3),bb(1)+bb(3))-max(bbs(:,1),bb(1));
hs1=min(bbs(:,2)+bbs(:,4),bb(2)+bb(4))-max(bbs(:,2),bb(2));
o=max(0,ws1).*max(0,hs1); o=o./(bbs(:,3).*bbs(:,4)+bb(3).*bb(4)-o);
if(max(o)<=maxOverlap), bbs=[bbs0; bb]; else bbs=bbs0; end
end
elseif( uniqueOnly && k )
ids=[ids; sum(bbs1.*M(ones(1,size(bbs1,1)),:),2)]; %#ok<AGROW>
[ids,o]=sort(ids); bbs=bbs(o,:); kp=[ids(1:end-1)~=ids(2:end); true];
bbs=bbs(kp,:); ids=ids(kp,:);
end
k=size(bbs,1); if(k0==k), iter=iter+1; else iter=0; end
if(k>n), bbs=bbs(randSample(k,n),:); k=n; end;
tocStatus(tid,max(k/n,iter/maxIter));
end
if( k<n ), warning('only generated %i of %i bbs',k,n); n=k; end %#ok<WNTAG>
% optionally display a few bbs
if( show )
k=8; figure(show); im(zeros(dims)); cs=uniqueColors(1,k,0,0);
if(n>k), bbs1=bbs(randsample(n,k),:); else bbs1=bbs; end
bbs1(:,1:2)=bbs1(:,1:2)-.5;
for i=1:min(k,n), rectangle('Position',bbs1(i,:),...
'EdgeColor',cs(i,:),'LineStyle','--'); end
end
end
function bbs = frMask( M, bbw, bbh, thr )
% Convert weighted mask to bbs.
%
% Pixels in mask above given threshold (thr) indicate bb centers.
%
% USAGE
% bbs = bbApply('frMask',M,bbw,bbh,[thr])
%
% INPUTS
% M - mask
% bbw - bb target width
% bbh - bb target height
% thr - [0] mask threshold
%
% OUTPUTS
% bbs - bounding boxes
%
% EXAMPLE
% w=20; h=10; bbw=5; bbh=8; M=double(rand(h,w)); M(M<.95)=0;
% bbs=bbApply('frMask',M,bbw,bbh); M2=bbApply('toMask',bbs,w,h);
% sum(abs(M(:)-M2(:)))
%
% See also bbApply, bbApply>toMask
if(nargin<4), thr=0; end
ids=find(M>thr); ids=ids(:); h=size(M,1);
if(isempty(ids)), bbs=zeros(0,5); return; end
xs=floor((ids-1)/h); ys=ids-xs*h; xs=xs+1;
bbs=[xs-floor(bbw/2) ys-floor(bbh/2)];
bbs(:,3)=bbw; bbs(:,4)=bbh; bbs(:,5)=M(ids);
end
function M = toMask( bbs, w, h, fill, bgrd )
% Create weighted mask encoding bb centers (or extent).
%
% USAGE
% M = bbApply('toMask',bbs,w,h,[fill],[bgrd])
%
% INPUTS
% bbs - bounding boxes
% w - mask target width
% h - mask target height
% fill - [0] if 1 encodes extent of bbs
% bgrd - [0] default value for background pixels
%
% OUTPUTS
% M - hxw mask
%
% EXAMPLE
%
% See also bbApply, bbApply>frMask
if(nargin<4||isempty(fill)), fill=0; end
if(nargin<5||isempty(bgrd)), bgrd=0; end
if(size(bbs,2)==4), bbs(:,5)=1; end
M=zeros(h,w); B=true(h,w); n=size(bbs,1);
if( fill==0 )
p=floor(getCenter(bbs)); p=sub2ind([h w],p(:,2),p(:,1));
for i=1:n, M(p(i))=M(p(i))+bbs(i,5); end
if(bgrd~=0), B(p)=0; end
else
bbs=[intersect(round(bbs),[1 1 w h]) bbs(:,5)]; n=size(bbs,1);
x0=bbs(:,1); x1=x0+bbs(:,3)-1; y0=bbs(:,2); y1=y0+bbs(:,4)-1;
for i=1:n, y=y0(i):y1(i); x=x0(i):x1(i);
M(y,x)=M(y,x)+bbs(i,5); B(y,x)=0; end
end
if(bgrd~=0), M(B)=bgrd; end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
imwrite2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/images/imwrite2.m
| 5,086 |
utf_8
|
c98d66c2cddd9ec90beb9b1bbde31fe0
|
function I = imwrite2( I, mulFlag, imagei, path, ...
name, ext, nDigits, nSplits, spliti, varargin )
% Similar to imwrite, except follows a strict naming convention.
%
% Wrapper for imwrite that writes file to the filename:
% fName = [path name int2str2(i,nDigits) '.' ext];
% Using imwrite:
% imwrite( I, fName, writePrms )
% If I represents a stack of images, the ith image is written to:
% fNamei = [path name int2str2(i+imagei-1,nDigits) '.' ext];
% If I=[], then imwrite2 will attempt to read images from disk instead.
% If dir spec. by 'path' does not exist, imwrite2 attempts to create it.
%
% mulFlag controls how I is interpreted. If mulFlag==0, then I is
% intrepreted as a single image, otherwise I is interpreted as a stack of
% images, where I(:,:,...,j) represents the jth image (see fevalArrays for
% more info).
%
% If nSplits>1, writes/reads images into/from multiple directories. This is
% useful since certain OS handle very large directories (of say >20K
% images) rather poorly (I'm talking to you Bill). Thus, can take 100K
% images, and write into 5 separate dirs, then read them back in.
%
% USAGE
% I = imwrite2( I, mulFlag, imagei, path, ...
% [name], [ext], [nDigits], [nSplits], [spliti], [varargin] )
%
% INPUTS
% I - image or array or cell of images (if [] reads else writes)
% mulFlag - set to 1 if I represents a stack of images
% imagei - first image number
% path - directory where images are
% name - ['I'] base name of images
% ext - ['png'] extension of image
% nDigits - [5] number of digits for filename index
% nSplits - [1] number of dirs to break data into
% spliti - [0] first split (dir) number
% writePrms - [varargin] parameters to imwrite
%
% OUTPUTS
% I - image or images (read from disk if input I=[])
%
% EXAMPLE
% load images; I=images(:,:,1:10); clear IDXi IDXv t video videos images;
% imwrite2( I(:,:,1), 0, 0, 'rats/', 'rats', 'png', 5 ); % write 1
% imwrite2( I, 1, 0, 'rats/', 'rats', 'png', 5 ); % write 5
% I2 = imwrite2( [], 1, 0, 'rats/', 'rats', 'png', 5 ); % read 5
% I3 = fevalImages(@(x) x,{},'rats/','rats','png',0,4,5); % read 5
%
% EXAMPLE - multiple splits
% load images; I=images(:,:,1:10); clear IDXi IDXv t video videos images;
% imwrite2( I, 1, 0, 'rats', 'rats', 'png', 5, 2, 0 ); % write 10
% I2=imwrite2( [], 1, 0, 'rats', 'rats', 'png', 5, 2, 0 ); % read 10
%
% See also FEVALIMAGES, FEVALARRAYS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.30
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<5 || isempty(name) ); name='I'; end;
if( nargin<6 || isempty(ext) ); ext='png'; end;
if( nargin<7 || isempty(nDigits) ); nDigits=5; end;
if( nargin<8 || isempty(nSplits) ); nSplits=1; end;
if( nargin<9 || isempty(spliti) ); spliti=0; end;
n = size(I,3); if(isempty(I)); n=0; end
% multiple splits -- call imwrite2 recursively
if( nSplits>1 )
write2inp = [ {name, ext, nDigits, 1, 0} varargin ];
if(n>0); nSplits=min(n,nSplits); end;
for s=1:nSplits
pathS = [path int2str2(s-1+spliti,2)];
if( n>0 ) % write
nPerDir = ceil( n / nSplits );
ISplit = I(:,:,1:min(end,nPerDir));
imwrite2( ISplit, nPerDir>1, 0, pathS, write2inp{:} );
if( s~=nSplits ); I = I(:,:,(nPerDir+1):end); end
else % read
ISplit = imwrite2( [], 1, 0, pathS, write2inp{:} );
I = cat(3,I,ISplit);
end
end
return;
end
% if I is empty read from disk
if( n==0 )
I = fevalImages( @(x) x, {}, path, name, ext, imagei, [], nDigits );
return;
end
% Check if path exists (create if not) and add '/' at end if needed
if( ~isempty(path) )
if(~exist(path,'dir'))
warning( ['creating directory: ' path] ); %#ok<WNTAG>
mkdir( path );
end;
if( path(end)~='\' && path(end)~='/' ); path(end+1) = '/'; end
end
% Write images using one of the two subfunctions
params = varargin;
if( mulFlag )
imwrite2m( [], 'init', imagei, path, name, ext, nDigits, params );
if( ~iscell(I) )
fevalArrays( I, @imwrite2m, 'write' );
else
fevalArrays( I, @(x) imwrite2m(x{1},'write') );
end
else
if( ~iscell(I) )
imwrite2s( I, imagei, path, name, ext, nDigits, params );
else
imwrite2s( I{1}, imagei, path, name, ext, nDigits, params );
end;
end
function varargout = imwrite2m( I, type, varargin )
% helper for writing multiple images (passed to fevalArrays)
persistent imagei path name ext nDigits params
switch type
case 'init'
narginchk(8,8);
[nstart, path, name, ext, nDigits, params] = deal(varargin{:});
if(isempty(nstart)); imagei=0; else imagei=nstart; end
varargout = {[]};
case 'write'
narginchk(2,2);
imwrite2s( I, imagei, path, name, ext, nDigits, params );
imagei = imagei+1;
varargout = {[]};
end
function imwrite2s( I, imagei, path, name, ext, nDigits, params )
% helper for writing a single image
fullname = [path name int2str2(imagei,nDigits) '.' ext];
imwrite( I, fullname, params{:} );
|
github
|
garrickbrazil/SDS-RCNN-master
|
convnFast.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/images/convnFast.m
| 9,102 |
utf_8
|
03d05e74bb7ae2ecb0afd0ac115fda39
|
function C = convnFast( A, B, shape )
% Fast convolution, replacement for both conv2 and convn.
%
% See conv2 or convn for more information on convolution in general.
%
% This works as a replacement for both conv2 and convn. Basically,
% performs convolution in either the frequency or spatial domain, depending
% on which it thinks will be faster (see below). In general, if A is much
% bigger then B then spatial convolution will be faster, but if B is of
% similar size to A and both are fairly big (such as in the case of
% correlation), convolution as multiplication in the frequency domain will
% tend to be faster.
%
% The shape flag can take on 1 additional value which is 'smooth'. This
% flag is intended for use with smoothing kernels. The returned matrix C
% is the same size as A with boundary effects handled in a special manner.
% That is instead of A being zero padded before being convolved with B;
% near the boundaries a cropped version of the matrix B is used, and the
% results is scaled by the fraction of the weight found in the cropped
% version of B. In this case each dimension of B must be odd, and all
% elements of B must be positive. There are other restrictions on when
% this flag can be used, and in general it is only useful for smoothing
% kernels. For 2D filtering it does not have much overhead, for 3D it has
% more and for higher dimensions much much more.
%
% For optimal performance some timing constants must be set to choose
% between doing convolution in the spatial and frequency domains, for more
% info see timeConv below.
%
% USAGE
% C = convnFast( A, B, [shape] )
%
% INPUTS
% A - d dimensional input matrix
% B - d dimensional matrix to convolve with A
% shape - ['full'] 'valid', 'full', 'same', or 'smooth'
%
% OUTPUTS
% C - result of convolution
%
% EXAMPLE
%
% See also CONV2, CONVN
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(shape)); shape='full'; end
if( ~any(strcmp(shape,{'same', 'valid', 'full', 'smooth'})) )
error( 'convnFast: unknown shape flag' ); end
shapeorig = shape;
smoothFlag = (strcmp(shape,'smooth'));
if( smoothFlag ); shape = 'same'; end;
% get dimensions of A and B
ndA = ndims(A); ndB = ndims(B); nd = max(ndA,ndB);
sizA = size(A); sizB = size(B);
if (ndA>ndB); sizB = [sizB ones(1,ndA-ndB)]; end
if (ndA<ndB); sizA = [sizA ones(1,ndB-ndA)]; end
% ERROR CHECK if smoothflag
if( smoothFlag )
if( ~all( mod(sizB,2)==1 ) )
error('If flag==''smooth'' then must have odd sized mask');
end;
if( ~all( B>0 ) )
error('If flag==''smooth'' then mask must have >0 values.');
end;
if( any( (sizB-1)/2>sizA ) )
error('B is more then twice as big as A, cannot use flag==''smooth''');
end;
end
% OPTIMIZATION for 3D conv when B is actually 2D - calls (spatial) conv2
% repeatedly on 2D slices of A. Note that may need to rearange A and B
% first and use recursion. The benefits carry over to convnBound
% (which is faster for 2D arrays).
if( ndA==3 && ndB==3 && (sizB(1)==1 || sizB(2)==1) )
if (sizB(1)==1)
A = permute( A, [2 3 1]); B = permute( B, [2 3 1]);
C = convnFast( A, B, shapeorig );
C = permute( C, [3 1 2] );
elseif (sizB(2)==1)
A = permute( A, [3 1 2]); B = permute( B, [3 1 2]);
C = convnFast( A, B, shapeorig );
C = permute( C, [2 3 1] );
end
return;
elseif( ndA==3 && ndB==2 )
C1 = conv2( A(:,:,1), B, shape );
C = zeros( [size(C1), sizA(3)] ); C(:,:,1) = C1;
for i=2:sizA(3); C(:,:,i) = conv2( A(:,:,i), B, shape ); end
if (smoothFlag)
for i=1:sizA(3)
C(:,:,i) = convnBound(A(:,:,i),B,C(:,:,i),sizA(1:2),sizB(1:2));
end
end
return;
end
% get predicted time of convolution in frequency and spatial domain
% constants taken from timeConv
sizfft = 2.^ceil(real(log2(sizA+sizB-1))); psizfft=prod(sizfft);
frequenPt = 3 * 1e-7 * psizfft * log(psizfft);
if (nd==2)
spatialPt = 5e-9 * sizA(1) * sizA(2) * sizB(1) * sizB(2);
else
spatialPt = 5e-8 * prod(sizA) * prod(sizB);
end
% perform convolution
if ( spatialPt < frequenPt )
if (nd==2)
C = conv2( A, B, shape );
else
C = convn( A, B, shape );
end
else
C = convnFreq( A, B, sizA, sizB, shape );
end;
% now correct boundary effects (if shape=='smooth')
if( ~smoothFlag ); return; end;
C = convnBound( A, B, C, sizA, sizB );
function C = convnBound( A, B, C, sizA, sizB )
% calculate boundary values for C in spatial domain
nd = length(sizA);
radii = (sizB-1)/2;
% flip B appropriately (conv flips B)
for d=1:nd; B = flipdim(B,d); end
% accelerated case for 1D mask B
if( nd==2 && sizB(1)==1 )
sumB=sum(B(:)); r=radii(2); O=ones(1,sizA(1));
for i=1:r
Ai=A(:,1:r+i); Bi=B(r+2-i:end);
C(:,i)=sum(Ai.*Bi(O,:),2)/sum(Bi)*sumB;
Ai=A(:,end+1-r-i:end); Bi=B(1:(end-r+i-1));
C(:,end-i+1)=sum(Ai.*Bi(O,:),2)/sum(Bi)*sumB;
end; return;
elseif( nd==2 && sizB(2)==1 )
sumB=sum(B(:)); r=radii(1); O=ones(1,sizA(2));
for i=1:r
Ai=A(1:r+i,:); Bi=B(r+2-i:end);
C(i,:)=sum(Ai.*Bi(:,O),1)/sum(Bi)*sumB;
Ai=A(end+1-r-i:end,:); Bi=B(1:(end-r+i-1));
C(end-i+1,:)=sum(Ai.*Bi(:,O),1)/sum(Bi)*sumB;
end; return;
end
% get location that need to be updated
inds = {':'}; inds = inds(:,ones(1,nd));
Dind = zeros( sizA );
for d=1:nd
inds1 = inds; inds1{ d } = 1:radii(d);
inds2 = inds; inds2{ d } = sizA(d)-radii(d)+1:sizA(d);
Dind(inds1{:}) = 1; Dind(inds2{:}) = 1;
end
Dind = find( Dind );
Dndx = ind2sub2( sizA, Dind );
nlocs = length(Dind);
% get cuboid dimensions for all the boundary regions
sizeArep = repmat( sizA, [nlocs,1] );
radiiRep = repmat( radii, [nlocs,1] );
Astarts = max(1,Dndx-radiiRep);
Aends = min( sizeArep, Dndx+radiiRep);
Bstarts = Astarts + (1-Dndx+radiiRep);
Bends = Bstarts + (Aends-Astarts);
% now update these locations
vs = zeros( 1, nlocs );
if( nd==2 )
for i=1:nlocs % accelerated for 2D arrays
Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2) );
Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2) );
v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));
end
elseif( nd==3 ) % accelerated for 3D arrays
for i=1:nlocs
Apart = A( Astarts(i,1):Aends(i,1), Astarts(i,2):Aends(i,2), ...
Astarts(i,3):Aends(i,3) );
Bpart = B( Bstarts(i,1):Bends(i,1), Bstarts(i,2):Bends(i,2), ...
Bstarts(i,3):Bends(i,3) );
za = sum(sum(sum(Apart.*Bpart))); zb=sum(sum(sum(Bpart)));
vs(1,i) = za./zb;
end
else % general case [slow]
extract=cell(1,nd);
for i=1:nlocs
for d=1:nd; extract{d} = Astarts(i,d):Aends(i,d); end
Apart = A( extract{:} );
for d=1:nd; extract{d} = Bstarts(i,d):Bends(i,d); end
Bpart = B( extract{:} );
v = (Apart.*Bpart); vs(i) = sum(v(:)) ./ sum(Bpart(:));
end
end
C( Dind ) = vs * sum(B(:));
function C = convnFreq( A, B, sizA, sizB, shape )
% Convolution as multiplication in the frequency domain
siz = sizA + sizB - 1;
% calculate correlation in frequency domain
Fa = fftn(A,siz);
Fb = fftn(B,siz);
C = ifftn(Fa .* Fb);
% make sure output is real if inputs were both real
if(isreal(A) && isreal(B)); C = real(C); end
% crop to size
if(strcmp(shape,'valid'))
C = arrayToDims( C, max(0,sizA-sizB+1 ) );
elseif(strcmp(shape,'same'))
C = arrayToDims( C, sizA );
elseif(~strcmp(shape,'full'))
error('unknown shape');
end
function K = timeConv() %#ok<DEFNU>
% Function used to calculate constants for prediction of convolution in the
% frequency and spatial domains. Method taken from normxcorr2.m
% May need to reset K's if placing this on a new machine, however, their
% ratio should be about the same..
mintime = 4;
switch 3
case 1 % conv2 [[empirically K = 5e-9]]
% convolution time = K*prod(size(a))*prod(size(b))
siza = 30; sizb = 200;
a = ones(siza); b = ones(sizb);
t1 = cputime; t2 = t1; k = 0;
while (t2-t1)<mintime;
disc = conv2(a,b); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1)/k/siza^2/sizb^2;
case 2 % convn [[empirically K = 5e-8]]
% convolution time = K*prod(size(a))*prod(size(b))
siza = [10 10 10]; sizb = [30 30 10];
a = ones(siza); b = ones(sizb);
t1 = cputime; t2 = t1; k = 0;
while (t2-t1)<mintime;
disc = convn(a,b); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1)/k/prod(siza)/prod(sizb);
case 3 % fft (one dimensional) [[empirically K = 1e-7]]
% fft time = K * n log(n) [if n is power of 2]
% Works fastest for powers of 2. (so always zero pad until have
% size of power of 2?). 2 dimensional fft has to apply single
% dimensional fft to each column, and then signle dimensional fft
% to each resulting row. time = K * (mn)log(mn). Likewise for
% highter dimensions. convnFreq requires 3 such ffts.
n = 2^nextpow2(2^15);
vec = complex(rand(n,1),rand(n,1));
t1 = cputime; t2 = t1; k = 0;
while (t2-t1) < mintime;
disc = fft(vec); k = k + 1; t2 = cputime; %#ok<NASGU>
end
K = (t2-t1) / k / n / log(n);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
imMlGauss.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/images/imMlGauss.m
| 5,674 |
utf_8
|
56ead1b25fbe356f7912993d46468d02
|
function varargout = imMlGauss( G, symmFlag, show )
% Calculates max likelihood params of Gaussian that gave rise to image G.
%
% Suppose G contains an image of a gaussian distribution. One way to
% recover the parameters of the gaussian is to threshold the image, and
% then estimate the mean/covariance based on the coordinates of the
% thresholded points. A better method is to do no thresholding and instead
% use all the coordinates, weighted by their value. This function does the
% latter, except in a very efficient manner since all computations are done
% in parallel over the entire image.
%
% This function works over 2D or 3D images. It makes most sense when G in
% fact contains an image of a single gaussian, but a result will be
% returned regardless. All operations are performed on abs(G) in case it
% contains negative or complex values.
%
% symmFlag is an optional flag that if set to 1 then imMlGauss recovers
% the maximum likelihood symmetric gaussian. That is the variance in each
% direction is equal, and all covariance terms are 0. If symmFlag is set
% to 2 and G is 3D, imMlGauss recovers the ML guassian with equal
% variance in the 1st 2 dimensions (row and col) and all covariance terms
% equal to 0, but a possibly different variance in the 3rd (z or t)
% dimension.
%
% USAGE
% varargout = imMlGauss( G, [symmFlag], [show] )
%
% INPUTS
% G - image of a gaussian (weighted pixels)
% symmFlag - [0] see above
% show - [0] figure to use for optional display
%
% OUTPUTS
% mu - 2 or 3 element vector specifying the mean [row,col,z]
% C - 2x2 or 3x3 covariance matrix [row,col,z]
% GR - image of the recovered gaussian (faster if omitted)
% logl - log likelihood of G given recov. gaussian (faster if omitted)
%
% EXAMPLE - 2D
% R = rotationMatrix( pi/6 ); C=R'*[10^2 0; 0 20^2]*R;
% G = filterGauss( [200, 300], [150,100], C, 0 );
% [mu,C,GR,logl] = imMlGauss( G, 0, 1 );
% mask = maskEllipse( size(G,1), size(G,2), mu, C );
% figure(2); im(mask)
%
% EXAMPLE - 3D
% R = rotationMatrix( [1,1,0], pi/4 );
% C = R'*[5^2 0 0; 0 2^2 0; 0 0 4^2]*R;
% G = filterGauss( [50,50,50], [25,25,25], C, 0 );
% [mu,C,GR,logl] = imMlGauss( G, 0, 1 );
%
% See also GAUSS2ELLIPSE, PLOTGAUSSELLIPSES, MASKELLIPSE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<2 || isempty(symmFlag) ); symmFlag=0; end;
if( nargin<3 || isempty(show) ); show=0; end;
varargout = cell(1,max(nargout,2));
nd = ndims(G); G = abs(G);
if( nd==2 )
[varargout{:}] = imMlGauss2D( G, symmFlag, show );
elseif( nd==3 )
[varargout{:}] = imMlGauss3D( G, symmFlag, show );
else
error( 'Unsupported dimension for G. G must be 2D or 3D.' );
end
function [mu,C,GR,logl] = imMlGauss2D( G, symmFlag, show )
% to be used throughout calculations
[ gridCols, gridRows ] = meshgrid( 1:size(G,2), 1:size(G,1) );
sumG = sum(G(:)); if(sumG==0); sumG=1; end;
% recover mean
muCol = (gridCols .* G); muCol = sum( muCol(:) ) / sumG;
muRow = (gridRows .* G); muRow = sum( muRow(:) ) / sumG;
mu = [muRow, muCol];
% recover sigma
distCols = (gridCols - muCol);
distRows = (gridRows - muRow);
if( symmFlag==0 )
Ccc = (distCols .^ 2) .* G; Ccc = sum(Ccc(:)) / sumG;
Crr = (distRows .^ 2) .* G; Crr = sum(Crr(:)) / sumG;
Crc = (distCols .* distRows) .* G; Crc = sum(Crc(:)) / sumG;
C = [Crr Crc; Crc Ccc];
elseif( symmFlag==1 )
sigSq = (distCols.^2 + distRows.^2) .* G;
sigSq = 1/2 * sum(sigSq(:)) / sumG;
C = sigSq*eye(2);
else
error(['Illegal value for symmFlag: ' num2str(symmFlag)]);
end
% get the log likelihood of the data
if (nargout>2)
GR = filterGauss( size(G), mu, C );
probs = GR; probs( probs<realmin ) = realmin;
logl = G .* log( probs );
logl = sum( logl(:) );
end
% plot ellipses
if (show)
figure(show); im(G);
hold('on'); plotGaussEllipses( mu, C, 2 ); hold('off');
end
function [mu,C,GR,logl] = imMlGauss3D( G, symmFlag, show )
% to be used throughout calculations
[gridCols,gridRows,gridZs]=meshgrid(1:size(G,2),1:size(G,1),1:size(G,3));
sumG = sum(G(:));
% recover mean
muCol = (gridCols .* G); muCol = sum( muCol(:) ) / sumG;
muRow = (gridRows .* G); muRow = sum( muRow(:) ) / sumG;
muZ = (gridZs .* G); muZ = sum( muZ(:) ) / sumG;
mu = [muRow, muCol, muZ];
% recover C
distCols = (gridCols - muCol);
distRows = (gridRows - muRow);
distZs = (gridZs - muZ);
if( symmFlag==0 )
distColsG = distCols .* G; distRowsG = distRows .* G;
Ccc = distCols .* distColsG; Ccc = sum(Ccc(:));
Crc = distRows .* distColsG; Crc = sum(Crc(:));
Czc = distZs .* distColsG; Czc = sum(Czc(:));
Crr = distRows .* distRowsG; Crr = sum(Crr(:));
Czr = distZs .* distRowsG; Czr = sum(Czr(:));
Czz = distZs .* distZs .* G; Czz = sum(Czz(:));
C = [Crr Crc Czr; Crc Ccc Czc; Czr Czc Czz] / sumG;
elseif( symmFlag==1 )
sigSq = (distCols.^2 + distRows.^2 + distZs .^ 2) .* G;
sigSq = 1/3 * sum(sigSq(:));
C = [sigSq 0 0; 0 sigSq 0; 0 0 sigSq] / sumG;
elseif( symmFlag==2 )
sigSq = (distCols.^2 + distRows.^2) .* G; sigSq = 1/2 * sum(sigSq(:));
tauSq = (distZs .^ 2) .* G; tauSq = sum(tauSq(:));
C = [sigSq 0 0; 0 sigSq 0; 0 0 tauSq] / sumG;
else
error(['Illegal value for symmFlag: ' num2str(symmFlag)])
end
% get the log likelihood of the data
if( nargout>2 || (show) )
GR = filterGauss( size(G), mu, C );
probs = GR; probs( probs<realmin ) = realmin;
logl = G .* log( probs );
logl = sum( logl(:) );
end
% plot G and GR
if( show )
figure(show); montage2(G);
figure(show+1); montage2(GR);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
montage2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/images/montage2.m
| 7,484 |
utf_8
|
828f57d7b1f67d36eeb6056f06568ebf
|
function varargout = montage2( IS, prm )
% Used to display collections of images and videos.
%
% Improved version of montage, with more control over display.
% NOTE: Can convert between MxNxT and MxNx3xT image stack via:
% I = repmat( I, [1,1,1,3] ); I = permute(I, [1,2,4,3] );
%
% USAGE
% varargout = montage2( IS, [prm] )
%
% INPUTS
% IS - MxNxTxR or MxNxCxTxR, where C==1 or C==3, and R may be 1
% or cell vector of MxNxT or MxNxCxT matrices
% prm
% .showLines - [1] whether to show lines separating the various frames
% .extraInfo - [0] if 1 then a colorbar is shown as well as impixelinfo
% .cLim - [] cLim = [clow chigh] optional scaling of data
% .mm - [] #images/col per montage
% .nn - [] #images/row per montage
% .labels - [] cell array of labels (strings) (T if R==1 else R)
% .perRow - [0] only if R>1 and not cell, alternative displays method
% .hasChn - [0] if true assumes IS is MxNxCxTxR else MxNxTxR
% .padAmt - [0] only if perRow, amount to pad when in row mode
% .padEl - [] pad element, defaults to min value in IS
%
% OUTPUTS
% h - image handle
% m - #images/col
% nn - #images/row
%
% EXAMPLE - [3D] show a montage of images
% load( 'images.mat' ); clf; montage2( images );
%
% EXAMPLE - [3D] show a montage of images with labels
% load( 'images.mat' );
% for i=1:50; labels{i}=['I-' int2str2(i,2)]; end
% prm = struct('extraInfo',1,'perRow',0,'labels',{labels});
% clf; montage2( images(:,:,1:50), prm );
%
% EXAMPLE - [3D] show a montage of images with color boundaries
% load( 'images.mat' );
% I3 = repmat(permute(images,[1 2 4 3]),[1,1,3,1]); % add color chnls
% prm = struct('padAmt',4,'padEl',[50 180 50],'hasChn',1,'showLines',0);
% clf; montage2( I3(:,:,:,1:48), prm )
%
% EXAMPLE - [4D] show a montage of several groups of images
% for i=1:25; labels{i}=['V-' int2str2(i,2)]; end
% prm = struct('labels',{labels});
% load( 'images.mat' ); clf; montage2( videos(:,:,:,1:25), prm );
%
% EXAMPLE - [4D] show using 'row' format
% load( 'images.mat' );
% prm = struct('perRow',1, 'padAmt',6, 'padEl',255 );
% figure(1); clf; montage2( videos(:,:,:,1:10), prm );
%
% See also MONTAGE, PLAYMOVIE, FILMSTRIP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<2 ); prm=struct(); end
varargout = cell(1,nargout);
%%% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[],...
'labels',[], 'perRow',false, 'padAmt',0, 'padEl',[], 'hasChn',false };
prm = getPrmDflt( prm, dfs );
extraInfo=prm.extraInfo; labels=prm.labels; perRow=prm.perRow;
hasChn=prm.hasChn;
%%% If IS is not a cell convert to MxNxCxTxR array
if( iscell(IS) && numel(IS)==1 ); IS=IS{1}; end;
if( ~iscell(IS) && ~ismatrix(IS) )
siz=size(IS);
if( ~hasChn );
IS=reshape(IS,[siz(1:2),1,siz(3:end)]);
prm.hasChn = true;
end;
if(ndims(IS)>5); error('montage2: input too large'); end;
end
if( ~iscell(IS) && size(IS,5)==1 ) %%% special case call subMontage once
[varargout{:}] = subMontage(IS,prm);
title(inputname(1));
elseif( perRow ) %%% display each montage in row format
if(iscell(IS)); error('montage2: IS cannot be a cell if perRow'); end;
siz = size(IS);
IS=reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5));
if( nargout ); varargout{1}=IS; end
prm.perRow = false; prm.hasChn=true;
[varargout{2:end}] = subMontage( IS, prm );
title(inputname(1));
else %%% display each montage using subMontage
% convert to cell array
if( iscell(IS) )
nMontages = numel(IS);
else
nMontages = size(IS,5);
IS = squeeze(mat2cell2( IS, [1 1 1 1 nMontages] ));
end
% draw each montage
clf;
nn = ceil( sqrt(nMontages) ); mm = ceil(nMontages/nn);
for i=1:nMontages
subplot(mm,nn,i);
prmSub=prm; prmSub.extraInfo=0; prmSub.labels=[];
if( ~isempty(IS{i}) )
subMontage( IS{i}, prmSub );
else
set(gca,'XTick',[]); set(gca,'YTick',[]);
end
if(~isempty(labels)); title(labels{i}); end
end
if( extraInfo ); impixelinfo; end;
end
function varargout = subMontage( IS, prm )
% this function is a generalized version of Matlab's montage.m
% get parameters (set defaults)
dfs = {'showLines',1, 'extraInfo',0, 'cLim',[], 'mm',[], 'nn',[], ...
'labels',[], 'perRow',false, 'hasChn',false, 'padAmt',0, 'padEl',[] };
prm = getPrmDflt( prm, dfs );
showLines=prm.showLines; extraInfo=prm.extraInfo; cLim=prm.cLim;
mm=prm.mm; nn=prm.nn; labels=prm.labels; hasChn=prm.hasChn;
padAmt=prm.padAmt; padEl=prm.padEl;
if( prm.perRow ); mm=1; end;
% get/test image format info and parameters
if( hasChn )
if( ndims(IS)>4 || ~any(size(IS,3)==[1 3]) )
error('montage2: unsupported dimension of IS'); end
else
if( ndims(IS)>3 );
error('montage2: unsupported dimension of IS'); end
IS = permute(IS, [1 2 4 3] );
end
siz = size(IS); nCh=size(IS,3); nIm = size(IS,4); sizPad=siz+padAmt;
if( ~isempty(labels) && nIm~=length(labels) )
error('montage2: incorrect number of labels');
end
% set up the padEl correctly (must have same type / nCh as IS)
if(isempty(padEl))
if(isempty(cLim)); padEl=min(IS(:)); else padEl=cLim(1); end; end
if(length(padEl)==1); padEl=repmat(padEl,[1 nCh]); end;
if(length(padEl)~=nCh); error( 'invalid padEl' ); end;
padEl = feval( class(IS), padEl );
padEl = reshape( padEl, 1, 1, [] );
padAmt = floor(padAmt/2 + .5)*2;
% get layout of images (mm=#images/row, nn=#images/col)
if( isempty(mm) || isempty(nn))
if( isempty(mm) && isempty(nn))
nn = min( ceil(sqrt(sizPad(1)*nIm/sizPad(2))), nIm );
mm = ceil( nIm/nn );
elseif( isempty(mm) )
nn = min( nn, nIm );
mm = ceil(nIm/nn);
else
mm = min( mm, nIm );
nn = ceil(nIm/mm);
end
% often can shrink dimension further
while((mm-1)*nn>=nIm); mm=mm-1; end;
while((nn-1)*mm>=nIm); nn=nn-1; end;
end
% Calculate I (M*mm x N*nn size image)
I = repmat(padEl, [mm*sizPad(1), nn*sizPad(2), 1]);
rows = 1:siz(1); cols = 1:siz(2);
for k=1:nIm
rowsK = rows + floor((k-1)/nn)*sizPad(1)+padAmt/2;
colsK = cols + mod(k-1,nn)*sizPad(2)+padAmt/2;
I(rowsK,colsK,:) = IS(:,:,:,k);
end
% display I
if( ~isempty(cLim)); h=imagesc(I,cLim); else h=imagesc(I); end
colormap(gray); axis('image');
if( extraInfo )
colorbar; impixelinfo;
else
set(gca,'Visible','off')
end
% draw lines separating frames
if( showLines )
montageWd = nn * sizPad(2) + .5;
montageHt = mm * sizPad(1) + .5;
for i=1:mm-1
ht = i*sizPad(1) +.5; line([.5,montageWd],[ht,ht]);
end
for i=1:nn-1
wd = i*sizPad(2) +.5; line([wd,wd],[.5,montageHt]);
end
end
% plot text labels
textalign = { 'VerticalAlignment','bottom','HorizontalAlignment','left'};
if( ~isempty(labels) )
count=1;
for i=1:mm;
for j=1:nn
if( count<=nIm )
rStr = i*sizPad(1)-padAmt/2;
cStr =(j-1+.1)*sizPad(2)+padAmt/2;
text(cStr,rStr,labels{count},'color','r',textalign{:});
count = count+1;
end
end
end
end
% cross out unused frames
[nns,mms] = ind2sub( [nn,mm], nIm+1 );
for i=mms-1:mm-1
for j=nns-1:nn-1,
rStr = i*sizPad(1)+.5+padAmt/2; rs = [rStr,rStr+siz(1)];
cStr = j*sizPad(2)+.5+padAmt/2; cs = [cStr,cStr+siz(2)];
line( cs, rs ); line( fliplr(cs), rs );
end
end
% optional output
if( nargout>0 ); varargout={h,mm,nn}; end
|
github
|
garrickbrazil/SDS-RCNN-master
|
jitterImage.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/images/jitterImage.m
| 5,252 |
utf_8
|
3310f8412af00fd504c6f94b8c48992c
|
function IJ = jitterImage( I, varargin )
% Creates multiple, slightly jittered versions of an image.
%
% Takes an image I, and generates a number of images that are copies of the
% original image with slight translation, rotation and scaling applied. If
% the input image is actually an MxNxK stack of images then applies op to
% each image. Rotations and translations are specified by giving a range
% and a max value for each. For example, if mPhi=10 and nPhi=5, then the
% actual rotations applied are linspace(-mPhi,mPhi,nPhi)=[-10 -5 0 5 10].
% Likewise if mTrn=3 and nTrn=3 then the translations are [-3 0 3]. Each
% tran is applied in the x direction as well as the y direction. Each
% combination of rotation, tran in x, tran in y and scale is used (for
% example phi=5, transx=-3, transy=0), so the total number of images
% generated is R=nTrn*nTrn*nPhi*nScl. Finally, jsiz controls the size of
% the cropped images. If jsiz gives a size that's sufficiently smaller than
% I then all data in the the final set will come from I. Otherwise, I must
% be padded first (by calling padarray with the 'replicate' option).
%
% USAGE
% function IJ = jitterImage( I, varargin )
%
% INPUTS
% I - image (MxN) or set of K images (MxNxK)
% varargin - additional params (struct or name/value pairs)
% .maxn - [inf] maximum jitters to generate (prior to flip)
% .nPhi - [0] number of rotations
% .mPhi - [0] max value for rotation
% .nTrn - [0] number of translations
% .mTrn - [0] max value for translation
% .flip - [0] if true then also adds reflection of each image
% .jsiz - [] Final size of each image in IJ
% .scls - [1 1] nScl x 2 array of vert/horiz scalings
% .method - ['linear'] interpolation method for imtransform2
% .hasChn - [0] if true I is MxNxC or MxNxCxK
%
% OUTPUTS
% IJ - MxNxKxR or MxNxCxKxR set of images, R=(nTrn^2*nPhi*nScl)
%
% EXAMPLE
% load trees; I=imresize(ind2gray(X,map),[41 41]); clear X caption map
% % creates 10 (of 7^2*2) images of slight trans
% IJ = jitterImage(I,'nTrn',7,'mTrn',3,'maxn',10); montage2(IJ)
% % creates 5 images of slight rotations w reflection
% IJ = jitterImage(I,'nPhi',5,'mPhi',25,'flip',1); montage2(IJ)
% % creates 45 images of both rot and slight trans
% IJ = jitterImage(I,'nPhi',5,'mPhi',10,'nTrn',3,'mTrn',2); montage2(IJ)
% % additionally create multiple scaled versions
% IJ = jitterImage(I,'scls',[1 1; 2 1; 1 2; 2 2]); montage2(IJ)
% % example on color image (5 images of slight rotations)
% I=imResample(imread('peppers.png'),[100,100]);
% IJ=jitterImage(I,'nPhi',5,'mPhi',25,'hasChn',1);
% montage2(uint8(IJ),{'hasChn',1})
%
% See also imtransform2
%
% Piotr's Computer Vision Matlab Toolbox Version 2.65
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get additional parameters
siz=size(I);
dfs={'maxn',inf, 'nPhi',0, 'mPhi',0, 'nTrn',0, 'mTrn',0, 'flip',0, ...
'jsiz',siz(1:2), 'scls',[1 1], 'method','linear', 'hasChn',0};
[maxn,nPhi,mPhi,nTrn,mTrn,flip,jsiz,scls,method,hasChn] = ...
getPrmDflt(varargin,dfs,1);
if(nPhi<1), mPhi=0; nPhi=1; end; if(nTrn<1), mTrn=0; nTrn=1; end
% I must be big enough to support given ops so grow I if necessary
trn=linspace(-mTrn,mTrn,nTrn); [dX,dY]=meshgrid(trn,trn);
dY=dY(:)'; dX=dX(:)'; phis=linspace(-mPhi,mPhi,nPhi)/180*pi;
siz1=jsiz+2*max(dX); if(nPhi>1), siz1=sqrt(2)*siz1+1; end
siz1=[siz1(1)*max(scls(:,1)) siz1(2)*max(scls(:,2))];
pad=(siz1-siz(1:2))/2; pad=max([ceil(pad) 0],0);
if(any(pad>0)), I=padarray(I,pad,'replicate','both'); end
% jitter each image
nScl=size(scls,1); nTrn=length(dX); nPhi=length(phis);
nOps=min(maxn,nTrn*nPhi*nScl); if(flip), nOps=nOps*2; end
if(hasChn), nd=3; jsiz=[jsiz siz(3)]; else nd=2; end
n=size(I,nd+1); IJ=zeros([jsiz nOps n],class(I));
is=repmat({':'},1,nd); prm={method,maxn,jsiz,phis,dX,dY,scls,flip};
for i=1:n, IJ(is{:},:,i)=jitterImage1(I(is{:},i),prm{:}); end
end
function IJ = jitterImage1( I,method,maxn,jsiz,phis,dX,dY,scls,flip )
% generate list of transformations (HS)
nScl=size(scls,1); nTrn=length(dX); nPhi=length(phis);
nOps=nTrn*nPhi*nScl; HS=zeros(3,3,nOps); k=0;
for s=1:nScl, S=[scls(s,1) 0; 0 scls(s,2)];
for p=1:nPhi, R=rotationMatrix(phis(p));
for t=1:nTrn, k=k+1; HS(:,:,k)=[S*R [dX(t); dY(t)]; 0 0 1]; end
end
end
% apply each transformation HS(:,:,i) to image I
if(nOps>maxn), HS=HS(:,:,randSample(nOps,maxn)); nOps=maxn; end
siz=size(I); nd=ndims(I); nCh=size(I,3);
I1=I; p=(siz-jsiz)/2; IJ=zeros([jsiz nOps],class(I));
for i=1:nOps, H=HS(:,:,i); d=H(1:2,3)';
if( all(all(H(1:2,1:2)==eye(2))) && all(mod(d,1)==0) )
% handle transformation that's just an integer translation
s=max(1-d,1); e=min(siz(1:2)-d,siz(1:2)); s1=2-min(1-d,1); e1=e-s+s1;
I1(s1(1):e1(1),s1(2):e1(2),:) = I(s(1):e(1),s(2):e(2),:);
else % handle general transformations
for j=1:nCh, I1(:,:,j)=imtransform2(I(:,:,j),H,'method',method); end
end
% crop and store result
I2 = I1(p(1)+1:end-p(1),p(2)+1:end-p(2),:);
if(nd==2), IJ(:,:,i)=I2; else IJ(:,:,:,i)=I2; end
end
% finally flip each resulting image
if(flip), IJ=cat(nd+1,IJ,IJ(:,end:-1:1,:,:)); end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
movieToImages.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/images/movieToImages.m
| 889 |
utf_8
|
28c71798642af276951ee27e2d332540
|
function I = movieToImages( M )
% Creates a stack of images from a matlab movie M.
%
% Repeatedly calls frame2im. Useful for playback with playMovie.
%
% USAGE
% I = movieToImages( M )
%
% INPUTS
% M - a matlab movie
%
% OUTPUTS
% I - MxNxT array (of images)
%
% EXAMPLE
% load( 'images.mat' ); [X,map]=gray2ind(video(:,:,1));
% M = fevalArrays( video, @(x) im2frame(gray2ind(x),map) );
% I = movieToImages(M); playMovie(I);
%
% See also PLAYMOVIE
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
I = fevalArrays( M, @frame2Ii );
function I = frame2Ii( F )
[I,map] = frame2im( F );
if( isempty(map) )
if( size(I,3)==3 )
classname = class( I );
I = sum(I,3)/3;
I = feval( classname, I );
end
else
I = ind2gray( I, map );
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
toolboxUpdateHeader.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/toolboxUpdateHeader.m
| 2,255 |
utf_8
|
ade06ae438e20ad8faa66e41267915f3
|
function toolboxUpdateHeader
% Update the headers of all the files.
%
% USAGE
% toolboxUpdateHeader
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.50
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
header={
'Piotr''s Computer Vision Matlab Toolbox Version 3.50'; ...
'Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]'; ...
'Licensed under the Simplified BSD License [see external/bsd.txt]'};
root=fileparts(fileparts(mfilename('fullpath')));
ds=dir(root); ds=ds([ds.isdir]); ds={ds.name};
ds=ds(3:end); ds=setdiff(ds,{'.git','doc'});
subds = { '/', '/private/' };
exts = {'m','c','cpp','h','hpp'};
omit = {'Contents.m','fibheap.h','fibheap.cpp'};
for i=1:length(ds)
for j=1:length(subds)
for k=1:length(exts)
d=[root '/' ds{i} subds{j}];
if(k==1), comment='%'; else comment='*'; end
fs=dir([d '*.' exts{k}]); fs={fs.name}; fs=setdiff(fs,omit);
n=length(fs); for f=1:n, fs{f}=[d fs{f}]; end
for f=1:n, toolboxUpdateHeader1(fs{f},header,comment); end
end
end
end
end
function toolboxUpdateHeader1( fName, header, comment )
% set appropriate comment symbol in header
m=length(header); for i=1:m, header{i}=[comment ' ' header{i}]; end
% read in file and find header
disp(fName); lines=readFile(fName);
loc = find(not(cellfun('isempty',strfind(lines,header{1}(1:40)))));
if(isempty(loc)), error('NO HEADER: %s\n',fName); end; loc=loc(1);
% check that header is properly formed, return if up to date
for i=1:m; assert(isequal(lines{loc+i-1}(1:10),header{i}(1:10))); end
if(~any(strfind(lines{loc},'NEW'))); return; end
% update copyright year and overwrite rest of header
lines{loc+1}(13:16)=header{2}(13:16);
for i=[1 3:m]; lines{loc+i-1}=header{i}; end
writeFile( fName, lines );
end
function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
n=n+1; lines{n}=fgetl(fid);
if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end
function writeFile( fName, lines )
fid = fopen( fName, 'w' );
for i=1:length(lines); fprintf( fid, '%s\n', lines{i} ); end
fclose(fid);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
toolboxGenDoc.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/toolboxGenDoc.m
| 3,639 |
utf_8
|
4c21fb34fa9b6002a1a98a28ab40c270
|
function toolboxGenDoc
% Generate documentation, must run from dir toolbox.
%
% 1) Make sure to update and run toolboxUpdateHeader.m
% 2) Update history.txt appropriately, including w current version
% 3) Update overview.html file with the version/date/link to zip:
% edit external/m2html/templates/frame-piotr/overview.html
%
% USAGE
% toolboxGenDoc
%
% INPUTS
%
% OUTPUTS
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.40
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% Requires external/m2html to be in path.
cd(fileparts(mfilename('fullpath'))); cd('../');
addpath([pwd '/external/m2html']);
% delete temporary files that should not be part of release
fs={'pngreadc','pngwritec','rjpg8c','wjpg8c','png'};
for i=1:length(fs), delete(['videos/private/' fs{i} '.*']); end
delete('detector/models/*Dets.txt');
% delete old doc and run m2html
if(exist('doc/','dir')), rmdir('doc/','s'); end
dirs={'channels','classify','detector',...
'images','filters','matlab','videos'};
m2html('mfiles',dirs,'htmldir','doc','recursive','on','source','off',...
'template','frame-piotr','index','menu','global','on');
% copy custom menu.html and history file
sDir='external/m2html/templates/';
copyfile([sDir 'menu-for-frame-piotr.html'],'doc/menu.html');
copyfile('external/history.txt','doc/history.txt');
% remove links to private/ in the menu.html files and remove private/ dirs
for i=1:length(dirs)
name = ['doc/' dirs{i} '/menu.html'];
fid=fopen(name,'r'); c=fread(fid,'*char')'; fclose(fid);
c=regexprep(c,'<li>([^<]*[<]?[^<]*)private([^<]*[<]?[^<]*)</li>','');
fid=fopen(name,'w'); fwrite(fid,c); fclose(fid);
name = ['doc/' dirs{i} '/private/'];
if(exist(name,'dir')), rmdir(name,'s'); end
end
% postprocess each html file
for d=1:length(dirs)
fs=dir(['doc/' dirs{d} '/*.html']); fs={fs.name};
for j=1:length(fs), postProcess(['doc/' dirs{d} '/' fs{j}]); end
end
end
function postProcess( fName )
lines=readFile(fName);
assert(strcmp(lines{end-1},'</body>') && strcmp(lines{end},'</html>'));
% remove m2html datestamp (if present)
assert(strcmp(lines{end-2}(1:22),'<hr><address>Generated'));
if( strcmp(lines{end-2}(1:25),'<hr><address>Generated on'))
lines{end-2}=regexprep(lines{end-2}, ...
'<hr><address>Generated on .* by','<hr><address>Generated by');
end
% remove crossreference information
is=find(strcmp('<!-- crossreference -->',lines));
if(~isempty(is)), assert(length(is)==2); lines(is(1):is(2))=[]; end
% insert Google Analytics snippet to end of file
ga={ '';
'<!-- Start of Google Analytics Code -->';
'<script type="text/javascript">';
'var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");';
'document.write(unescape("%3Cscript src=''" + gaJsHost + "google-analytics.com/ga.js'' type=''text/javascript''%3E%3C/script%3E"));';
'</script>';
'<script type="text/javascript">';
'var pageTracker = _gat._getTracker("UA-4884268-1");';
'pageTracker._initData();';
'pageTracker._trackPageview();';
'</script>';
'<!-- end of Google Analytics Code -->';
'' };
lines = [lines(1:end-3); ga; lines(end-2:end)];
% write file
writeFile( fName, lines );
end
function lines = readFile( fName )
fid = fopen( fName, 'rt' ); assert(fid~=-1);
lines=cell(10000,1); n=0;
while( 1 )
n=n+1; lines{n}=fgetl(fid);
if( ~ischar(lines{n}) ), break; end
end
fclose(fid); n=n-1; lines=lines(1:n);
end
function writeFile( fName, lines )
fid = fopen( fName, 'w' );
for i=1:length(lines); fprintf( fid, '%s\r\n', lines{i} ); end
fclose(fid);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
toolboxHeader.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/toolboxHeader.m
| 2,391 |
utf_8
|
30c24a94fb54ca82622719adcab17903
|
function [y1,y2] = toolboxHeader( x1, x2, x3, prm )
% One line description of function (will appear in file summary).
%
% General commments explaining purpose of function [width is 75
% characters]. There may be multiple paragraphs. In special cases some or
% all of these guidelines may need to be broken.
%
% Next come a series of sections, including USAGE, INPUTS, OUTPUTS,
% EXAMPLE, and "See also". Each of these fields should always appear, even
% if nothing follows (for example no inputs). USAGE should usually be a
% copy of the first line of code (which begins with "function"), minus the
% word "function". Optional parameters are surrounded by brackets.
% Occasionally, there may be more than 1 distinct usage, in this case list
% additional usages. In general try to avoid this. INPUTS/OUTPUTS are
% self explanatory, however if there are multiple usages can be subdivided
% as below. EXAMPLE should list 1 or more useful examples. Main comment
% should all appear as one contiguous block. Next a blank comment line,
% and then a short comment that includes the toolbox version.
%
% USAGE
% xsum = toolboxHeader( x1, x2, [x3], [prm] )
% [xprod, xdiff] = toolboxHeader( x1, x2, [x3], [prm] )
%
% INPUTS
% x1 - descr. of variable 1,
% x2 - descr. of variable 2, keep spacing like this
% if descr. spans multiple lines do this
% x3 - [0] indicates an optional variable, put def val in []
% prm - [] param struct
% .p1 parameter 1 descr
% .p2 parameter 2 descr
%
% OUTPUTS - and whatever after the dash
% xsum - sum of xs
%
% OUTPUTS - usage 2
% xprod - prod of xs
% xdiff - negative sum of xs
%
% EXAMPLE - and whatever after the dash
% y = toolboxHeader( 1, 2 );
%
% EXAMPLE - example 2
% y = toolboxHeader( 2, 3 );
%
% See also GETPRMDFLT
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% optional arguments x3 and prm
if( nargin<3 || isempty(x3) ), x3=0; end
if( nargin<4 || isempty(prm) ), prm=[]; end %#ok<NASGU>
% indents should be set with Matlab's "smart indent" (with 2 spaces)
if( nargout==1 )
y1 = add(x1,x2) + x3;
else
y1 = x1 * x2 * x3;
y2 = - x1 - x2 - x3;
end
function s=add(x,y)
% optional sub function comment
s=x+y;
|
github
|
garrickbrazil/SDS-RCNN-master
|
mdot.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/m2html/mdot.m
| 2,516 |
utf_8
|
34a14428c433e118d1810e23f5a6caf5
|
function mdot(mmat, dotfile,f)
%MDOT - Export a dependency graph into DOT language
% MDOT(MMAT, DOTFILE) loads a .mat file generated by M2HTML using option
% ('save','on') and writes an ascii file using the DOT language that can
% be drawn using <dot> or <neato> .
% MDOT(MMAT, DOTFILE,F) builds the graph containing M-file F and its
% neighbors only.
% See the following page for more details:
% <http://www.graphviz.org/>
%
% Example:
% mdot('m2html.mat','m2html.dot');
% !dot -Tps m2html.dot -o m2html.ps
% !neato -Tps m2html.dot -o m2html.ps
%
% See also M2HTML
% Copyright (C) 2004 Guillaume Flandin <[email protected]>
% $Revision: 1.1 $Date: 2004/05/05 17:14:09 $
error(nargchk(2,3,nargin));
if ischar(mmat)
load(mmat);
elseif iscell(mmat)
hrefs = mmat{1};
names = mmat{2};
options = mmat{3};
if nargin == 3, mfiles = mmat{4}; end
mdirs = cell(size(names));
[mdirs{:}] = deal('');
if nargin == 2 & length(mmat) > 3,
mdirs = mmat{4};
end;
else
error('[mdot] Invalid argument: mmat.');
end
fid = fopen(dotfile,'wt');
if fid == -1, error(sprintf('[mdot] Cannot open %s.',dotfile)); end
fprintf(fid,'/* Created by mdot for Matlab */\n');
fprintf(fid,'digraph m2html {\n');
% if 'names' contains '.' then they should be surrounded by '"'
if nargin == 2
for i=1:size(hrefs,1)
n = find(hrefs(i,:) == 1);
m{i} = n;
for j=1:length(n)
fprintf(fid,[' ' names{i} ' -> ' names{n(j)} ';\n']);
end
end
%m = unique([m{:}]);
fprintf(fid,'\n');
for i=1:size(hrefs,1)
fprintf(fid,[' ' names{i} ' [URL="' ...
fullurl(mdirs{i},[names{i} options.extension]) '"];\n']);
end
else
i = find(strcmp(f,mfiles));
if length(i) ~= 1
error(sprintf('[mdot] Cannot find %s.',f));
end
n = find(hrefs(i,:) == 1);
for j=1:length(n)
fprintf(fid,[' ' names{i} ' -> ' names{n(j)} ';\n']);
end
m = find(hrefs(:,i) == 1);
for j=1:length(m)
if n(j) ~= i
fprintf(fid,[' ' names{m(j)} ' -> ' names{i} ';\n']);
end
end
n = unique([n(:)' m(:)']);
fprintf(fid,'\n');
for i=1:length(n)
fprintf(fid,[' ' names{n(i)} ' [URL="' fullurl(mdirs{i}, ...
[names{n(i)} options.extension]) '"];\n']);
end
end
fprintf(fid,'}');
fid = fclose(fid);
if fid == -1, error(sprintf('[mdot] Cannot close %s.',dotfile)); end
%===========================================================================
function f = fullurl(varargin)
%- Build full url from parts (using '/' and not filesep)
f = strrep(fullfile(varargin{:}),'\','/');
|
github
|
garrickbrazil/SDS-RCNN-master
|
m2html.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/m2html/m2html.m
| 49,063 |
utf_8
|
472047b4c36a4f8b162012840e31b59b
|
function m2html(varargin)
%M2HTML - Documentation Generator for Matlab M-files and Toolboxes in HTML
% M2HTML by itself generates an HTML documentation of the Matlab M-files found
% in the direct subdirectories of the current directory. HTML files are
% written in a 'doc' directory (created if necessary). All the others options
% are set to default (in brackets in the following).
% M2HTML('PropertyName1',PropertyValue1,'PropertyName2',PropertyValue2,...)
% sets multiple option values. The list of option names and default values is:
% o mFiles - Cell array of strings or character array containing the
% list of M-files and/or directories of M-files for which an HTML
% documentation will be built (use relative paths without backtracking).
% Launch M2HTML one directory above the directory your wanting to
% generate documentation for [ <all direct subdirectories> ]
% o htmlDir - Top level directory for generated HTML files [ 'doc' ]
% o recursive - Process subdirectories recursively [ on | {off} ]
% o source - Include Matlab source code in the generated documentation
% [ {on} | off ]
% o download - Add a link to download each M-file separately [ on | {off} ]
% o syntaxHighlighting - Source Code Syntax Highlighting [ {on} | off ]
% o tabs - Replace '\t' (horizontal tab) in source code by n white space
% characters [ 0 ... {4} ... n ]
% o globalHypertextLinks - Hypertext links among separate Matlab
% directories [ on | {off} ]
% o todo - Create a TODO list in each directory summarizing all the
% '% TODO %' lines found in Matlab code [ on | {off}]
% o graph - Compute a dependency graph using GraphViz [ on | {off}]
% 'dot' required, see <http://www.graphviz.org/>
% o indexFile - Basename of the HTML index file [ 'index' ]
% o extension - Extension of generated HTML files [ '.html' ]
% o template - HTML template name to use [ {'blue'} | 'frame' | ... ]
% o search - Add a PHP search engine [ on | {off}] - beta version!
% o save - Save current state after M-files parsing in 'm2html.mat'
% in directory htmlDir [ on | {off}]
% o load - Load a previously saved '.mat' M2HTML state to generate HTML
% files once again with possibly other options [ <none> ]
% o verbose - Verbose mode [ {on} | off ]
%
% For more information, please read the M2HTML tutorial and FAQ at:
% <http://www.artefact.tk/software/matlab/m2html/>
%
% Examples:
% >> m2html('mfiles','matlab', 'htmldir','doc');
% >> m2html('mfiles',{'matlab/signal' 'matlab/image'}, 'htmldir','doc');
% >> m2html('mfiles','matlab', 'htmldir','doc', 'recursive','on');
% >> m2html('mfiles','mytoolbox', 'htmldir','doc', 'source','off');
% >> m2html('mfiles','matlab', 'htmldir','doc', 'global','on');
% >> m2html( ... , 'template','frame', 'index','menu');
%
% See also MWIZARD, MDOT, TEMPLATE.
% Copyright (C) 2005 Guillaume Flandin <[email protected]>
% $Revision: 1.5 $Date: 2005/04/29 16:04:17 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to [email protected]
% For tips on how to write Matlab code, see:
% * MATLAB Programming Style Guidelines, by R. Johnson:
% <http://www.datatool.com/prod02.htm>
% * For tips on creating help for your m-files 'type help.m'.
% * Matlab documentation on M-file Programming:
% <http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/ch_funh8.html>
% This function uses the Template class so that you can fully customize
% the output. You can modify .tpl files in templates/blue/ or create new
% templates in a new directory.
% See the template class documentation for more details.
% <http://www.artefact.tk/software/matlab/template/>
% Latest information on M2HTML is available on the web through:
% <http://www.artefact.tk/software/matlab/m2html/>
% Other Matlab to HTML converters available on the web:
% 1/ mat2html.pl, J.C. Kantor, in Perl, 1995:
% <http://fresh.t-systems-sfr.com/unix/src/www/mat2html>
% 2/ htmltools, B. Alsberg, in Matlab, 1997:
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=175>
% 3/ mtree2html2001, H. Pohlheim, in Perl, 1996, 2001:
% <http://www.pohlheim.com/perl_main.html#matlabdocu>
% 4/ MatlabToHTML, T. Kristjansson, binary, 2001:
% <http://www.psi.utoronto.ca/~trausti/MatlabToHTML/MatlabToHTML.html>
% 5/ Highlight, G. Flandin, in Matlab, 2003:
% <http://www.artefact.tk/software/matlab/highlight/>
% 6/ mdoc, P. Brinkmann, in Matlab, 2003:
% <http://www.math.uiuc.edu/~brinkman/software/mdoc/>
% 7/ Ocamaweb, Miriad Technologies, in Ocaml, 2002:
% <http://ocamaweb.sourceforge.net/>
% 8/ Matdoc, M. Kaminsky, in Perl, 2003:
% <http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=3498>
% 9/ Matlab itself, The Mathworks Inc, with HELPWIN, DOC and PUBLISH (R14)
%-------------------------------------------------------------------------------
%- Set up options and default parameters
%-------------------------------------------------------------------------------
t0 = clock; % for statistics
msgInvalidPair = 'Bad value for argument: ''%s''';
options = struct('verbose', 1,...
'mFiles', {{'.'}},...
'htmlDir', 'doc',...
'recursive', 0,...
'source', 1,...
'download',0,...
'syntaxHighlighting', 1,...
'tabs', 4,...
'globalHypertextLinks', 0,...
'graph', 0,...
'todo', 0,...
'load', 0,...
'save', 0,...
'search', 0,...
'helptocxml', 0,...
'indexFile', 'index',...
'extension', '.html',...
'template', 'blue',...
'rootdir', pwd,...
'language', 'english');
if nargin == 1 & isstruct(varargin{1})
paramlist = [ fieldnames(varargin{1}) ...
struct2cell(varargin{1}) ]';
paramlist = { paramlist{:} };
else
if mod(nargin,2)
error('Invalid parameter/value pair arguments.');
end
paramlist = varargin;
end
optionsnames = lower(fieldnames(options));
for i=1:2:length(paramlist)
pname = paramlist{i};
pvalue = paramlist{i+1};
ind = strmatch(lower(pname),optionsnames);
if isempty(ind)
error(['Invalid parameter: ''' pname '''.']);
elseif length(ind) > 1
error(['Ambiguous parameter: ''' pname '''.']);
end
switch(optionsnames{ind})
case 'verbose'
if strcmpi(pvalue,'on')
options.verbose = 1;
elseif strcmpi(pvalue,'off')
options.verbose = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'mfiles'
if iscellstr(pvalue)
options.mFiles = pvalue;
elseif ischar(pvalue)
options.mFiles = cellstr(pvalue);
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'htmldir'
if ischar(pvalue)
if isempty(pvalue),
options.htmlDir = '.';
else
options.htmlDir = pvalue;
end
else
error(sprintf(msgInvalidPair,pname));
end
case 'recursive'
if strcmpi(pvalue,'on')
options.recursive = 1;
elseif strcmpi(pvalue,'off')
options.recursive = 0;
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'source'
if strcmpi(pvalue,'on')
options.source = 1;
elseif strcmpi(pvalue,'off')
options.source = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'download'
if strcmpi(pvalue,'on')
options.download = 1;
elseif strcmpi(pvalue,'off')
options.download = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'syntaxhighlighting'
if strcmpi(pvalue,'on')
options.syntaxHighlighting = 1;
elseif strcmpi(pvalue,'off')
options.syntaxHighlighting = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'tabs'
if pvalue >= 0
options.tabs = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'globalhypertextlinks'
if strcmpi(pvalue,'on')
options.globalHypertextLinks = 1;
elseif strcmpi(pvalue,'off')
options.globalHypertextLinks = 0;
else
error(sprintf(msgInvalidPair,pname));
end
options.load = 0;
case 'graph'
if strcmpi(pvalue,'on')
options.graph = 1;
elseif strcmpi(pvalue,'off')
options.graph = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'todo'
if strcmpi(pvalue,'on')
options.todo = 1;
elseif strcmpi(pvalue,'off')
options.todo = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'load'
if ischar(pvalue)
if exist(pvalue) == 7 % directory provided
pvalue = fullfile(pvalue,'m2html.mat');
end
try
load(pvalue);
catch
error(sprintf('Unable to load %s.', pvalue));
end
options.load = 1;
[dummy options.template] = fileparts(options.template);
else
error(sprintf(msgInvalidPair,pname));
end
case 'save'
if strcmpi(pvalue,'on')
options.save = 1;
elseif strcmpi(pvalue,'off')
options.save = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'search'
if strcmpi(pvalue,'on')
options.search = 1;
elseif strcmpi(pvalue,'off')
options.search = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'helptocxml'
if strcmpi(pvalue,'on')
options.helptocxml = 1;
elseif strcmpi(pvalue,'off')
options.helptocxml = 0;
else
error(sprintf(msgInvalidPair,pname));
end
case 'indexfile'
if ischar(pvalue)
options.indexFile = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'extension'
if ischar(pvalue) & pvalue(1) == '.'
options.extension = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'template'
if ischar(pvalue)
options.template = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
case 'language'
if ischar(pvalue)
options.language = pvalue;
else
error(sprintf(msgInvalidPair,pname));
end
otherwise
error(['Invalid parameter: ''' pname '''.']);
end
end
%-------------------------------------------------------------------------------
%- Get template files location
%-------------------------------------------------------------------------------
s = fileparts(which(mfilename));
options.template = fullfile(s,'templates',options.template);
if exist(options.template) ~= 7
error('[Template] Unknown template.');
end
%-------------------------------------------------------------------------------
%- Get list of M-files
%-------------------------------------------------------------------------------
if ~options.load
if strcmp(options.mFiles,'.')
d = dir(pwd); d = {d([d.isdir]).name};
options.mFiles = {d{~ismember(d,{'.' '..'})}};
end
mfiles = getmfiles(options.mFiles,{},options.recursive);
if ~length(mfiles), fprintf('Nothing to be done.\n'); return; end
if options.verbose,
fprintf('Found %d M-files.\n',length(mfiles));
end
mfiles = sort(mfiles); % sort list of M-files in dictionary order
end
%-------------------------------------------------------------------------------
%- Get list of (unique) directories and (unique) names
%-------------------------------------------------------------------------------
if ~options.load
mdirs = {};
names = {};
for i=1:length(mfiles)
[mdirs{i}, names{i}] = fileparts(mfiles{i});
if isempty(mdirs{i}), mdirs{i} = '.'; end
end
mdir = unique(mdirs);
if options.verbose,
fprintf('Found %d unique Matlab directories.\n',length(mdir));
end
name = names;
%name = unique(names); % output is sorted
%if options.verbose,
% fprintf('Found %d unique Matlab files.\n',length(name));
%end
end
%-------------------------------------------------------------------------------
%- Create output directory, if necessary
%-------------------------------------------------------------------------------
if isempty(dir(options.htmlDir))
%- Create the top level output directory
if options.verbose
fprintf('Creating directory %s...\n',options.htmlDir);
end
if options.htmlDir(end) == filesep,
options.htmlDir(end) = [];
end
[pathdir, namedir] = fileparts(options.htmlDir);
if isempty(pathdir)
[status, msg] = mkdir(escapeblank(namedir));
else
[status, msg] = mkdir(escapeblank(pathdir), escapeblank(namedir));
end
if ~status, error(msg); end
end
%-------------------------------------------------------------------------------
%- Get synopsis, H1 line, script/function, subroutines, cross-references, todo
%-------------------------------------------------------------------------------
if ~options.load
synopsis = cell(size(mfiles));
h1line = cell(size(mfiles));
subroutine = cell(size(mfiles));
hrefs = sparse(length(mfiles), length(mfiles));
todo = struct('mfile',[], 'line',[], 'comment',{{}});
ismex = zeros(length(mfiles), length(mexexts));
statlist = {};
statinfo = sparse(1,length(mfiles));
kw = cell(size(mfiles));
freq = cell(size(mfiles));
for i=1:length(mfiles)
if options.verbose
fprintf('Processing file %s...',mfiles{i});
end
s = mfileparse(mfiles{i}, mdirs, names, options);
synopsis{i} = s.synopsis;
h1line{i} = s.h1line;
subroutine{i} = s.subroutine;
hrefs(i,:) = s.hrefs;
todo.mfile = [todo.mfile repmat(i,1,length(s.todo.line))];
todo.line = [todo.line s.todo.line];
todo.comment = {todo.comment{:} s.todo.comment{:}};
ismex(i,:) = s.ismex;
if options.search
if options.verbose, fprintf('search...'); end
[kw{i}, freq{i}] = searchindex(mfiles{i});
statlist = union(statlist, kw{i});
end
if options.verbose, fprintf('\n'); end
end
hrefs = hrefs > 0;
if options.search
if options.verbose
fprintf('Creating the search index...');
end
statinfo = sparse(length(statlist),length(mfiles));
for i=1:length(mfiles)
i1 = find(ismember(statlist, kw{i}));
i2 = repmat(i,1,length(i1));
if ~isempty(i1)
statinfo(sub2ind(size(statinfo),i1,i2)) = freq{i};
end
if options.verbose, fprintf('.'); end
end
clear kw freq;
if options.verbose, fprintf('\n'); end
end
end
%-------------------------------------------------------------------------------
%- Save M-filenames and cross-references for further analysis
%-------------------------------------------------------------------------------
matfilesave = 'm2html.mat';
if options.save
if options.verbose
fprintf('Saving MAT file %s...\n',matfilesave);
end
save(fullfile(options.htmlDir,matfilesave), ...
'mfiles', 'names', 'mdirs', 'name', 'mdir', 'options', ...
'hrefs', 'synopsis', 'h1line', 'subroutine', 'todo', 'ismex', ...
'statlist', 'statinfo');
end
%-------------------------------------------------------------------------------
%- Setup the output directories
%-------------------------------------------------------------------------------
for i=1:length(mdir)
if exist(fullfile(options.htmlDir,mdir{i})) ~= 7
ldir = splitpath(mdir{i});
for j=1:length(ldir)
if exist(fullfile(options.htmlDir,ldir{1:j})) ~= 7
%- Create the output directory
if options.verbose
fprintf('Creating directory %s...\n',...
fullfile(options.htmlDir,ldir{1:j}));
end
if j == 1
[status, msg] = mkdir(escapeblank(options.htmlDir), ...
escapeblank(ldir{1}));
else
[status, msg] = mkdir(escapeblank(options.htmlDir), ...
escapeblank(fullfile(ldir{1:j})));
end
error(msg);
end
end
end
end
%-------------------------------------------------------------------------------
%- Write the master index file
%-------------------------------------------------------------------------------
tpl_master = 'master.tpl';
tpl_master_identifier_nbyline = 4;
php_search = 'search.php';
dotbase = 'graph';
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MASTER',tpl_master);
tpl = set(tpl,'block','TPL_MASTER','rowdir','rowdirs');
tpl = set(tpl,'block','TPL_MASTER','idrow','idrows');
tpl = set(tpl,'block','idrow','idcolumn','idcolumns');
tpl = set(tpl,'block','TPL_MASTER','search','searchs');
tpl = set(tpl,'block','TPL_MASTER','graph','graphs');
%- Open for writing the HTML master index file
curfile = fullfile(options.htmlDir,[options.indexFile options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set some template variables
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
tpl = set(tpl,'var','MASTERPATH', './');
tpl = set(tpl,'var','DIRS', sprintf('%s ',mdir{:}));
%- Print list of unique directories
for i=1:length(mdir)
tpl = set(tpl,'var','L_DIR',...
fullurl(mdir{i},[options.indexFile options.extension]));
tpl = set(tpl,'var','DIR',mdir{i});
tpl = parse(tpl,'rowdirs','rowdir',1);
end
%- Print full list of M-files (sorted by column)
[sortnames, ind] = sort(names);
m_mod = mod(length(sortnames), tpl_master_identifier_nbyline);
ind = [ind zeros(1,tpl_master_identifier_nbyline-m_mod)];
m_floor = floor(length(ind) / tpl_master_identifier_nbyline);
ind = reshape(ind,m_floor,tpl_master_identifier_nbyline)';
for i=1:prod(size(ind))
if ind(i)
tpl = set(tpl,'var','L_IDNAME',...
fullurl(mdirs{ind(i)},[names{ind(i)} options.extension]));
tpl = set(tpl,'var','T_IDNAME',mdirs{ind(i)});
tpl = set(tpl,'var','IDNAME',names{ind(i)});
tpl = parse(tpl,'idcolumns','idcolumn',1);
else
tpl = set(tpl,'var','L_IDNAME','');
tpl = set(tpl,'var','T_IDNAME','');
tpl = set(tpl,'var','IDNAME','');
tpl = parse(tpl,'idcolumns','idcolumn',1);
end
if mod(i,tpl_master_identifier_nbyline) == 0
tpl = parse(tpl,'idrows','idrow',1);
tpl = set(tpl,'var','idcolumns','');
end
end
%- Add a search form if necessary
tpl = set(tpl,'var','searchs','');
if options.search
tpl = set(tpl,'var','PHPFILE',php_search);
tpl = parse(tpl,'searchs','search',1);
end
%- Link to a full dependency graph, if necessary
tpl = set(tpl,'var','graphs','');
if options.graph & options.globalHypertextLinks & length(mdir) > 1
tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]);
tpl = parse(tpl,'graphs','graph',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_MASTER');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
%-------------------------------------------------------------------------------
%- Copy template files (CSS, images, ...)
%-------------------------------------------------------------------------------
% Get list of files
d = dir(options.template);
d = {d(~[d.isdir]).name};
% Copy files
for i=1:length(d)
[p, n, ext] = fileparts(d{i});
if ~strcmp(ext,'.tpl') ... % do not copy .tpl files
& ~strcmp([n ext],'Thumbs.db') % do not copy this Windows generated file
if isempty(dir(fullfile(options.htmlDir,d{i})))
if options.verbose
fprintf('Copying template file %s...\n',d{i});
end
%- there is a bug with <copyfile> in Matlab 6.5 :
% http://www.mathworks.com/support/solutions/data/1-1B5JY.html
%- and <copyfile> does not overwrite files even if newer...
[status, errmsg] = copyfile(fullfile(options.template,d{i}),...
options.htmlDir);
%- If you encounter this bug, please uncomment one of the following lines
% eval(['!cp -rf ' fullfile(options.template,d{i}) ' ' options.htmlDir]);
% eval(['!copy ' fullfile(options.template,d{i}) ' ' options.htmlDir]);
% status = 1;
if ~status
if ~isempty(errmsg)
error(errmsg)
else
warning(sprintf(['<copyfile> failed to do its job...\n' ...
'This is a known bug in Matlab 6.5 (R13).\n' ...
'See http://www.mathworks.com/support/solutions/data/1-1B5JY.html']));
end
end
end
end
end
%-------------------------------------------------------------------------------
%- Search engine (index file and PHP script)
%-------------------------------------------------------------------------------
tpl_search = 'search.tpl';
idx_search = 'search.idx';
% TODO % improving the fill in of 'statlist' and 'statinfo'
% TODO % improving the search template file and update the CSS file
if options.search
%- Write the search index file in output directory
if options.verbose
fprintf('Creating Search Index file %s...\n', idx_search);
end
docinfo = cell(length(mfiles),2);
for i=1:length(mfiles)
docinfo{i,1} = h1line{i};
docinfo{i,2} = fullurl(mdirs{i}, [names{i} options.extension]);
end
doxywrite(fullfile(options.htmlDir,idx_search),statlist,statinfo,docinfo);
%- Create the PHP template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_SEARCH',tpl_search);
%- Open for writing the PHP search script
curfile = fullfile(options.htmlDir, php_search);
if options.verbose
fprintf('Creating PHP script %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH','./');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
tpl = set(tpl,'var','IDXFILE',idx_search);
tpl = set(tpl,'var','PHPFILE',php_search);
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_SEARCH');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Create <helptoc.xml> needed to display hierarchical entries in Contents panel
%-------------------------------------------------------------------------------
% See http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_env/guiref16.html
% and http://www.mathworks.com/support/solutions/data/1-18U6Q.html?solution=1-18U6Q
% TODO % display directories in TOC hierarchically instead of linearly
if options.helptocxml
curfile = fullfile(options.htmlDir, 'helptoc.xml');
if options.verbose
fprintf('Creating XML Table-Of-Content %s...\n',curfile);
end
fid = openfile(curfile,'w');
fprintf(fid,'<?xml version=''1.0'' encoding=''ISO-8859-1'' ?>\n');
fprintf(fid,'<!-- $Date: %s $ -->\n\n', datestr(now,31));
fprintf(fid,'<toc version="1.0">\n\n');
fprintf(fid,['<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/book_mat.gif">%s\n'], ...
[options.indexFile options.extension],'Toolbox');
for i=1:length(mdir)
fprintf(fid,['<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/reficon.gif">%s\n'], ...
fullfile(mdir{i}, ...
[options.indexFile options.extension]),mdir{i});
if options.graph
fprintf(fid,['\t<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/simulinkicon.gif">%s</tocitem>\n'], ...
fullfile(mdir{i},...
[dotbase options.extension]),'Dependency Graph');
end
if options.todo
if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile))
fprintf(fid,['\t<tocitem target="%s" ',...
'image="$toolbox/matlab/icons/demoicon.gif">%s</tocitem>\n'], ...
fullfile(mdir{i},...
['todo' options.extension]),'Todo list');
end
end
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
curfile = fullfile(mdir{i},...
[names{j} options.extension]);
fprintf(fid,'\t<tocitem target="%s">%s</tocitem>\n', ...
curfile,names{j});
end
end
fprintf(fid,'</tocitem>\n');
end
fprintf(fid,'</tocitem>\n');
fprintf(fid,'\n</toc>\n');
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Write an index for each output directory
%-------------------------------------------------------------------------------
tpl_mdir = 'mdir.tpl';
tpl_mdir_link = '<a href="%s">%s</a>';
%dotbase defined earlier
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MDIR',tpl_mdir);
tpl = set(tpl,'block','TPL_MDIR','row-m','rows-m');
tpl = set(tpl,'block','row-m','mexfile','mex');
tpl = set(tpl,'block','TPL_MDIR','othermatlab','other');
tpl = set(tpl,'block','othermatlab','row-other','rows-other');
tpl = set(tpl,'block','TPL_MDIR','subfolder','subfold');
tpl = set(tpl,'block','subfolder','subdir','subdirs');
tpl = set(tpl,'block','TPL_MDIR','todolist','todolists');
tpl = set(tpl,'block','TPL_MDIR','graph','graphs');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
for i=1:length(mdir)
%- Open for writing each output directory index file
curfile = fullfile(options.htmlDir,mdir{i},...
[options.indexFile options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH',backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
%- Display Matlab m-files, their H1 line and their Mex status
tpl = set(tpl,'var','rows-m','');
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
tpl = set(tpl,'var','L_NAME', [names{j} options.extension]);
tpl = set(tpl,'var','NAME', names{j});
tpl = set(tpl,'var','H1LINE', h1line{j});
if any(ismex(j,:))
tpl = parse(tpl,'mex','mexfile');
else
tpl = set(tpl,'var','mex','');
end
tpl = parse(tpl,'rows-m','row-m',1);
end
end
%- Display other Matlab-specific files (.mat,.mdl,.p)
tpl = set(tpl,'var','other','');
tpl = set(tpl,'var','rows-other','');
w = what(mdir{i}); w = w(1);
w = {w.mat{:} w.mdl{:} w.p{:}};
for j=1:length(w)
tpl = set(tpl,'var','OTHERFILE',w{j});
tpl = parse(tpl,'rows-other','row-other',1);
end
if ~isempty(w)
tpl = parse(tpl,'other','othermatlab');
end
%- Display subsequent directories and classes
tpl = set(tpl,'var','subdirs','');
tpl = set(tpl,'var','subfold','');
d = dir(mdir{i});
d = {d([d.isdir]).name};
d = {d{~ismember(d,{'.' '..'})}};
for j=1:length(d)
if ismember(fullfile(mdir{i},d{j}),mdir)
tpl = set(tpl,'var','SUBDIRECTORY',...
sprintf(tpl_mdir_link,...
fullurl(d{j},[options.indexFile options.extension]),d{j}));
else
tpl = set(tpl,'var','SUBDIRECTORY',d{j});
end
tpl = parse(tpl,'subdirs','subdir',1);
end
if ~isempty(d)
tpl = parse(tpl,'subfold','subfolder');
end
%- Link to the TODO list if necessary
tpl = set(tpl,'var','todolists','');
if options.todo
if ~isempty(intersect(find(strcmp(mdir{i},mdirs)),todo.mfile))
tpl = set(tpl,'var','LTODOLIST',['todo' options.extension]);
tpl = parse(tpl,'todolists','todolist',1);
end
end
%- Link to the dependency graph if necessary
tpl = set(tpl,'var','graphs','');
if options.graph
tpl = set(tpl,'var','LGRAPH',[dotbase options.extension]);
tpl = parse(tpl,'graphs','graph',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_MDIR');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
%-------------------------------------------------------------------------------
%- Write a TODO list file for each output directory, if necessary
%-------------------------------------------------------------------------------
tpl_todo = 'todo.tpl';
if options.todo
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_TODO',tpl_todo);
tpl = set(tpl,'block','TPL_TODO','filelist','filelists');
tpl = set(tpl,'block','filelist','row','rows');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
for i=1:length(mdir)
mfilestodo = intersect(find(strcmp(mdir{i},mdirs)),todo.mfile);
if ~isempty(mfilestodo)
%- Open for writing each TODO list file
curfile = fullfile(options.htmlDir,mdir{i},...
['todo' options.extension]);
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
%- Set template fields
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
tpl = set(tpl,'var','filelists', '');
for k=1:length(mfilestodo)
tpl = set(tpl,'var','MFILE',names{mfilestodo(k)});
tpl = set(tpl,'var','rows','');
nbtodo = find(todo.mfile == mfilestodo(k));
for l=1:length(nbtodo)
tpl = set(tpl,'var','L_NBLINE',...
[names{mfilestodo(k)} ...
options.extension ...
'#l' num2str(todo.line(nbtodo(l)))]);
tpl = set(tpl,'var','NBLINE',num2str(todo.line(nbtodo(l))));
tpl = set(tpl,'var','COMMENT',todo.comment{nbtodo(l)});
tpl = parse(tpl,'rows','row',1);
end
tpl = parse(tpl,'filelists','filelist',1);
end
%- Print the template in the HTML file
tpl = parse(tpl,'OUT','TPL_TODO');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid);
end
end
end
%-------------------------------------------------------------------------------
%- Create dependency graphs using GraphViz, if requested
%-------------------------------------------------------------------------------
tpl_graph = 'graph.tpl';
% You may have to modify the following line with Matlab7 (R14) to specify
% the full path to where GraphViz is installed
dot_exec = 'dot';
%dotbase defined earlier
if options.graph
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_GRAPH',tpl_graph);
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
%- Create a full dependency graph for all directories if possible
if options.globalHypertextLinks & length(mdir) > 1
mdotfile = fullfile(options.htmlDir,[dotbase '.dot']);
if options.verbose
fprintf('Creating full dependency graph %s...',mdotfile);
end
mdot({hrefs, names, options, mdirs}, mdotfile); %mfiles
calldot(dot_exec, mdotfile, ...
fullfile(options.htmlDir,[dotbase '.map']), ...
fullfile(options.htmlDir,[dotbase '.png']));
if options.verbose, fprintf('\n'); end
fid = openfile(fullfile(options.htmlDir, [dotbase options.extension]),'w');
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', './');
tpl = set(tpl,'var','MDIR', 'the whole toolbox');
tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']);
try % if <dot> failed...
fmap = openfile(fullfile(options.htmlDir,[dotbase '.map']),'r');
tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c'));
fclose(fmap);
end
tpl = parse(tpl,'OUT','TPL_GRAPH');
fprintf(fid,'%s', get(tpl,'OUT'));
fclose(fid);
end
%- Create a dependency graph for each output directory
for i=1:length(mdir)
mdotfile = fullfile(options.htmlDir,mdir{i},[dotbase '.dot']);
if options.verbose
fprintf('Creating dependency graph %s...',mdotfile);
end
ind = find(strcmp(mdirs,mdir{i}));
href1 = zeros(length(ind),length(hrefs));
for j=1:length(hrefs), href1(:,j) = hrefs(ind,j); end
href2 = zeros(length(ind));
for j=1:length(ind), href2(j,:) = href1(j,ind); end
mdot({href2, {names{ind}}, options}, mdotfile); %{mfiles{ind}}
calldot(dot_exec, mdotfile, ...
fullfile(options.htmlDir,mdir{i},[dotbase '.map']), ...
fullfile(options.htmlDir,mdir{i},[dotbase '.png']));
if options.verbose, fprintf('\n'); end
fid = openfile(fullfile(options.htmlDir,mdir{i},...
[dotbase options.extension]),'w');
tpl = set(tpl,'var','INDEX',[options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdir{i});
tpl = set(tpl,'var','GRAPH_IMG', [dotbase '.png']);
try % if <dot> failed, no '.map' file has been created
fmap = openfile(fullfile(options.htmlDir,mdir{i},[dotbase '.map']),'r');
tpl = set(tpl,'var','GRAPH_MAP', fscanf(fmap,'%c'));
fclose(fmap);
end
tpl = parse(tpl,'OUT','TPL_GRAPH');
fprintf(fid,'%s', get(tpl,'OUT'));
fclose(fid);
end
end
%-------------------------------------------------------------------------------
%- Write an HTML file for each M-file
%-------------------------------------------------------------------------------
%- List of Matlab keywords (output from iskeyword)
matlabKeywords = {'break', 'case', 'catch', 'continue', 'elseif', 'else', ...
'end', 'for', 'function', 'global', 'if', 'otherwise', ...
'persistent', 'return', 'switch', 'try', 'while'};
%'keyboard', 'pause', 'eps', 'NaN', 'Inf'
tpl_mfile = 'mfile.tpl';
tpl_mfile_code = '<a href="%s" class="code" title="%s">%s</a>';
tpl_mfile_keyword = '<span class="keyword">%s</span>';
tpl_mfile_comment = '<span class="comment">%s</span>';
tpl_mfile_string = '<span class="string">%s</span>';
tpl_mfile_aname = '<a name="%s" href="#_subfunctions" class="code">%s</a>';
tpl_mfile_line = '%04d %s\n';
%- Delimiters used in strtok: some of them may be useless (% " .), removed '.'
strtok_delim = sprintf(' \t\n\r(){}[]<>+-*~!|\\@&/,:;="''%%');
%- Create the HTML template
tpl = template(options.template,'remove');
tpl = set(tpl,'file','TPL_MFILE',tpl_mfile);
tpl = set(tpl,'block','TPL_MFILE','pathline','pl');
tpl = set(tpl,'block','TPL_MFILE','mexfile','mex');
tpl = set(tpl,'block','TPL_MFILE','script','scriptfile');
tpl = set(tpl,'block','TPL_MFILE','crossrefcall','crossrefcalls');
tpl = set(tpl,'block','TPL_MFILE','crossrefcalled','crossrefcalleds');
tpl = set(tpl,'block','TPL_MFILE','subfunction','subf');
tpl = set(tpl,'block','subfunction','onesubfunction','onesubf');
tpl = set(tpl,'block','TPL_MFILE','source','thesource');
tpl = set(tpl,'block','TPL_MFILE','download','downloads');
tpl = set(tpl,'var','DATE',[datestr(now,8) ' ' datestr(now,1) ' ' ...
datestr(now,13)]);
nblinetot = 0;
for i=1:length(mdir)
for j=1:length(mdirs)
if strcmp(mdirs{j},mdir{i})
curfile = fullfile(options.htmlDir,mdir{i},...
[names{j} options.extension]);
%- Copy M-file for download, if necessary
if options.download
if options.verbose
fprintf('Copying M-file %s.m to %s...\n',names{j},...
fullfile(options.htmlDir,mdir{i}));
end
[status, errmsg] = copyfile(mfiles{j},...
fullfile(options.htmlDir,mdir{i}));
error(errmsg);
end
%- Open for writing the HTML file
if options.verbose
fprintf('Creating HTML file %s...\n',curfile);
end
fid = openfile(curfile,'w');
if strcmp(names{j},options.indexFile)
fprintf(['Warning: HTML index file %s will be ' ...
'overwritten by Matlab function %s.\n'], ...
[options.indexFile options.extension], mfiles{j});
end
%- Open for reading the M-file
fid2 = openfile(mfiles{j},'r');
%- Set some template fields
tpl = set(tpl,'var','INDEX', [options.indexFile options.extension]);
tpl = set(tpl,'var','MASTERPATH', backtomaster(mdir{i}));
tpl = set(tpl,'var','MDIR', mdirs{j});
tpl = set(tpl,'var','NAME', names{j});
tpl = set(tpl,'var','H1LINE', entity(h1line{j}));
tpl = set(tpl,'var','scriptfile', '');
if isempty(synopsis{j})
tpl = set(tpl,'var','SYNOPSIS',get(tpl,'var','script'));
else
tpl = set(tpl,'var','SYNOPSIS', synopsis{j});
end
s = splitpath(mdir{i});
tpl = set(tpl,'var','pl','');
for k=1:length(s)
c = cell(1,k); for l=1:k, c{l} = filesep; end
cpath = {s{1:k};c{:}}; cpath = [cpath{:}];
if ~isempty(cpath), cpath = cpath(1:end-1); end
if ismember(cpath,mdir)
tpl = set(tpl,'var','LPATHDIR',[repmat('../',...
1,length(s)-k) options.indexFile options.extension]);
else
tpl = set(tpl,'var','LPATHDIR','#');
end
tpl = set(tpl,'var','PATHDIR',s{k});
tpl = parse(tpl,'pl','pathline',1);
end
%- Handle mex files
tpl = set(tpl,'var','mex', '');
samename = dir(fullfile(mdir{i},[names{j} '.*']));
samename = {samename.name};
tpl = set(tpl,'var','MEXTYPE', 'mex');
for k=1:length(samename)
[dummy, dummy, ext] = fileparts(samename{k});
switch ext
case '.c'
tpl = set(tpl,'var','MEXTYPE', 'c');
case {'.cpp' '.c++' '.cxx' '.C'}
tpl = set(tpl,'var','MEXTYPE', 'c++');
case {'.for' '.f' '.FOR' '.F'}
tpl = set(tpl,'var','MEXTYPE', 'fortran');
otherwise
%- Unknown mex file source
end
end
[exts, platform] = mexexts;
mexplatforms = sprintf('%s, ',platform{find(ismex(j,:))});
if ~isempty(mexplatforms)
tpl = set(tpl,'var','PLATFORMS', mexplatforms(1:end-2));
tpl = parse(tpl,'mex','mexfile');
end
%- Set description template field
descr = '';
flagsynopcont = 0;
flag_seealso = 0;
while 1
tline = fgets(fid2);
if ~ischar(tline), break, end
tline = entity(fliplr(deblank(fliplr(tline))));
%- Synopsis line
if ~isempty(strmatch('function',tline))
if ~isempty(strmatch('...',fliplr(deblank(tline))))
flagsynopcont = 1;
end
%- H1 line and description
elseif ~isempty(strmatch('%',tline))
%- Hypertext links on the "See also" line
ind = findstr(lower(tline),'see also');
if ~isempty(ind) | flag_seealso
%- "See also" only in files in the same directory
indsamedir = find(strcmp(mdirs{j},mdirs));
hrefnames = {names{indsamedir}};
r = deblank(tline);
flag_seealso = 1; %(r(end) == ',');
tline = '';
while 1
[t,r,q] = strtok(r,sprintf(' \t\n\r.,;%%'));
tline = [tline q];
if isempty(t), break, end;
ii = strcmpi(hrefnames,t);
if any(ii)
jj = find(ii);
tline = [tline sprintf(tpl_mfile_code,...
[hrefnames{jj(1)} options.extension],...
synopsis{indsamedir(jj(1))},t)];
else
tline = [tline t];
end
end
tline = sprintf('%s\n',tline);
end
descr = [descr tline(2:end)];
elseif isempty(tline)
if ~isempty(descr), break, end;
else
if flagsynopcont
if isempty(strmatch('...',fliplr(deblank(tline))))
flagsynopcont = 0;
end
else
break;
end
end
end
tpl = set(tpl,'var','DESCRIPTION',...
horztab(descr,options.tabs));
%- Set cross-references template fields:
% Function called
ind = find(hrefs(j,:) == 1);
tpl = set(tpl,'var','crossrefcalls','');
for k=1:length(ind)
if strcmp(mdirs{j},mdirs{ind(k)})
tpl = set(tpl,'var','L_NAME_CALL', ...
[names{ind(k)} options.extension]);
else
tpl = set(tpl,'var','L_NAME_CALL', ...
fullurl(backtomaster(mdirs{j}), ...
mdirs{ind(k)}, ...
[names{ind(k)} options.extension]));
end
tpl = set(tpl,'var','SYNOP_CALL', synopsis{ind(k)});
tpl = set(tpl,'var','NAME_CALL', names{ind(k)});
tpl = set(tpl,'var','H1LINE_CALL', h1line{ind(k)});
tpl = parse(tpl,'crossrefcalls','crossrefcall',1);
end
% Callers
ind = find(hrefs(:,j) == 1);
tpl = set(tpl,'var','crossrefcalleds','');
for k=1:length(ind)
if strcmp(mdirs{j},mdirs{ind(k)})
tpl = set(tpl,'var','L_NAME_CALLED', ...
[names{ind(k)} options.extension]);
else
tpl = set(tpl,'var','L_NAME_CALLED', ...
fullurl(backtomaster(mdirs{j}),...
mdirs{ind(k)}, ...
[names{ind(k)} options.extension]));
end
tpl = set(tpl,'var','SYNOP_CALLED', synopsis{ind(k)});
tpl = set(tpl,'var','NAME_CALLED', names{ind(k)});
tpl = set(tpl,'var','H1LINE_CALLED', h1line{ind(k)});
tpl = parse(tpl,'crossrefcalleds','crossrefcalled',1);
end
%- Set subfunction template field
tpl = set(tpl,'var',{'subf' 'onesubf'},{'' ''});
if ~isempty(subroutine{j}) & options.source
for k=1:length(subroutine{j})
tpl = set(tpl, 'var', 'L_SUB', ['#_sub' num2str(k)]);
tpl = set(tpl, 'var', 'SUB', subroutine{j}{k});
tpl = parse(tpl, 'onesubf', 'onesubfunction',1);
end
tpl = parse(tpl,'subf','subfunction');
end
subname = extractname(subroutine{j});
%- Link to M-file (for download)
tpl = set(tpl,'var','downloads','');
if options.download
tpl = parse(tpl,'downloads','download',1);
end
%- Display source code with cross-references
if options.source & ~strcmpi(names{j},'contents')
fseek(fid2,0,-1);
it = 1;
matlabsource = '';
nbsubroutine = 1;
%- Get href function names of this file
indhrefnames = find(hrefs(j,:) == 1);
hrefnames = {names{indhrefnames}};
%- Loop over lines
while 1
tline = fgetl(fid2);
if ~ischar(tline), break, end
myline = '';
splitc = splitcode(entity(tline));
for k=1:length(splitc)
if isempty(splitc{k})
elseif ~isempty(strmatch('function',splitc{k}))
%- Subfunctions definition
myline = [myline ...
sprintf(tpl_mfile_aname,...
['_sub' num2str(nbsubroutine-1)],splitc{k})];
nbsubroutine = nbsubroutine + 1;
elseif splitc{k}(1) == ''''
myline = [myline ...
sprintf(tpl_mfile_string,splitc{k})];
elseif splitc{k}(1) == '%'
myline = [myline ...
sprintf(tpl_mfile_comment,deblank(splitc{k}))];
elseif ~isempty(strmatch('...',splitc{k}))
myline = [myline sprintf(tpl_mfile_keyword,'...')];
if ~isempty(splitc{k}(4:end))
myline = [myline ...
sprintf(tpl_mfile_comment,splitc{k}(4:end))];
end
else
%- Look for keywords
r = splitc{k};
while 1
[t,r,q] = strtok(r,strtok_delim);
myline = [myline q];
if isempty(t), break, end;
%- Highlight Matlab keywords &
% cross-references on known functions
if options.syntaxHighlighting & ...
any(strcmp(matlabKeywords,t))
if strcmp('end',t)
rr = fliplr(deblank(fliplr(r)));
icomma = strmatch(',',rr);
isemicolon = strmatch(';',rr);
if ~(isempty(rr) | ~isempty([icomma isemicolon]))
myline = [myline t];
else
myline = [myline sprintf(tpl_mfile_keyword,t)];
end
else
myline = [myline sprintf(tpl_mfile_keyword,t)];
end
elseif any(strcmp(hrefnames,t))
indt = indhrefnames(logical(strcmp(hrefnames,t)));
flink = [t options.extension];
ii = ismember({mdirs{indt}},mdirs{j});
if ~any(ii)
% take the first one...
flink = fullurl(backtomaster(mdirs{j}),...
mdirs{indt(1)}, flink);
else
indt = indt(logical(ii));
end
myline = [myline sprintf(tpl_mfile_code,...
flink, synopsis{indt(1)}, t)];
elseif any(strcmp(subname,t))
ii = find(strcmp(subname,t));
myline = [myline sprintf(tpl_mfile_code,...
['#_sub' num2str(ii)],...
['sub' subroutine{j}{ii}],t)];
else
myline = [myline t];
end
end
end
end
matlabsource = [matlabsource sprintf(tpl_mfile_line,it,myline)];
it = it + 1;
end
nblinetot = nblinetot + it - 1;
tpl = set(tpl,'var','SOURCECODE',...
horztab(matlabsource,options.tabs));
tpl = parse(tpl,'thesource','source');
else
tpl = set(tpl,'var','thesource','');
end
tpl = parse(tpl,'OUT','TPL_MFILE');
fprintf(fid,'%s',get(tpl,'OUT'));
fclose(fid2);
fclose(fid);
end
end
end
%-------------------------------------------------------------------------------
%- Display Statistics
%-------------------------------------------------------------------------------
if options.verbose
prnbline = '';
if options.source
prnbline = sprintf('(%d lines) ', nblinetot);
end
fprintf('Stats: %d M-files %sin %d directories documented in %d s.\n', ...
length(mfiles), prnbline, length(mdir), round(etime(clock,t0)));
end
%===============================================================================
function mfiles = getmfiles(mdirs, mfiles, recursive)
%- Extract M-files from a list of directories and/or M-files
for i=1:length(mdirs)
currentdir = fullfile(pwd, mdirs{i});
if exist(currentdir) == 2 % M-file
mfiles{end+1} = mdirs{i};
elseif exist(currentdir) == 7 % Directory
d = dir(fullfile(currentdir, '*.m'));
d = {d(~[d.isdir]).name};
for j=1:length(d)
%- don't take care of files containing ','
% probably a sccs file...
if isempty(findstr(',',d{j}))
mfiles{end+1} = fullfile(mdirs{i}, d{j});
end
end
if recursive
d = dir(currentdir);
d = {d([d.isdir]).name};
d = {d{~ismember(d,{'.' '..'})}};
for j=1:length(d)
mfiles = getmfiles(cellstr(fullfile(mdirs{i},d{j})), ...
mfiles, recursive);
end
end
else
fprintf('Warning: Unprocessed file %s.\n',mdirs{i});
if ~isempty(strmatch('/',mdirs{i})) | findstr(':',mdirs{i})
fprintf(' Use relative paths in ''mfiles'' option\n');
end
end
end
%===============================================================================
function calldot(dotexec, mdotfile, mapfile, pngfile, opt)
%- Draw a dependency graph in a PNG image using <dot> from GraphViz
if nargin == 4, opt = ''; end
try
%- See <http://www.graphviz.org/>
% <dot> must be in your system path, see M2HTML FAQ:
% <http://www.artefact.tk/software/matlab/m2html/faq.php>
eval(['!"' dotexec '" ' opt ' -Tcmap -Tpng "' mdotfile ...
'" -o "' mapfile ...
'" -o "' pngfile '"']);
% use '!' rather than 'system' for backward compability with Matlab 5.3
catch % use of '!' prevents errors to be catched...
fprintf('<dot> failed.');
end
%===============================================================================
function s = backtomaster(mdir)
%- Provide filesystem path to go back to the root folder
ldir = splitpath(mdir);
s = repmat('../',1,length(ldir));
%===============================================================================
function ldir = splitpath(p)
%- Split a filesystem path into parts using filesep as separator
ldir = {};
p = deblank(p);
while 1
[t,p] = strtok(p,filesep);
if isempty(t), break; end
if ~strcmp(t,'.')
ldir{end+1} = t;
end
end
if isempty(ldir)
ldir{1} = '.'; % should be removed
end
%===============================================================================
function name = extractname(synopsis)
%- Extract function name in a synopsis
if ischar(synopsis), synopsis = {synopsis}; end
name = cell(size(synopsis));
for i=1:length(synopsis)
ind = findstr(synopsis{i},'=');
if isempty(ind)
ind = findstr(synopsis{i},'function');
s = synopsis{i}(ind(1)+8:end);
else
s = synopsis{i}(ind(1)+1:end);
end
name{i} = strtok(s,[9:13 32 40]); % white space characters and '('
end
if length(name) == 1, name = name{1}; end
%===============================================================================
function f = fullurl(varargin)
%- Build full url from parts (using '/' and not filesep)
f = strrep(fullfile(varargin{:}),'\','/');
%===============================================================================
function str = escapeblank(str)
%- Escape white spaces using '\'
str = deblank(fliplr(deblank(fliplr(str))));
str = strrep(str,' ','\ ');
%===============================================================================
function str = entity(str)
%- Escape HTML special characters
%- See http://www.w3.org/TR/html4/charset.html#h-5.3.2
str = strrep(str,'&','&');
str = strrep(str,'<','<');
str = strrep(str,'>','>');
str = strrep(str,'"','"');
%===============================================================================
function str = horztab(str,n)
%- For browsers, the horizontal tab character is the smallest non-zero
%- number of spaces necessary to line characters up along tab stops that are
%- every 8 characters: behaviour obtained when n = 0.
if n > 0
str = strrep(str,sprintf('\t'),blanks(n));
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
doxysearch.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/m2html/private/doxysearch.m
| 7,724 |
utf_8
|
8331cde8495f34b86aef8c18656b37f2
|
function result = doxysearch(query,filename)
%DOXYSEARCH Search a query in a 'search.idx' file
% RESULT = DOXYSEARCH(QUERY,FILENAME) looks for request QUERY
% in FILENAME (Doxygen search.idx format) and returns a list of
% files responding to the request in RESULT.
%
% See also DOXYREAD, DOXYWRITE
% Copyright (C) 2004 Guillaume Flandin <[email protected]>
% $Revision: 1.1 $Date: 2004/05/05 14:33:55 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(1,2,nargin));
if nargin == 1,
filename = 'search.idx';
end
%- Open the search index file
[fid, errmsg] = fopen(filename,'r','ieee-be');
if fid == -1, error(errmsg); end
%- 4 byte header (DOXS)
header = char(fread(fid,4,'uchar'))';
if ~all(header == 'DOXS')
error('[doxysearch] Header of index file is invalid!');
end
%- many thanks to <doxyread.m> and <doxysearch.php>
r = query;
requiredWords = {};
forbiddenWords = {};
foundWords = {};
res = {};
while 1
% extract each word of the query
[t,r] = strtok(r);
if isempty(t), break, end;
if t(1) == '+'
t = t(2:end); requiredWords{end+1} = t;
elseif t(1) == '-'
t = t(2:end); forbiddenWords{end+1} = t;
end
if ~ismember(t,foundWords)
foundWords{end+1} = t;
res = searchAgain(fid,t,res);
end
end
%- Filter and sort results
docs = combineResults(res);
filtdocs = filterResults(docs,requiredWords,forbiddenWords);
filtdocs = normalizeResults(filtdocs);
res = sortResults(filtdocs);
%-
if nargout
result = res;
else
for i=1:size(res,1)
fprintf(' %d. %s - %s\n ',i,res{i,1},res{i,2});
for j=1:size(res{i,4},1)
fprintf('%s ',res{i,4}{j,1});
end
fprintf('\n');
end
end
%- Close the search index file
fclose(fid);
%===========================================================================
function res = searchAgain(fid, word,res)
i = computeIndex(word);
if i > 0
fseek(fid,i*4+4,'bof'); % 4 bytes per entry, skip header
start = size(res,1);
idx = readInt(fid);
if idx > 0
fseek(fid,idx,'bof');
statw = readString(fid);
while ~isempty(statw)
statidx = readInt(fid);
if length(statw) >= length(word) & ...
strcmp(statw(1:length(word)),word)
res{end+1,1} = statw; % word
res{end,2} = word; % match
res{end,3} = statidx; % index
res{end,4} = (length(statw) == length(word)); % full
res{end,5} = {}; % doc
end
statw = readString(fid);
end
totalfreq = 0;
for j=start+1:size(res,1)
fseek(fid,res{j,3},'bof');
numdoc = readInt(fid);
docinfo = {};
for m=1:numdoc
docinfo{m,1} = readInt(fid); % idx
docinfo{m,2} = readInt(fid); % freq
docinfo{m,3} = 0; % rank
totalfreq = totalfreq + docinfo{m,2};
if res{j,2},
totalfreq = totalfreq + docinfo{m,2};
end;
end
for m=1:numdoc
fseek(fid, docinfo{m,1}, 'bof');
docinfo{m,4} = readString(fid); % name
docinfo{m,5} = readString(fid); % url
end
res{j,5} = docinfo;
end
for j=start+1:size(res,1)
for m=1:size(res{j,5},1)
res{j,5}{m,3} = res{j,5}{m,2} / totalfreq;
end
end
end % if idx > 0
end % if i > 0
%===========================================================================
function docs = combineResults(result)
docs = {};
for i=1:size(result,1)
for j=1:size(result{i,5},1)
key = result{i,5}{j,5};
rank = result{i,5}{j,3};
if ~isempty(docs) & ismember(key,{docs{:,1}})
l = find(ismember({docs{:,1}},key));
docs{l,3} = docs{l,3} + rank;
docs{l,3} = 2 * docs{l,3};
else
l = size(docs,1)+1;
docs{l,1} = key; % key
docs{l,2} = result{i,5}{j,4}; % name
docs{l,3} = rank; % rank
docs{l,4} = {}; %words
end
n = size(docs{l,4},1);
docs{l,4}{n+1,1} = result{i,1}; % word
docs{l,4}{n+1,2} = result{i,2}; % match
docs{l,4}{n+1,3} = result{i,5}{j,2}; % freq
end
end
%===========================================================================
function filtdocs = filterResults(docs,requiredWords,forbiddenWords)
filtdocs = {};
for i=1:size(docs,1)
words = docs{i,4};
c = 1;
j = size(words,1);
% check required
if ~isempty(requiredWords)
found = 0;
for k=1:j
if ismember(words{k,1},requiredWords)
found = 1;
break;
end
end
if ~found, c = 0; end
end
% check forbidden
if ~isempty(forbiddenWords)
for k=1:j
if ismember(words{k,1},forbiddenWords)
c = 0;
break;
end
end
end
% keep it or not
if c,
l = size(filtdocs,1)+1;
filtdocs{l,1} = docs{i,1};
filtdocs{l,2} = docs{i,2};
filtdocs{l,3} = docs{i,3};
filtdocs{l,4} = docs{i,4};
end;
end
%===========================================================================
function docs = normalizeResults(docs);
m = max([docs{:,3}]);
for i=1:size(docs,1)
docs{i,3} = 100 * docs{i,3} / m;
end
%===========================================================================
function result = sortResults(docs);
[y, ind] = sort([docs{:,3}]);
result = {};
ind = fliplr(ind);
for i=1:size(docs,1)
result{i,1} = docs{ind(i),1};
result{i,2} = docs{ind(i),2};
result{i,3} = docs{ind(i),3};
result{i,4} = docs{ind(i),4};
end
%===========================================================================
function i = computeIndex(word)
if length(word) < 2,
i = -1;
else
i = double(word(1)) * 256 + double(word(2));
end
%===========================================================================
function s = readString(fid)
s = '';
while 1
w = fread(fid,1,'uchar');
if w == 0, break; end
s(end+1) = char(w);
end
%===========================================================================
function i = readInt(fid)
i = fread(fid,1,'uint32');
|
github
|
garrickbrazil/SDS-RCNN-master
|
doxywrite.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/m2html/private/doxywrite.m
| 3,584 |
utf_8
|
3255d8f824957ebc173dde374d0f78af
|
function doxywrite(filename, kw, statinfo, docinfo)
%DOXYWRITE Write a 'search.idx' file compatible with DOXYGEN
% DOXYWRITE(FILENAME, KW, STATINFO, DOCINFO) writes file FILENAME
% (Doxygen search.idx. format) using the cell array KW containing the
% word list, the sparse matrix (nbword x nbfile) with non-null values
% in (i,j) indicating the frequency of occurence of word i in file j
% and the cell array (nbfile x 2) containing the list of urls and names
% of each file.
%
% See also DOXYREAD
% Copyright (C) 2003 Guillaume Flandin <[email protected]>
% $Revision: 1.0 $Date: 2003/23/10 15:52:56 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(4,4,nargin));
%- Open the search index file
[fid, errmsg] = fopen(filename,'w','ieee-be');
if fid == -1, error(errmsg); end
%- Write 4 byte header (DOXS)
fwrite(fid,'DOXS','uchar');
pos = ftell(fid);
%- Write 256 * 256 header
idx = zeros(256);
writeInt(fid, idx);
%- Write word lists
i = 1;
idx2 = zeros(1,length(kw));
while 1
s = kw{i}(1:2);
idx(double(s(2)+1), double(s(1)+1)) = ftell(fid);
while i <= length(kw) & strmatch(s, kw{i})
writeString(fid,kw{i});
idx2(i) = ftell(fid);
writeInt(fid,0);
i = i + 1;
end
fwrite(fid, 0, 'int8');
if i > length(kw), break; end
end
%- Write extra padding bytes
pad = mod(4 - mod(ftell(fid),4), 4);
for i=1:pad, fwrite(fid,0,'int8'); end
pos2 = ftell(fid);
%- Write 256*256 header again
fseek(fid, pos, 'bof');
writeInt(fid, idx);
% Write word statistics
fseek(fid,pos2,'bof');
idx3 = zeros(1,length(kw));
for i=1:length(kw)
idx3(i) = ftell(fid);
[ia, ib, v] = find(statinfo(i,:));
counter = length(ia); % counter
writeInt(fid,counter);
for j=1:counter
writeInt(fid,ib(j)); % index
writeInt(fid,v(j)); % freq
end
end
pos3 = ftell(fid);
%- Set correct handles to keywords
for i=1:length(kw)
fseek(fid,idx2(i),'bof');
writeInt(fid,idx3(i));
end
% Write urls
fseek(fid,pos3,'bof');
idx4 = zeros(1,length(docinfo));
for i=1:length(docinfo)
idx4(i) = ftell(fid);
writeString(fid, docinfo{i,1}); % name
writeString(fid, docinfo{i,2}); % url
end
%- Set corrext handles to word statistics
fseek(fid,pos2,'bof');
for i=1:length(kw)
[ia, ib, v] = find(statinfo(i,:));
counter = length(ia);
fseek(fid,4,'cof'); % counter
for m=1:counter
writeInt(fid,idx4(ib(m)));% index
fseek(fid,4,'cof'); % freq
end
end
%- Close the search index file
fclose(fid);
%===========================================================================
function writeString(fid, s)
fwrite(fid,s,'uchar');
fwrite(fid,0,'int8');
%===========================================================================
function writeInt(fid, i)
fwrite(fid,i,'uint32');
|
github
|
garrickbrazil/SDS-RCNN-master
|
doxyread.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/m2html/private/doxyread.m
| 3,093 |
utf_8
|
3152e7d26bf7ac64118be56f72832a20
|
function [statlist, docinfo] = doxyread(filename)
%DOXYREAD Read a 'search.idx' file generated by DOXYGEN
% STATLIST = DOXYREAD(FILENAME) reads FILENAME (Doxygen search.idx
% format) and returns the list of keywords STATLIST as a cell array.
% [STATLIST, DOCINFO] = DOXYREAD(FILENAME) also returns a cell array
% containing details for each keyword (frequency in each file where it
% appears and the URL).
%
% See also DOXYSEARCH, DOXYWRITE
% Copyright (C) 2003 Guillaume Flandin <[email protected]>
% $Revision: 1.0 $Date: 2003/05/10 17:41:21 $
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation Inc, 59 Temple Pl. - Suite 330, Boston, MA 02111-1307, USA.
% Suggestions for improvement and fixes are always welcome, although no
% guarantee is made whether and when they will be implemented.
% Send requests to <[email protected]>
% See <http://www.doxygen.org/> for more details.
error(nargchk(0,1,nargin));
if nargin == 0,
filename = 'search.idx';
end
%- Open the search index file
[fid, errmsg] = fopen(filename,'r','ieee-be');
if fid == -1, error(errmsg); end
%- 4 byte header (DOXS)
header = char(fread(fid,4,'uchar'))';
%- 256*256*4 byte index
idx = fread(fid,256*256,'uint32');
idx = reshape(idx,256,256);
%- Extract list of words
i = find(idx);
statlist = cell(0,2);
for j=1:length(i)
fseek(fid, idx(i(j)), 'bof');
statw = readString(fid);
while ~isempty(statw)
statidx = readInt(fid);
statlist{end+1,1} = statw; % word
statlist{end,2} = statidx; % index
statw = readString(fid);
end
end
%- Extract occurence frequency of each word and docs info (name and url)
docinfo = cell(size(statlist,1),1);
for k=1:size(statlist,1)
fseek(fid, statlist{k,2}, 'bof');
numdoc = readInt(fid);
docinfo{k} = cell(numdoc,4);
for m=1:numdoc
docinfo{k}{m,1} = readInt(fid); % idx
docinfo{k}{m,2} = readInt(fid); % freq
end
for m=1:numdoc
fseek(fid, docinfo{k}{m,1}, 'bof');
docinfo{k}{m,3} = readString(fid); % name
docinfo{k}{m,4} = readString(fid); % url
end
docinfo{k} = reshape({docinfo{k}{:,2:4}},numdoc,[]);
end
%- Close the search index file
fclose(fid);
%- Remove indexes
statlist = {statlist{:,1}}';
%===========================================================================
function s = readString(fid)
s = '';
while 1
w = fread(fid,1,'uchar');
if w == 0, break; end
s(end+1) = char(w);
end
%===========================================================================
function i = readInt(fid)
i = fread(fid,1,'uint32');
|
github
|
garrickbrazil/SDS-RCNN-master
|
imwrite2split.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/imwrite2split.m
| 1,617 |
utf_8
|
4222fd45df123e6dec9ef40ae793004f
|
% Writes/reads a large set of images into/from multiple directories.
%
% This is useful since certain OS handle very large directories (of say
% >20K images) rather poorly (I'm talking to you Bill). Thus, can take
% 100K images, and write into 5 separate directories, then read them back
% in.
%
% USAGE
% I = imwrite2split( I, nSplits, spliti, path, [varargin] )
%
% INPUTS
% I - image or images (if [] reads else writes)
% nSplits - number of directories to split data into
% spliti - first split number
% path - directory where images are
% writePrms - [varargin] parameters to imwrite2
%
% OUTPUTS
% I - image or images (read from disk if input I=[])
%
% EXAMPLE
% load images; clear IDXi IDXv t video videos;
% imwrite2split( images(:,:,1:10), 2, 0, 'rats', 'rats', 'png', 5 );
% images2=imwrite2split( [], 2, 0, 'rats', 'rats', 'png', 5 );
%
% See also IMWRITE2
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = imwrite2split( I, nSplits, spliti, path, varargin )
n = size(I,3); if( isempty(I) ); n=0; end
nSplits = min(n,nSplits);
for s=1:nSplits
pathSplit = [path int2str2(s-1+spliti,2)];
if( n>0 ) % write
nPerDir = ceil( n / nSplits );
ISplit = I(:,:,1:min(end,nPerDir));
imwrite2( ISplit, nPerDir>1, 0, pathSplit, varargin{:} );
if( s~=nSplits ); I = I(:,:,(nPerDir+1):end); end
else % read
ISplit = imwrite2( [], 1, 0, pathSplit, varargin{:} );
I = cat(3,I,ISplit);
end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
playmovies.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/playmovies.m
| 1,935 |
utf_8
|
ef2eaad8a130936a1a281f1277ca0ea1
|
% [4D] shows R videos simultaneously as a movie.
%
% Plays a movie.
%
% USAGE
% playmovies( I, [fps], [loop] )
%
% INPUTS
% I - MxNxTxR or MxNx1xTxR or MxNx3xTxR array (if MxNxT calls
% playmovie)
% fps - [100] maximum number of frames to display per second use
% fps==0 to introduce no pause and have the movie play as
% fast as possible
% loop - [0] number of time to loop video (may be inf),
% if neg plays video forward then backward then forward etc.
%
% OUTPUTS
%
% EXAMPLE
% load( 'images.mat' );
% playmovies( videos );
%
% See also MONTAGES, PLAYMOVIE, MAKEMOVIES
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function playmovies( I, fps, loop )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n PLAYMOVIE is its '...
'recommended replacement.'],upper(mfilename));
if( nargin<2 || isempty(fps)); fps = 100; end
if( nargin<3 || isempty(loop)); loop = 1; end
playmovie( I, fps, loop )
%
% nd=ndims(I); siz=size(I); nframes=siz(end-1);
% if( nd==3 ); playmovie( I, fps, loop ); return; end
% if( iscell(I) ); error('cell arrays not supported.'); end
% if( ~(nd==4 || (nd==5 && any(size(I,3)==[1 3]))) )
% error('unsupported dimension of I'); end
% inds={':'}; inds=inds(:,ones(1,nd-2));
% clim = [min(I(:)),max(I(:))];
%
% h=gcf; colormap gray; figure(h); % bring to focus
% for nplayed = 1 : abs(loop)
% if( loop<0 && mod(nplayed,2)==1 )
% order = nframes:-1:1;
% else
% order = 1:nframes;
% end
% for i=order
% tic; try disc=get(h); catch return; end %#ok<NASGU>
% montage2(squeeze(I(inds{:},i,:)),1,[],clim);
% title(sprintf('frame %d of %d',i,nframes));
% if(fps>0); pause(1/fps - toc); else pause(eps); end
% end
% end
|
github
|
garrickbrazil/SDS-RCNN-master
|
pca_apply_large.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/pca_apply_large.m
| 2,062 |
utf_8
|
af84a2179b9d8042519bc6b378736a88
|
% Wrapper for pca_apply that allows for application to large X.
%
% Wrapper for pca_apply that splits and processes X in parts, this may be
% useful if processing cannot be done fully in parallel because of memory
% constraints. See pca_apply for usage.
%
% USAGE
% same as pca_apply
%
% INPUTS
% same as pca_apply
%
% OUTPUTS
% same as pca_apply
%
% EXAMPLE
%
% See also PCA, PCA_APPLY, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [ Yk, Xhat, avsq ] = pca_apply_large( X, U, mu, vars, k )
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% Will run out of memory if X has too many elements. Hence, run
% pca_apply on parts of X and recombine.
maxwidth = ceil( (10^7) / d );
if(maxwidth > siz(end))
if (nargout==1)
Yk = pca_apply( X, U, mu, vars, k );
elseif (nargout==2)
[Yk, Xhat] = pca_apply( X, U, mu, vars, k );
else
[ Yk, Xhat, avsq ] = pca_apply( X, U, mu, vars, k );
end
else
Yk = zeros( k, siz(end) ); Xhat = zeros( siz );
avsq = 0; avsqOrig = 0; last = 0;
while(last < siz(end))
first=last+1; last=min(first+maxwidth-1,siz(end));
Xi = X(inds{:}, first:last);
if( nargout==1 )
Yki = pca_apply( Xi, U, mu, vars, k );
else
if( nargout==2 )
[Yki,Xhati] = pca_apply( Xi, U, mu, vars, k );
else
[Yki,Xhati,avsqi,avsqOrigi] = pca_apply( Xi, U, mu, vars, k );
avsq = avsq + avsqi; avsqOrig = avsqOrig + avsqOrigi;
end;
Xhat(inds{:}, first:last ) = Xhati;
end
Yk( :, first:last ) = Yki;
end;
if( nargout==3); avsq = avsq / avsqOrig; end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
montages2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/montages2.m
| 2,269 |
utf_8
|
505e2be915d65fff8bfef8473875cc98
|
% MONTAGES2 [4D] Used to display R sets of T images each.
%
% Displays one montage (see montage2) per row. Each of the R image sets is
% flattened to a single long image by concatenating the T images in the
% set. Alternative to montages.
%
% USAGE
% varargout = montages2( IS, [montage2prms], [padSiz] )
%
% INPUTS
% IS - MxNxTxR or MxNx1xTxR or MxNx3xTxR array
% montage2prms - [] params for montage2; ex: {showLns,extraInf}
% padSiz - [4] total amount of vertical or horizontal padding
%
% OUTPUTS
% I - 3D or 4D array of flattened images, disp with montage2
% mm - #montages/row
% nn - #montages/col
%
% EXAMPLE
% load( 'images.mat' );
% imageclusters = clustermontage( images, IDXi, 16, 1 );
% montages2( imageclusters );
%
% See also MONTAGES, MAKEMOVIES, MONTAGE2, CLUSTERMONTAGE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function varargout = montages2( IS, montage2prms, padSiz )
if( nargin<2 || isempty(montage2prms) ); montage2prms = {}; end
if( nargin<3 || isempty(padSiz) ); padSiz = 4; end
[padSiz,er] = checknumericargs( padSiz,[1 1], 0, 1 ); error(er);
% get/test image format info
nd = ndims(IS); siz = size(IS);
if( nd==5 ) %MxNx1xTxR or MxNx3xTxR
nch = size(IS,3);
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end
if( nch==1 ); IS = squeeze(IS); nd=4; siz=size(IS); end
end
if ~any(nd==3:5)
error('unsupported dimension of IS');
end
% reshape IS so that each 3D element is concatenated to a 2D image, adding
% padding
padEl = max(IS(:));
IS=arraycrop2dims(IS, [siz(1)+padSiz siz(2:end)], padEl ); %UD pad
siz=size(IS);
if(nd==3) % reshape bw single
IS=squeeze( reshape( IS, siz(1), [] ) );
elseif(nd==4) % reshape bw
IS=squeeze( reshape( IS, siz(1), [], siz(4) ) );
else % reshape color
IS=squeeze( reshape(permute(IS,[1 2 4 3 5]),siz(1),[],siz(3),siz(5)));
end; siz = size(IS);
IS=arraycrop2dims(IS, [siz(1) siz(2)+padSiz siz(3:end)], padEl);
% show using montage2
varargout = cell(1,nargout);
if( nargout); varargout{1}=IS; end;
[varargout{2:end}] = montage2( IS, montage2prms{:} );
title(inputname(1));
|
github
|
garrickbrazil/SDS-RCNN-master
|
filter_gauss_1D.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/filter_gauss_1D.m
| 1,137 |
utf_8
|
94a453b82dcdeba67bd886e042d552d9
|
% 1D Gaussian filter.
%
% Equivalent to (but faster then):
% f = fspecial('Gaussian',[2*r+1,1],sigma);
% f = filter_gauss_nD( 2*r+1, r+1, sigma^2 );
%
% USAGE
% f = filter_gauss_1D( r, sigma, [show] )
%
% INPUTS
% r - filter size=2r+1, if r=[] -> r=ceil(2.25*sigma)
% sigma - standard deviation of filter
% show - [0] figure to use for optional display
%
% OUTPUTS
% f - 1D Gaussian filter
%
% EXAMPLE
% f1 = filter_gauss_1D( 10, 2, 1 );
% f2 = filter_gauss_nD( 21, [], 2^2, 2);
%
% See also FILTER_BINOMIAL_1D, FILTER_GAUSS_ND, FSPECIAL
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function f = filter_gauss_1D( r, sigma, show )
if( nargin<3 || isempty(show) ); show=0; end
if( isempty(r) ); r = ceil(sigma*2.25); end
if( mod(r,1)~=0 ); error( 'r must be an integer'); end
% compute filter
x = -r:r;
f = exp(-(x.*x)/(2*sigma*sigma))';
f(f<eps*max(f(:))*10) = 0;
sumf = sum(f(:)); if(sumf~=0); f = f/sumf; end
% display
if(show); filter_visualize_1D( f, show ); end
|
github
|
garrickbrazil/SDS-RCNN-master
|
clfEcoc.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/clfEcoc.m
| 1,493 |
utf_8
|
e77e1b4fd5469ed39f47dd6ed15f130f
|
function clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets)
% Wrapper for ecoc that makes ecoc compatible with nfoldxval.
%
% Requires the SVM toolbox by Anton Schwaighofer.
%
% USAGE
% clf = clfEcoc(p,clfInit,clfparams,nclasses,use01targets)
%
% INPUTS
% p - data dimension
% clfInit - binary classifier init (see nfoldxval)
% clfparams - binary classifier parameters (see nfoldxval)
% nclasses - num of classes (currently 3<=nclasses<=7 suppored)
% use01targets - see ecoc
%
% OUTPUTS
% clf - see ecoc
%
% EXAMPLE
%
% See also ECOC, NFOLDXVAL, CLFECOCCODE
%
% Piotr's Image&Video Toolbox Version 2.0
% Copyright 2008 Piotr Dollar. [pdollar-at-caltech.edu]
% Please email me if you find bugs, or have suggestions or questions!
% Licensed under the Lesser GPL [see external/lgpl.txt]
if( nclasses<3 || nclasses>7 )
error( 'currently only works if 3<=nclasses<=7'); end;
if( nargin<5 || isempty(use01targets)); use01targets=0; end;
% create code (limited for now)
[C,nbits] = clfEcocCode( nclasses );
clf = ecoc(nclasses, nbits, C, use01targets ); % didn't use to pass use01?
clf.verbosity = 0; % don't diplay output
% initialize and temporarily store binary learner
clf.templearner = feval( clfInit, p, clfparams{:} );
% ecoctrain2 is custom version of ecoctrain
clf.funTrain = @clfEcocTrain;
clf.funFwd = @ecocfwd;
function clf = clfEcocTrain( clf, varargin )
clf = ecoctrain( clf, clf.templearner, varargin{:} );
|
github
|
garrickbrazil/SDS-RCNN-master
|
getargs.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/getargs.m
| 3,455 |
utf_8
|
de2bab917fa6b9ba3099f1c6b6d68cf0
|
% Utility to process parameter name/value pairs.
%
% DEPRECATED -- ONLY USED BY KMEANS2? SHOULD BE REMOVED.
% USE GETPARAMDEFAULTS INSTEAD.
%
% Based on code fromt Matlab Statistics Toolobox's "private/statgetargs.m"
%
% [EMSG,A,B,...]=GETARGS(PNAMES,DFLTS,'NAME1',VAL1,'NAME2',VAL2,...)
% accepts a cell array PNAMES of valid parameter names, a cell array DFLTS
% of default values for the parameters named in PNAMES, and additional
% parameter name/value pairs. Returns parameter values A,B,... in the same
% order as the names in PNAMES. Outputs corresponding to entries in PNAMES
% that are not specified in the name/value pairs are set to the
% corresponding value from DFLTS. If nargout is equal to length(PNAMES)+1,
% then unrecognized name/value pairs are an error. If nargout is equal to
% length(PNAMES)+2, then all unrecognized name/value pairs are returned in
% a single cell array following any other outputs.
%
% EMSG is empty if the arguments are valid, or the text of an error message
% if an error occurs. GETARGS does not actually throw any errors, but
% rather returns an error message so that the caller may throw the error.
% Outputs will be partially processed after an error occurs.
%
% USAGE
% [emsg,varargout]=getargs(pnames,dflts,varargin)
%
% INPUTS
% pnames - cell of valid parameter names
% dflts - cell of default parameter values
% varargin - list of proposed name / value pairs
%
% OUTPUTS
% emsg - error msg - '' if no error
% varargout - list of assigned name / value pairs
%
% EXAMPLE
% pnames = {'color' 'linestyle', 'linewidth'}; dflts = { 'r','_','1'};
% v = {'linew' 2 'nonesuch' [1 2 3] 'linestyle' ':'};
% [emsg,color,linestyle,linewidth,unrec] = getargs(pnames,dflts,v{:}) % ok
% [emsg,color,linestyle,linewidth] = getargs(pnames,dflts,v{:}) % err
%
% See also GETPARAMDEFAULTS
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [emsg,varargout]=getargs(pnames,dflts,varargin)
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n It will be ' ...
'removed in the next version of the toolbox.'],upper(mfilename));
% We always create (nparams+1) outputs:
% one for emsg
% nparams varargs for values corresponding to names in pnames
% If they ask for one more (nargout == nparams+2), it's for unrecognized
% names/values
emsg = '';
nparams = length(pnames);
varargout = dflts;
unrecog = {};
nargs = length(varargin);
% Must have name/value pairs
if mod(nargs,2)~=0
emsg = sprintf('Wrong number of arguments.');
else
% Process name/value pairs
for j=1:2:nargs
pname = varargin{j};
if ~ischar(pname)
emsg = sprintf('Parameter name must be text.');
break;
end
i = strmatch(lower(pname),lower(pnames));
if isempty(i)
% if they've asked to get back unrecognized names/values, add this
% one to the list
if nargout > nparams+1
unrecog((end+1):(end+2)) = {varargin{j} varargin{j+1}};
% otherwise, it's an error
else
emsg = sprintf('Invalid parameter name: %s.',pname);
break;
end
elseif length(i)>1
emsg = sprintf('Ambiguous parameter name: %s.',pname);
break;
else
varargout{i} = varargin{j+1};
end
end
end
varargout{nparams+1} = unrecog;
|
github
|
garrickbrazil/SDS-RCNN-master
|
normxcorrn_fg.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/normxcorrn_fg.m
| 2,699 |
utf_8
|
e65c38d97efb3a624e0fa94a97f75eb6
|
% Normalized n-dimensional cross-correlation with a mask.
%
% Similar to normxcorrn, except takes an additional argument that specifies
% a figure ground mask for the T. That is T_fg must be of the same
% dimensions as T, with each entry being 0 or 1, where zero specifies
% regions to ignore (the ground) and 1 specifies interesting regions (the
% figure). Essentially T_fg specifies regions in T that are interesting
% and should be taken into account when doing normalized cross correlation.
% This allows for templates of arbitrary shape, and not just squares.
%
% Note: this function is approximately 3 times slower then normxcorr2
% because it cannot use the trick of precomputing sums.
%
% USAGE
% C = normxcorrn_fg( T, T_fg, A, [shape] )
%
% INPUTS
% T - template to correlate to each window in A
% T_fg - figure/ground mask for the template
% A - matrix to correlate T to
% shape - ['full'] 'valid', 'full', or 'same', see convn_fast help
%
% OUTPUTS
% C - correlation matrix
%
% EXAMPLE
% A=rand(50); B=rand(11); Bfg=ones(11);
% C1=normxcorrn_fg(B,Bfg,A); C2=normxcorr2(B,A);
% figure(1); im(C1); figure(2); im(C2);
% figure(3); im(abs(C1-C2));
%
% See also NORMXCORRN
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function C = normxcorrn_fg( T, T_fg, A, shape )
if( nargin <4 || isempty(shape)); shape='full'; end;
if( ndims(T)~=ndims(A) || ndims(T)~=ndims(T_fg) )
error('TEMPALTE, T_fg, and A must have same number of dimensions'); end;
if( any(size(T)~=size(T_fg)))
error('TEMPALTE and T_fg must have same dimensions'); end;
if( ~all(T_fg==0 | T_fg==1))
error('T_fg may have only entries either 0 or 1'); end;
nkeep = sum(T_fg(:));
if( nkeep==0); error('T_fg must have some nonzero values'); end;
% center T on 0 and normalize magnitued to 1, excluding ground
% T= (T-T_av) / ||(T-T_av)||
T(T_fg==0)=0;
T = T - sum(T(:)) / nkeep;
T(T_fg==0)=0;
T = T / norm( T(:) );
% flip for convn_fast purposes
for d=1:ndims(T); T = flipdim(T,d); end;
for d=1:ndims(T_fg); T_fg = flipdim(T_fg,d); end;
% get average over each window over A
A_av = convn_fast( A, T_fg/nkeep, shape );
% get magnitude over each window over A "mag(WA-WAav)"
% We can rewrite the above as "sqrt(SUM(WAi^2)-n*WAav^2)". so:
A_mag = convn_fast( A.*A, T_fg, shape ) - nkeep * A_av .* A_av;
A_mag = sqrt(A_mag); A_mag(A_mag<.000001)=1; %removes divide by 0 error
% finally get C. in each image window, we will now do:
% "dot(T,(WA-WAav)) / mag(WA-WAav)"
C = convn_fast(A,T,shape) - A_av*sum(T(:));
C = C ./ A_mag;
|
github
|
garrickbrazil/SDS-RCNN-master
|
makemovie.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/makemovie.m
| 1,266 |
utf_8
|
9a03d9a5227c4eaa86520f206ce283e7
|
% [3D] Used to convert a stack of T images into a movie.
%
% To display same data statically use montage.
%
% USAGE
% M = makemovies( IS )
%
% INPUTS
% IS - MxNxT or MxNx1xT or MxNx3xT array of movies.
%
% OUTPUTS
% M - resulting movie
%
% EXAMPLE
% load( 'images.mat' );
% M = makemovie( videos(:,:,:,1) );
% movie( M );
%
% See also MONTAGE2, MAKEMOVIES, PLAYMOVIE, CELL2ARRAY, FEVALARRAYS,
% IMMOVIE, MOVIE2AVI
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function M = makemovie( IS )
% get images format (if image stack is MxNxT convert to MxNx1xT)
if (ndims(IS)==3); IS = permute(IS, [1,2,4,3] ); end
siz = size(IS); nch = siz(3); nd = ndims(IS);
if ( nd~=4 ); error('unsupported dimension of IS'); end
if( nch~=1 && nch~=3 ); error('illegal image stack format'); end;
% normalize for maximum contrast
if( isa(IS,'double') ); IS = IS - min(IS(:)); IS = IS / max(IS(:)); end
% make movie
for i=1:siz(4)
Ii=IS(:,:,:,i);
if( nch==1 ); [Ii,Mi] = gray2ind( Ii ); else Mi=[]; end
if i==1
M=repmat(im2frame( Ii, Mi ),[1,siz(4)]);
else
M(i) = im2frame( Ii, Mi );
end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
localsum_block.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/localsum_block.m
| 815 |
utf_8
|
1216b03a3bd44ff1fc3256de16a2f1c6
|
% Calculates the sum in non-overlapping blocks of I of size dims.
%
% Similar to localsum except gets sum in non-overlapping windows.
% Equivalent to doing localsum, and then subsampling (except more
% efficient).
%
% USAGE
% I = localsum_block( I, dims )
%
% INPUTS
% I - matrix to compute sum over
% dims - size of volume to compute sum over
%
% OUTPUTS
% I - resulting array
%
% EXAMPLE
% load trees; I=ind2gray(X,map);
% I2 = localsum_block( I, 11 );
% figure(1); im(I); figure(2); im(I2);
%
% See also LOCALSUM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function I = localsum_block( I, dims )
I = nlfiltblock_sep( I, dims, @rnlfiltblock_sum );
|
github
|
garrickbrazil/SDS-RCNN-master
|
imrotate2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/imrotate2.m
| 1,326 |
utf_8
|
bb2ff6c3138ce5f53154d58d7ebc4f31
|
% Custom version of imrotate that demonstrates use of apply_homography.
%
% Works exactly the same as imrotate. For usage see imrotate.
%
% USAGE
% IR = imrotate2( I, angle, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% angle - angle to rotate in degrees
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - rotated image
%
% EXAMPLE
% load trees;
% tic; X1 = imrotate( X, 55, 'bicubic' ); toc,
% tic; X2 = imrotate2( X, 55, 'bicubic' ); toc
% clf; subplot(2,2,1); im(X); subplot(2,2,2); im(X1-X2);
% subplot(2,2,3); im(X1); subplot(2,2,4); im(X2);
%
% See also IMROTATE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imrotate2( I, angle, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<3 || isempty(method)); method='linear'; end
if( nargin<4 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
angle_rads = angle /180 * pi;
R = rotationMatrix( angle_rads );
H = [R [0;0]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
garrickbrazil/SDS-RCNN-master
|
imSubsResize.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/imSubsResize.m
| 1,338 |
utf_8
|
cd7dedf790c015adfb1f2d620e9ed82f
|
% Resizes subs by resizVals.
%
% Resizes subs in subs/vals image representation by resizVals.
%
% This essentially replaces each sub by sub.*resizVals. The only subtlety
% is that in images the leftmost sub value is .5, so for example when
% resizing by a factor of 2, the first pixel is replaced by 2 pixels and so
% location 1 in the original image goes to location 1.5 in the second
% image, NOT 2. It may be necessary to round the values afterward.
%
% USAGE
% subs = imSubsResize( subs, resizVals, [zeroPnt] )
%
% INPUTS
% subs - subscripts of point locations (n x d)
% resizVals - k element vector of shrinking factors
% zeroPnt - [.5] See comment above.
%
% OUTPUTS
% subs - transformed subscripts of point locations (n x d)
%
% EXAMPLE
% subs = imSubsResize( [1 1; 2 2], [2 2] )
%
%
% See also IMSUBSTOARRAY
% Piotr's Image&Video Toolbox Version NEW
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function subs = imSubsResize( subs, resizVals, zeroPnt )
if( nargin<3 || isempty(zeroPnt) ); zeroPnt=.5; end
[n d] = size(subs);
[resizVals,er] = checkNumArgs( resizVals, [1 d], -1, 2 ); error(er);
% transform subs
resizVals = repmat( resizVals, [n, 1] );
subs = (subs - zeroPnt) .* resizVals + zeroPnt;
|
github
|
garrickbrazil/SDS-RCNN-master
|
imtranslate.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/imtranslate.m
| 1,183 |
utf_8
|
054727fb31c105414b655c0f938b6ced
|
% Translate an image to subpixel accuracy.
%
% Note that for subplixel accuracy cannot use nearest neighbor interp.
%
% USAGE
% IR = imtranslate( I, dx, dy, [method], [bbox] )
%
% INPUTS
% I - 2D image [converted to double]
% dx - x translation (right)
% dy - y translation (up)
% method - ['linear'] 'nearest', 'linear', 'spline', 'cubic'
% bbox - ['loose'] 'loose' or 'crop'
%
% OUTPUTS
% IR - translated image
%
% EXAMPLE
% load trees;
% XT = imtranslate(X,0,1.5,'bicubic','crop');
% figure(1); im(X,[0 255]); figure(2); im(XT,[0 255]);
%
% See also IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = imtranslate( I, dx, dy, method, bbox )
if( ~isa( I, 'double' ) ); I = double(I); end
if( nargin<4 || isempty(method)); method='linear'; end
if( nargin<5 || isempty(bbox) ); bbox='loose'; end
if( strcmp(method,'bilinear') || strcmp(method,'lin')); method='linear';end
% convert arguments for apply_homography
H = [eye(2) [dy; dx]; 0 0 1];
IR = apply_homography( I, H, method, bbox );
|
github
|
garrickbrazil/SDS-RCNN-master
|
randperm2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/randperm2.m
| 1,398 |
utf_8
|
5007722f3d5f5ba7c0f83f32ef8a3a2c
|
% Returns a random permutation of integers.
%
% randperm2(n) is a random permutation of the integers from 1 to n. For
% example, randperm2(6) might be [2 4 5 6 1 3]. randperm2(n,k) is only
% returns the first k elements of the permuation, so for example
% randperm2(6) might be [2 4]. This is a faster version of randperm.m if
% only need first k<<n elements of the random permutation. Also uses less
% random bits (only k). Note that this is an implementation O(k), versus
% the matlab implementation which is O(nlogn), however, in practice it is
% often slower for k=n because it uses a loop.
%
% USAGE
% p = randperm2( n, k )
%
% INPUTS
% n - permute 1:n
% k - keep only first k outputs
%
% OUTPUTS
% p - k length vector of permutations
%
% EXAMPLE
% randperm2(10,5)
%
% See also RANDPERM
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function p = randperm2( n, k )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n RANDSAMPLE is its '...
'recommended replacement.'],upper(mfilename));
p = randsample( n, k );
%if (nargin<2); k=n; else k = min(k,n); end
% p = 1:n;
% for i=1:k
% r = i + floor( (n-i+1)*rand );
% t = p(r); p(r) = p(i); p(i) = t;
% end
% p = p(1:k);
|
github
|
garrickbrazil/SDS-RCNN-master
|
apply_homography.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/apply_homography.m
| 3,582 |
utf_8
|
9c3ed72d35b1145f41114e6e6135b44f
|
% Applies the homography defined by H on the image I.
%
% Takes the center of the image as the origin, not the top left corner.
% Also, the coordinate system is row/ column format, so H must be also.
%
% The bounding box of the image is set by the BBOX argument, a string that
% can be 'loose' (default) or 'crop'. When BBOX is 'loose', IR includes the
% whole transformed image, which generally is larger than I. When BBOX is
% 'crop' IR is cropped to include only the central portion of the
% transformed image and is the same size as I. Preserves I's type.
%
% USAGE
% IR = apply_homography( I, H, [method], [bbox], [show] )
%
% INPUTS
% I - input black and white image (2D double or unint8 array)
% H - 3x3 nonsingular homography matrix
% method - ['linear'] for interp2 'nearest','linear','spline','cubic'
% bbox - ['loose'] see above for meaning of bbox 'loose','crop')
% show - [0] figure to use for optional display
%
% OUTPUTS
% IR - result of applying H to I.
%
% EXAMPLE
% load trees; I=X;
% R = rotationMatrix( pi/4 ); T = [1; 3]; H = [R T; 0 0 1];
% IR = apply_homography( I, H, [], 'crop', 1 );
%
% See also TEXTURE_MAP, IMROTATE2
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function IR = apply_homography( I, H, method, bbox, show )
if( ndims(I)~=2 ); error('I must a MxN array'); end;
if(any(size(H)~=[3 3])); error('H must be 3 by 3'); end;
if(rank(H)~=3); error('H must be full rank.'); end;
if( nargin<3 || isempty(method)); method='linear'; end;
if( nargin<4 || isempty(bbox)); bbox='loose'; end;
if( nargin<5 || isempty(show)); show=0; end;
classname = class( I );
if(~strcmp(classname,'double')); I = double(I); end
I = padarray(I,[3,3],eps,'both');
siz = size(I);
% set origin to be center of image
rstart = (-siz(1)+1)/2; rend = (siz(1)-1)/2;
cstart = (-siz(2)+1)/2; cend = (siz(2)-1)/2;
% If 'bbox' then get bounds of resulting image. To do this project the
% original points accoring to the homography and see the bounds. Note
% that since a homography maps a quadrilateral to a quadrilateral only
% need to look at where the bounds of the quadrilateral are mapped to.
% If 'same' then simply use the original image bounds.
if (strcmp(bbox,'loose'))
pr = H * [rstart rend rstart rend; cstart cstart cend cend; 1 1 1 1];
row_dest = pr(1,:) ./ pr(3,:); col_dest = pr(2,:) ./ pr(3,:);
minr = floor(min(row_dest(:))); maxr = ceil(max(row_dest(:)));
minc = floor(min(col_dest(:))); maxc = ceil(max(col_dest(:)));
elseif (strcmp(bbox,'crop'))
minr = rstart; maxr = rend;
minc = cstart; maxc = cend;
else
error('illegal value for bbox');
end;
mrows = maxr-minr+1;
ncols = maxc-minc+1;
% apply inverse homography on meshgrid in destination image
[col_dest_grid,row_dest_grid] = meshgrid( minc:maxc, minr:maxr );
pr = inv(H) * [row_dest_grid(:)'; col_dest_grid(:)'; ones(1,mrows*ncols)];
row_sample_locs = pr(1,:) ./ pr(3,:) + (siz(1)+1)/2;
row_sample_locs = reshape(row_sample_locs,mrows,ncols);
col_sample_locs = pr(2,:) ./ pr(3,:) + (siz(2)+1)/2;
col_sample_locs = reshape(col_sample_locs,mrows,ncols);
% now texture map results
IR = interp2( I, col_sample_locs, row_sample_locs, method );
IR(isnan(IR)) = 0;
IR = arraycrop2dims( IR, size(IR)-6 ); %undo extra padding
if(~strcmp(classname,'double')); IR=feval(classname,IR ); end
% optionally show
if ( show)
I = arraycrop2dims( I, size(IR)-2 );
figure(show); clf; im(I);
figure(show+1); clf; im(IR);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
pca_apply.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/pca_apply.m
| 2,427 |
utf_8
|
0831befb6057f8502bc492227455019a
|
% Companion function to pca.
%
% Use pca to retrieve the principal components U and the mean mu from a
% set fo vectors X1 via [U,mu,vars] = pca(X1). Then given a new
% vector x, use y = pca_apply( x, U, mu, vars, k ) to get the first k
% coefficients of x in the space spanned by the columns of U. See pca for
% general information.
%
% This may prove useful:
% siz = size(X); k = 100;
% Uim = reshape( U(:,1:k), [ siz(1:end-1) k ] );
%
% USAGE
% [ Yk, Xhat, avsq, avsqOrig ] = pca_apply( X, U, mu, vars, k )
%
% INPUTS
% X - array for which to get PCA coefficients
% U - [returned by pca] -- see pca
% mu - [returned by pca] -- see pca
% vars - [returned by pca] -- see pca
% k - number of principal coordinates to approximate X with
%
% OUTPUTS
% Yk - first k coordinates of X in column space of U
% Xhat - approximation of X corresponding to Yk
% avsq - measure of squared error normalized to fall between [0,1]
%
% EXAMPLE
%
% See also PCA, PCA_VISUALIZE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function [Yk,Xhat,avsq,avsqOrig] = pca_apply(X,U,mu,vars,k) %#ok<INUSL>
siz = size(X); nd = ndims(X); [N,r] = size(U);
if(N==prod(siz) && ~(nd==2 && siz(2)==1)); siz=[siz, 1]; nd=nd+1; end
inds = {':'}; inds = inds(:,ones(1,nd-1));
d= prod(siz(1:end-1));
% some error checking
if(d~=N); error('incorrect size for X or U'); end
if(isa(X,'uint8')); X = double(X); end
if( k>r )
warning(['Only ' int2str(r) '<k comp. available.']); %#ok<WNTAG>
k=r;
end
% subtract mean, then flatten X
Xorig = X;
murep = mu( inds{:}, ones(1,siz(end)));
X = X - murep;
X = reshape(X, d, [] );
% Find Yk, the first k coefficients of X in the new basis
k = min( r, k );
Uk = U(:,1:k);
Yk = Uk' * X;
% calculate Xhat - the approx of X using the first k princ components
if( nargout>1 )
Xhat = Uk * Yk;
Xhat = reshape( Xhat, siz );
Xhat = Xhat + murep;
end
% caclulate average value of (Xhat-Xorig).^2 compared to average value
% of X.^2, where X is Xorig without the mean. This is equivalent to
% what fraction of the variance is captured by Xhat.
if( nargout>2 )
avsq = Xhat - Xorig;
avsq = dot(avsq(:),avsq(:));
avsqOrig = dot(X(:),X(:));
if (nargout==3)
avsq = avsq / avsqOrig;
end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
mode2.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/deprecated/mode2.m
| 731 |
utf_8
|
5c9321ef4b610b4f4a2d43902a68838e
|
% Returns the mode of a vector.
%
% Was mode not part of Matlab before?
%
% USAGE
% y = mode2( x )
%
% INPUTS
% x - vector of integers
%
% OUTPUTS
% y - mode
%
% EXAMPLE
% x = randint2( 1, 10, [1 3] )
% mode(x), mode2( x )
%
% See also MODE
% Piotr's Image&Video Toolbox Version 1.5
% Written and maintained by Piotr Dollar pdollar-at-cs.ucsd.edu
% Please email me if you find bugs, or have suggestions or questions!
function y = mode2( x )
wid = sprintf('Images:%s:obsoleteFunction',mfilename);
warning(wid,[ '%s is obsolete in Piotr''s toolbox.\n MODE is its '...
'recommended replacement.'],upper(mfilename));
y = mode( x );
% [b,i,j] = unique(x);
% [ mval, ind ] = max(hist(j,length(b)));
% y = b(ind);
|
github
|
garrickbrazil/SDS-RCNN-master
|
savefig.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/external/other/savefig.m
| 13,459 |
utf_8
|
2b8463f9b01ceb743e440d8fb5755829
|
function savefig(fname, varargin)
% Usage: savefig(filename, fighdl, options)
%
% Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure.
% It saves an eps of the figure and the uses Ghostscript to convert to the other formats.
% The result is a cropped, clean picture. There are options for using rgb or cmyk colours,
% or grayscale. You can also choose the resolution.
%
% The advantage of savefig is that there is very little empty space around the figure in the
% resulting files, you can export to more than one format at once, and Ghostscript generates
% trouble-free files.
%
% If you find any errors, please let me know! (peder at axensten dot se)
%
% filename: File name without suffix.
%
% fighdl: (default: gcf) Integer handle to figure.
%
% options: (default: '-r300', '-lossless', '-rgb') You can define your own
% defaults in a global variable savefig_defaults, if you want to, i.e.
% savefig_defaults= {'-r200','-gray'};.
% 'eps': Output in Encapsulated Post Script (no preview yet).
% 'pdf': Output in (Adobe) Portable Document Format.
% 'png': Output in Portable Network Graphics.
% 'jpeg': Output in Joint Photographic Experts Group format.
% 'tiff': Output in Tagged Image File Format (no compression: huge files!).
% '-rgb': Output in rgb colours.
% '-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used).
% '-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used).
% '-fonts': Include fonts in eps or pdf. Includes only the subset needed.
% '-lossless': Use lossless compression, works on most formats. same as '-c0', below.
% '-c<float>': Set compression for non-indexed bitmaps in PDFs -
% 0: lossless; 0.1: high quality; 0.5: medium; 1: high compression.
% '-r<integer>': Set resolution.
% '-crop': Removes points and line segments outside the viewing area -- permanently.
% Only use this on figures where many points and/or line segments are outside
% the area zoomed in to. This option will result in smaller vector files (has no
% effect on pixel files).
% '-dbg': Displays gs command line(s).
%
% EXAMPLE:
% savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250');
% Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi,
% with high quality lossy compression.
%
% REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop'
% must be supported. I think version 7.32 or newer is ok.
%
% HISTORY:
% Version 1.0, 2006-04-20.
% Version 1.1, 2006-04-27:
% - No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead!
% Version 1.2, 2006-05-02:
% - Added a '-dbg' option (see options, above).
% - Now looks for a global variable 'savefig_defaults' (see options, above).
% - More detailed Ghostscript options (user will not really notice).
% - Warns when there is no device for a file-type/color-model combination.
% Version 1.3, 2006-06-06:
% - Added a check to see if there actually is a figure handle.
% - Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
% - Now compatible with Ghostscript 8.54, released 2006-06-01.
% Version 1.4, 2006-07-20:
% - Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
% - Added an option '-hard' that don't do anti-aliasing on pixel graphics.
% Version 1.5, 2006-07-27:
% - Fixed a bug when calling with a figure handle argument.
% Version 1.6, 2006-07-28:
% - Added a crop option, see above.
% Version 1.7, 2007-03-31:
% - Fixed bug: calling print with invalid renderer value '-none'.
% - Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.
% Version 1.8, 2008-01-03:
% - Added MacIntel: 'MACI'.
% - Added 64bit PC (I think, can't test it myself).
% - Added option '-nointerpolate' (use it to prevent blurring of pixelated).
% - Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'.
% - Fixed the gs 8.57 warning on UseCIEColor (it's now set).
% - Added '-gray' for pdf, but gs 8.56 or newer is needed.
% - Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed.
% Version 1.9, 2008-07-27:
% - Added lossless compression, see option '-lossless', above. Works on most formats.
% - Added lossy compression, see options '-c<float>...', above. Works on 'pdf'.
% Thanks to Olly Woodford for idea and implementation!
% - Removed option '-nointerpolate' -- now savefig never interpolates.
% - Fixed a few small bugs and removed some mlint comments.
% Version 2.0, 2008-11-07:
% - Added the possibility to include fonts into eps or pdf.
%
% TO DO: (Need Ghostscript support for these, so don't expect anything soon...)
% - svg output.
% - '-cmyk' for 'jpeg' and 'png'.
% - Preview in 'eps'.
% - Embedded vector fonts, not bitmap, in 'eps'.
%
% Copyright (C) Peder Axensten (peder at axensten dot se), 2006.
% KEYWORDS: eps, pdf, jpg, jpeg, png, tiff, eps2pdf, epstopdf, ghostscript
%
% INSPIRATION: eps2pdf (5782), eps2xxx (6858)
%
% REQUIREMENTS: Works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
op_dbg= false; % Default value.
% Compression
compr= [' -dUseFlateCompression=true -dLZWEncodePages=true -dCompatibilityLevel=1.6' ...
' -dAutoFilterColorImages=false -dAutoFilterGrayImages=false ' ...
' -dColorImageFilter=%s -dGrayImageFilter=%s']; % Compression.
lossless= sprintf (compr, '/FlateEncode', '/FlateEncode');
lossy= sprintf (compr, '/DCTEncode', '/DCTEncode' );
lossy= [lossy ' -c ".setpdfwrite << /ColorImageDict << /QFactor %g ' ...
'/Blend 1 /HSample [%s] /VSample [%s] >> >> setdistillerparams"'];
% Create gs command.
cmdEnd= ' -sDEVICE=%s -sOutputFile="%s"'; % Essential.
epsCmd= '';
epsCmd= [epsCmd ' -dSubsetFonts=true -dNOPLATFONTS']; % Future support?
epsCmd= [epsCmd ' -dUseCIEColor=true -dColorConversionStrategy=/UseDeviceIndependentColor'];
epsCmd= [epsCmd ' -dProcessColorModel=/%s']; % Color conversion.
pdfCmd= [epsCmd ' -dAntiAliasColorImages=false' cmdEnd];
epsCmd= [epsCmd cmdEnd];
% Get file name.
if((nargin < 1) || isempty(fname) || ~ischar(fname)) % Check file name.
error('No file name specified.');
end
[pathstr, namestr] = fileparts(fname);
if(isempty(pathstr)), fname= fullfile(cd, namestr); end
% Get handle.
fighdl= get(0, 'CurrentFigure'); % See gcf. % Get figure handle.
if((nargin >= 2) && (numel(varargin{1}) == 1) && isnumeric(varargin{1}))
fighdl= varargin{1};
varargin= {varargin{2:end}};
end
if(isempty(fighdl)), error('There is no figure to save!?'); end
set(fighdl, 'Units', 'centimeters') % Set paper stuff.
sz= get(fighdl, 'Position');
sz(1:2)= 0;
set(fighdl, 'PaperUnits', 'centimeters', 'PaperSize', sz(3:4), 'PaperPosition', sz);
% Set up the various devices.
% Those commented out are not yet supported by gs (nor by savefig).
% pdf-cmyk works due to the Matlab '-cmyk' export being carried over from eps to pdf.
device.eps.rgb= sprintf(epsCmd, 'DeviceRGB', 'epswrite', [fname '.eps']);
device.jpeg.rgb= sprintf(cmdEnd, 'jpeg', [fname '.jpeg']);
% device.jpeg.cmyk= sprintf(cmdEnd, 'jpegcmyk', [fname '.jpeg']);
device.jpeg.gray= sprintf(cmdEnd, 'jpeggray', [fname '.jpeg']);
device.pdf.rgb= sprintf(pdfCmd, 'DeviceRGB', 'pdfwrite', [fname '.pdf']);
device.pdf.cmyk= sprintf(pdfCmd, 'DeviceCMYK', 'pdfwrite', [fname '.pdf']);
device.pdf.gray= sprintf(pdfCmd, 'DeviceGray', 'pdfwrite', [fname '.pdf']);
device.png.rgb= sprintf(cmdEnd, 'png16m', [fname '.png']);
% device.png.cmyk= sprintf(cmdEnd, 'png???', [fname '.png']);
device.png.gray= sprintf(cmdEnd, 'pnggray', [fname '.png']);
device.tiff.rgb= sprintf(cmdEnd, 'tiff24nc', [fname '.tiff']);
device.tiff.cmyk= sprintf(cmdEnd, 'tiff32nc', [fname '.tiff']);
device.tiff.gray= sprintf(cmdEnd, 'tiffgray', [fname '.tiff']);
% Get options.
global savefig_defaults; % Add global defaults.
if( iscellstr(savefig_defaults)), varargin= {savefig_defaults{:}, varargin{:}};
elseif(ischar(savefig_defaults)), varargin= {savefig_defaults, varargin{:}};
end
varargin= {'-r300', '-lossless', '-rgb', varargin{:}}; % Add defaults.
res= '';
types= {};
fonts= 'false';
crop= false;
for n= 1:length(varargin) % Read options.
if(ischar(varargin{n}))
switch(lower(varargin{n}))
case {'eps','jpeg','pdf','png','tiff'}, types{end+1}= lower(varargin{n});
case '-rgb', color= 'rgb'; deps= {'-depsc2'};
case '-cmyk', color= 'cmyk'; deps= {'-depsc2', '-cmyk'};
case '-gray', color= 'gray'; deps= {'-deps2'};
case '-fonts', fonts= 'true';
case '-lossless', comp= 0;
case '-crop', crop= true;
case '-dbg', op_dbg= true;
otherwise
if(regexp(varargin{n}, '^\-r[0-9]+$')), res= varargin{n};
elseif(regexp(varargin{n}, '^\-c[0-9.]+$')), comp= str2double(varargin{n}(3:end));
else warning('pax:savefig:inputError', 'Unknown option in argument: ''%s''.', varargin{n});
end
end
else
warning('pax:savefig:inputError', 'Wrong type of argument: ''%s''.', class(varargin{n}));
end
end
types= unique(types);
if(isempty(types)), error('No output format given.'); end
if (comp == 0) % Lossless compression
gsCompr= lossless;
elseif (comp <= 0.1) % High quality lossy
gsCompr= sprintf(lossy, comp, '1 1 1 1', '1 1 1 1');
else % Normal lossy
gsCompr= sprintf(lossy, comp, '2 1 1 2', '2 1 1 2');
end
% Generate the gs command.
switch(computer) % Get gs command.
case {'MAC','MACI'}, gs= '/usr/local/bin/gs';
case {'PCWIN'}, gs= 'gswin32c.exe';
case {'PCWIN64'}, gs= 'gswin64c.exe';
otherwise, gs= 'gs';
end
gs= [gs ' -q -dNOPAUSE -dBATCH -dEPSCrop']; % Essential.
gs= [gs ' -dPDFSETTINGS=/prepress -dEmbedAllFonts=' fonts]; % Must be first?
gs= [gs ' -dUseFlateCompression=true']; % Useful stuff.
gs= [gs ' -dAutoRotatePages=/None']; % Probably good.
gs= [gs ' -dHaveTrueTypes']; % Probably good.
gs= [gs ' ' res]; % Add resolution to cmd.
if(crop && ismember(types, {'eps', 'pdf'})) % Crop the figure.
fighdl= do_crop(fighdl);
end
% Output eps from Matlab.
renderer= ['-' lower(get(fighdl, 'Renderer'))]; % Use same as in figure.
if(strcmpi(renderer, '-none')), renderer= '-painters'; end % We need a valid renderer.
deps = [deps '-loose']; % added by PPD seems to help w cropping in matlab 2014b :(
print(fighdl, deps{:}, '-noui', renderer, res, [fname '-temp']); % Output the eps.
% Convert to other formats.
for n= 1:length(types) % Output them.
if(isfield(device.(types{n}), color))
cmd= device.(types{n}).(color); % Colour model exists.
else
cmd= device.(types{n}).rgb; % Use alternative.
if(~strcmp(types{n}, 'eps')) % It works anyways for eps (VERY SHAKY!).
warning('pax:savefig:deviceError', ...
'No device for %s using %s. Using rgb instead.', types{n}, color);
end
end
cmp= lossless;
if (strcmp(types{n}, 'pdf')), cmp= gsCompr; end % Lossy compr only for pdf.
if (strcmp(types{n}, 'eps')), cmp= ''; end % eps can't use lossless.
cmd= sprintf('%s %s %s -f "%s-temp.eps"', gs, cmd, cmp, fname);% Add up.
status= system(cmd); % Run Ghostscript.
if (op_dbg || status), display (cmd), end
end
delete([fname '-temp.eps']); % Clean up.
end
function fig= do_crop(fig)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Remove line segments that are outside the view.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
haxes= findobj(fig, 'Type', 'axes', '-and', 'Tag', '');
for n=1:length(haxes)
xl= get(haxes(n), 'XLim');
yl= get(haxes(n), 'YLim');
lines= findobj(haxes(n), 'Type', 'line');
for m=1:length(lines)
x= get(lines(m), 'XData');
y= get(lines(m), 'YData');
inx= (xl(1) <= x) & (x <= xl(2)); % Within the x borders.
iny= (yl(1) <= y) & (y <= yl(2)); % Within the y borders.
keep= inx & iny; % Within the box.
if(~strcmp(get(lines(m), 'LineStyle'), 'none'))
crossx= ((x(1:end-1) < xl(1)) & (xl(1) < x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) < xl(2)) & (xl(2) < x(2:end))) ... % Crossing border x2.
| ((x(1:end-1) > xl(1)) & (xl(1) > x(2:end))) ... % Crossing border x1.
| ((x(1:end-1) > xl(2)) & (xl(2) > x(2:end))); % Crossing border x2.
crossy= ((y(1:end-1) < yl(1)) & (yl(1) < y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) < yl(2)) & (yl(2) < y(2:end))) ... % Crossing border y2.
| ((y(1:end-1) > yl(1)) & (yl(1) > y(2:end))) ... % Crossing border y1.
| ((y(1:end-1) > yl(2)) & (yl(2) > y(2:end))); % Crossing border y2.
crossp= [( (crossx & iny(1:end-1) & iny(2:end)) ... % Crossing a x border within y limits.
| (crossy & inx(1:end-1) & inx(2:end)) ... % Crossing a y border within x limits.
| crossx & crossy ... % Crossing a x and a y border (corner).
), false ...
];
crossp(2:end)= crossp(2:end) | crossp(1:end-1); % Add line segment's secont end point.
keep= keep | crossp;
end
set(lines(m), 'XData', x(keep))
set(lines(m), 'YData', y(keep))
end
end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
dirSynch.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/matlab/dirSynch.m
| 4,570 |
utf_8
|
d288299d31d15f1804183206d0aa0227
|
function dirSynch( root1, root2, showOnly, flag, ignDate )
% Synchronize two directory trees (or show differences between them).
%
% If a file or directory 'name' is found in both tree1 and tree2:
% 1) if 'name' is a file in both the pair is considered the same if they
% have identical size and identical datestamp (or if ignDate=1).
% 2) if 'name' is a directory in both the dirs are searched recursively.
% 3) if 'name' is a dir in root1 and a file in root2 (or vice-versa)
% synchronization cannot proceed (an error is thrown).
% If 'name' is found only in root1 or root2 it's a difference between them.
%
% The parameter flag controls how synchronization occurs:
% flag==0: neither tree1 nor tree2 has preference (newer file is kept)
% flag==1: tree2 is altered to reflect tree1 (tree1 is unchanged)
% flag==2: tree1 is altered to reflect tree2 (tree2 is unchanged)
% Run with showOnly=1 and different values of flag to see its effect.
%
% By default showOnly==1. If showOnly, displays a list of actions that need
% to be performed in order to synchronize the two directory trees, but does
% not actually perform the actions. It is highly recommended to run
% dirSynch first with showOnly=1 before running it with showOnly=0.
%
% USAGE
% dirSynch( root1, root2, [showOnly], [flag], [ignDate] )
%
% INPUTS
% root1 - root directory of tree1
% root2 - root directory of tree2
% showOnly - [1] show but do NOT perform actions
% flag - [0] 0: synchronize; 1: set root2=root1; 2: set root1==root2
% ignDate - [0] if true considers two files same even if have diff dates
%
% OUTPUTS
% dirSynch( 'c:\toolbox', 'c:\toolbox-old', 1 )
%
% EXAMPLE
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 2.10
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if(nargin<3 || isempty(showOnly)), showOnly=1; end;
if(nargin<4 || isempty(flag)), flag=0; end;
if(nargin<5 || isempty(ignDate)), ignDate=0; end;
% get differences between root1/root2 and loop over them
D = dirDiff( root1, root2, ignDate );
roots={root1,root2}; ticId = ticStatus;
for i=1:length(D)
% get action
if( flag==1 )
if( D(i).in1 ), act=1; src1=1; else act=0; src1=2; end
elseif( flag==2 )
if( D(i).in2 ), act=1; src1=2; else act=0; src1=1; end
else
act=1;
if(D(i).in1 && D(i).in2)
if( D(i).new1 ), src1=1; else src1=2; end
else
if( D(i).in1 ), src1=1; else src1=2; end
end
end
src2=mod(src1,2)+1;
% perform action
if( act==1 )
if( showOnly )
disp(['COPY ' int2str(src1) '->' int2str(src2) ': ' D(i).name]);
else
copyfile( [roots{src1} D(i).name], [roots{src2} D(i).name], 'f' );
end;
else
if( showOnly )
disp(['DEL in ' int2str(src1) ': ' D(i).name]);
else
fName = [roots{src1} D(i).name];
if(D(i).isdir), rmdir(fName,'s'); else delete(fName); end
end
end
if(~showOnly), tocStatus( ticId, i/length(D) ); end;
end
end
function D = dirDiff( root1, root2, ignDate )
% get differences from root1 to root2
D1 = dirDiff1( root1, root2, ignDate, '/' );
% get differences from root2 to root1
D2 = dirDiff1( root2, root1, ignDate, '/' );
% remove duplicates (arbitrarily from D2)
D2=D2(~([D2.in1] & [D2.in2]));
% swap 1 and 2 in D2
for i=1:length(D2),
D2(i).in1=0; D2(i).in2=1; D2(i).new1=~D2(i).new1;
end
% merge
D = [D1 D2];
end
function D = dirDiff1( root1, root2, ignDate, subdir )
if(root1(end)~='/'), root1(end+1)='/'; end
if(root2(end)~='/'), root2(end+1)='/'; end
if(subdir(end)~='/'), subdir(end+1)='/'; end
fs1=dir([root1 subdir]); fs2=dir([root2 subdir]);
D=struct('name',0,'isdir',0,'in1',0,'in2',0,'new1',0);
D=repmat(D,[1 length(fs1)]); n=0; names2={fs2.name}; Dsub=[];
for i1=1:length( fs1 )
name=fs1(i1).name; isdir=fs1(i1).isdir;
if( any(strcmp(name,{'.','..'})) ), continue; end;
i2 = find(strcmp(name,names2));
if(~isempty(i2) && isdir)
% cannot handle this condition
if(~fs2(i2).isdir), disp([root1 subdir name]); assert(false); end;
% recurse and record possible differences
Dsub=[Dsub dirDiff1(root1,root2,ignDate,[subdir name])]; %#ok<AGROW>
elseif( ~isempty(i2) && fs1(i1).bytes==fs2(i2).bytes && ...
(ignDate || fs1(i1).datenum==fs2(i2).datenum))
% nothing to do - files are same
continue;
else
% record differences
n=n+1;
D(n).name=[subdir name]; D(n).isdir=isdir;
D(n).in1=1; D(n).in2=~isempty(i2);
D(n).new1 = ~D(n).in2 || (fs1(i1).datenum>fs2(i2).datenum);
end
end
D = [D(1:n) Dsub];
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
plotRoc.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/matlab/plotRoc.m
| 5,212 |
utf_8
|
008f9c63073c6400c4960e9e213c47e5
|
function [h,miss,stds] = plotRoc( D, varargin )
% Function for display of rocs (receiver operator characteristic curves).
%
% Display roc curves. Consistent usage ensures uniform look for rocs. The
% input D should have n rows, each of which is of the form:
% D = [falsePosRate truePosRate]
% D is generated, for example, by scanning a detection threshold over n
% values from 0 (so first entry is [1 1]) to 1 (so last entry is [0 0]).
% Alternatively D can be a cell vector of rocs, in which case an average
% ROC will be shown with error bars. Plots missRate (which is just 1 minus
% the truePosRate) on the y-axis versus the falsePosRate on the x-axis.
%
% USAGE
% [h,miss,stds] = plotRoc( D, prm )
%
% INPUTS
% D - [nx2] n data points along roc [falsePosRate truePosRate]
% typically ranges from [1 1] to [0 0] (or may be reversed)
% prm - [] param struct
% .color - ['g'] color for curve
% .lineSt - ['-'] linestyle (see LineSpec)
% .lineWd - [4] curve width
% .logx - [0] use logarithmic scale for x-axis
% .logy - [0] use logarithmic scale for y-axis
% .marker - [''] marker type (see LineSpec)
% .mrkrSiz - [12] marker size
% .nMarker - [5] number of markers (regularly spaced) to display
% .lims - [0 1 0 1] axes limits
% .smooth - [0] if T compute lower envelop of roc to smooth staircase
% .fpTarget - [] return miss rates at given fp values (and draw lines)
% .xLbl - ['false positive rate'] label for x-axis
% .yLbl - ['miss rate'] label for y-axis
%
% OUTPUTS
% h - plot handle for use in legend only
% miss - average miss rates at fpTarget reference values
% stds - standard deviation of miss rates at fpTarget reference values
%
% EXAMPLE
% k=2; x=0:.0001:1; data1 = [1-x; (1-x.^k).^(1/k)]';
% k=3; x=0:.0001:1; data2 = [1-x; (1-x.^k).^(1/k)]';
% hs(1)=plotRoc(data1,struct('color','g','marker','s'));
% hs(2)=plotRoc(data2,struct('color','b','lineSt','--'));
% legend( hs, {'roc1','roc2'} ); xlabel('fp'); ylabel('fn');
%
% See also
%
% Piotr's Computer Vision Matlab Toolbox Version 3.02
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% get params
[color,lineSt,lineWd,logx,logy,marker,mrkrSiz,nMarker,lims,smooth, ...
fpTarget,xLbl,yLbl] = getPrmDflt( varargin, {'color' 'g' 'lineSt' '-' ...
'lineWd' 4 'logx' 0 'logy' 0 'marker' '' 'mrkrSiz' 12 'nMarker' 5 ...
'lims' [] 'smooth' 0 'fpTarget' [] 'xLbl' 'false positive rate' ...
'yLbl' 'miss rate' } );
if( isempty(lims) ); lims=[logx*1e-5 1 logy*1e-5 1]; end
% ensure descending fp rate, change to miss rate, optionally 'nicefy' roc
if(~iscell(D)), D={D}; end; nD=length(D);
for j=1:nD, assert(size(D{j},2)==2); end
for j=1:nD, if(D{j}(1,2)<D{j}(end,2)), D{j}=flipud(D{j}); end; end
for j=1:nD, D{j}(:,2)=1-D{j}(:,2); assert(all(D{j}(:,2)>=0)); end
if(smooth), for j=1:nD, D{j}=smoothRoc(D{j}); end; end
% plot: (1) h for legend only, (2) markers, (3) error bars, (4) roc curves
hold on; axis(lims); xlabel(xLbl); ylabel(yLbl);
prmMrkr = {'MarkerSize',mrkrSiz,'MarkerFaceColor',color};
prmClr={'Color',color}; prmPlot = [prmClr,{'LineWidth',lineWd}];
h = plot( 2, 0, [lineSt marker], prmMrkr{:}, prmPlot{:} ); %(1)
DQ = quantizeRocs( D, nMarker, logx, lims ); DQm=mean(DQ,3);
if(~isempty(marker))
plot(DQm(:,1),DQm(:,2),marker,prmClr{:},prmMrkr{:} ); end %(2)
if(nD>1), DQs=std(DQ,0,3);
errorbar(DQm(:,1),DQm(:,2),DQs(:,2),'.',prmClr{:}); end %(3)
if(nD==1), DQ=D{1}; else DQ=quantizeRocs(D,100,logx,lims); end
DQm = mean(DQ,3); plot( DQm(:,1), DQm(:,2), lineSt, prmPlot{:} ); %(4)
% plot line at given fp rate
m=length(fpTarget); miss=zeros(1,m); stds=miss;
if( m>0 )
assert( min(DQm(:,1))<=min(fpTarget) ); DQs=std(DQ,0,3);
for i=1:m, j=find(DQm(:,1)<=fpTarget(i)); j=j(1);
miss(i)=DQm(j,2); stds(i)=DQs(j,2); end
fp=min(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
fp=max(fpTarget); plot([fp fp],lims(3:4),'Color',.7*[1 1 1]);
end
% set log axes
if( logx==1 )
ticks=10.^(-8:8);
set(gca,'XScale','log','XTick',ticks);
end
if( logy==1 )
ticks=[.001 .002 .005 .01 .02 .05 .1 .2 .5 1];
set(gca,'YScale','log','YTick',ticks);
end
if( logx==1 || logy==1 ), grid on;
set(gca,'XMinorGrid','off','XMinorTic','off');
set(gca,'YMinorGrid','off','YMinorTic','off');
end
end
function DQ = quantizeRocs( Ds, nPnts, logx, lims )
% estimate miss rate at each target fp rate
nD=length(Ds); DQ=zeros(nPnts,2,nD);
if(logx==1), fps=logspace(log10(lims(1)),log10(lims(2)),nPnts);
else fps=linspace(lims(1),lims(2),nPnts); end; fps=flipud(fps');
for j=1:nD, D=[Ds{j}; 0 1]; k=1; fp=D(k,1);
for i=1:nPnts
while( k<size(D,1) && fp>=fps(i) ), k=k+1; fp=D(k,1); end
k0=max(k-1,1); fp0=D(k0,1); assert(fp0>=fp);
if(fp0==fp), r=.5; else r=(fps(i)-fp)/(fp0-fp); end
DQ(i,1,j)=fps(i); DQ(i,2,j)=r*D(k0,2)+(1-r)*D(k,2);
end
end
end
function D1 = smoothRoc( D )
D1 = zeros(size(D));
n = size(D,1); cnt=0;
for i=1:n
isAnkle = (i==1) || (i==n);
if( ~isAnkle )
dP=D1(cnt,:); dC=D(i,:); dN=D(i+1,:);
isAnkle = (dC(1)~=dP(1)) && (dC(2)~=dN(2));
end
if(isAnkle); cnt=cnt+1; D1(cnt,:)=D(i,:); end
end
D1=D1(1:cnt,:);
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
simpleCache.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/matlab/simpleCache.m
| 4,098 |
utf_8
|
92df86b0b7e919c9a26388e598e4d370
|
function varargout = simpleCache( op, cache, varargin )
% A simple cache that can be used to store results of computations.
%
% Can save and retrieve arbitrary values using a vector (includnig char
% vectors) as a key. Especially useful if a function must perform heavy
% computation but is often called with the same inputs (for which it will
% give the same outputs). Note that the current implementation does a
% linear search for the key (a more refined implementation would use a hash
% table), so it is not meant for large scale usage.
%
% To use inside a function, make the cache persistent:
% persistent cache; if( isempty(cache) ) cache=simpleCache('init'); end;
% The following line, when placed inside a function, means the cache will
% stay in memory until the matlab environment changes. For an example
% usage see maskGaussians.
%
% USAGE - 'init': initialize a cache object
% cache = simpleCache('init');
%
% USAGE - 'put': put something in cache. key must be a numeric vector
% cache = simpleCache( 'put', cache, key, val );
%
% USAGE - 'get': retrieve from cache. found==1 if obj was found
% [found,val] = simpleCache( 'get', cache, key );
%
% USAGE - 'remove': free key
% [cache,found] = simpleCache( 'remove', cache, key );
%
% INPUTS
% op - 'init', 'put', 'get', 'remove'
% cache - the cache object being operated on
% varargin - see USAGE above
%
% OUTPUTS
% varargout - see USAGE above
%
% EXAMPLE
% cache = simpleCache('init');
% hellokey=rand(1,3); worldkey=rand(1,11);
% cache = simpleCache( 'put', cache, hellokey, 'hello' );
% cache = simpleCache( 'put', cache, worldkey, 'world' );
% [f,v]=simpleCache( 'get', cache, hellokey ); disp(v);
% [f,v]=simpleCache( 'get', cache, worldkey ); disp(v);
%
% See also PERSISTENT, MASKGAUSSIANS
%
% Piotr's Computer Vision Matlab Toolbox Version 2.61
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
switch op
case 'init' % init a cache
cacheSiz = 8;
cache.freeinds = 1:cacheSiz;
cache.keyns = -ones(1,cacheSiz);
cache.keys = cell(1,cacheSiz);
cache.vals = cell(1,cacheSiz);
varargout = {cache};
case 'put' % a put operation
key=varargin{1}; val=varargin{2};
cache = cacheput( cache, key, val );
varargout = {cache};
case 'get' % a get operation
key=varargin{1};
[ind,val] = cacheget( cache, key );
found = ind>0;
varargout = {found,val};
case 'remove' % a remove operation
key=varargin{1};
[cache,found] = cacheremove( cache, key );
varargout = {cache,found};
otherwise
error('Unknown cache operation: %s',op);
end
end
function cache = cachegrow( cache )
% double cache size
cacheSiz = length( cache.keyns );
if( cacheSiz>64 ) % warn if getting big
warning(['doubling cache size to: ' int2str2(cacheSiz*2)]);%#ok<WNTAG>
end
cache.freeinds = [cache.freeinds (cacheSiz+1):(2*cacheSiz)];
cache.keyns = [cache.keyns -ones(1,cacheSiz)];
cache.keys = [cache.keys cell(1,cacheSiz)];
cache.vals = [cache.vals cell(1,cacheSiz)];
end
function cache = cacheput( cache, key, val )
% put something into the cache
% get location to place
ind = cacheget( cache, key ); % see if already in cache
if( ind==-1 )
if( isempty( cache.freeinds ) )
cache = cachegrow( cache ); %grow cache
end
ind = cache.freeinds(1); % get new cache loc
cache.freeinds = cache.freeinds(2:end);
end
% now simply place in ind
cache.keyns(ind) = length(key);
cache.keys{ind} = key;
cache.vals{ind} = val;
end
function [ind,val] = cacheget( cache, key )
% get cache element, or fail
cacheSiz = length( cache.keyns );
keyn = length( key );
for i=1:cacheSiz
if(keyn==cache.keyns(i) && all(key==cache.keys{i}))
val = cache.vals{i}; ind = i; return; end
end
ind=-1; val=-1;
end
function [cache,found] = cacheremove( cache, key )
% get cache element, or fail
ind = cacheget( cache, key );
found = ind>0;
if( found )
cache.freeinds = [ind cache.freeinds];
cache.keyns(ind) = -1;
cache.keys{ind} = [];
cache.vals{ind} = [];
end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
tpsInterpolate.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/matlab/tpsInterpolate.m
| 1,646 |
utf_8
|
d3bd3a26d048f32cfdc17884ccae6d8c
|
function [xsR,ysR] = tpsInterpolate( warp, xs, ys, show )
% Apply warp (obtained by tpsGetWarp) to a set of new points.
%
% USAGE
% [xsR,ysR] = tpsInterpolate( warp, xs, ys, [show] )
%
% INPUTS
% warp - [see tpsGetWarp] bookstein warping parameters
% xs, ys - points to apply warp to
% show - [1] will display results in figure(show)
%
% OUTPUTS
% xsR, ysR - result of warp applied to xs, ys
%
% EXAMPLE
%
% See also TPSGETWARP
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<4 || isempty(show)); show = 1; end
wx = warp.wx; affinex = warp.affinex;
wy = warp.wy; affiney = warp.affiney;
xsS = warp.xsS; ysS = warp.ysS;
xsD = warp.xsD; ysD = warp.ysD;
% interpolate points (xs,ys)
xsR = f( wx, affinex, xsS, ysS, xs(:)', ys(:)' );
ysR = f( wy, affiney, xsS, ysS, xs(:)', ys(:)' );
% optionally show points (xsR, ysR)
if( show )
figure(show);
subplot(2,1,1); plot( xs, ys, '.', 'color', [0 0 1] );
hold('on'); plot( xsS, ysS, '+' ); hold('off');
subplot(2,1,2); plot( xsR, ysR, '.' );
hold('on'); plot( xsD, ysD, '+' ); hold('off');
end
function zs = f( w, aff, xsS, ysS, xs, ys )
% find f(x,y) for xs and ys given W and original points
n = size(w,1); ns = size(xs,2);
delXs = xs'*ones(1,n) - ones(ns,1)*xsS;
delYs = ys'*ones(1,n) - ones(ns,1)*ysS;
distSq = (delXs .* delXs + delYs .* delYs);
distSq = distSq + eye(size(distSq)) + eps;
U = distSq .* log( distSq ); U( isnan(U) )=0;
zs = aff(1)*ones(ns,1)+aff(2)*xs'+aff(3)*ys';
zs = zs + sum((U.*(ones(ns,1)*w')),2);
|
github
|
garrickbrazil/SDS-RCNN-master
|
checkNumArgs.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/matlab/checkNumArgs.m
| 3,796 |
utf_8
|
726c125c7dc994c4989c0e53ad4be747
|
function [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag )
% Helper utility for checking numeric vector arguments.
%
% Runs a number of tests on the numeric array x. Tests to see if x has all
% integer values, all positive values, and so on, depending on the values
% for intFlag and signFlag. Also tests to see if the size of x matches siz
% (unless siz==[]). If x is a scalar, x is converted to a array simply by
% creating a matrix of size siz with x in each entry. This is why the
% function returns x. siz=M is equivalent to siz=[M M]. If x does not
% satisfy some criteria, an error message is returned in er. If x satisfied
% all the criteria er=''. Note that error('') has no effect, so can use:
% [ x, er ] = checkNumArgs( x, ... ); error(er);
% which will throw an error only if something was wrong with x.
%
% USAGE
% [ x, er ] = checkNumArgs( x, siz, intFlag, signFlag )
%
% INPUTS
% x - numeric array
% siz - []: does not test size of x
% - [if not []]: intended size for x
% intFlag - -1: no need for integer x
% 0: error if non integer x
% 1: error if non odd integers
% 2: error if non even integers
% signFlag - -2: entires of x must be strictly negative
% -1: entires of x must be negative
% 0: no contstraints on sign of entries in x
% 1: entires of x must be positive
% 2: entires of x must be strictly positive
%
% OUTPUTS
% x - if x was a scalar it may have been replicated into a matrix
% er - contains error msg if anything was wrong with x
%
% EXAMPLE
% a=1; [a, er]=checkNumArgs( a, [1 3], 2, 0 ); a, error(er)
%
% See also NARGCHK
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
xname = inputname(1); er='';
if( isempty(siz) ); siz = size(x); end;
if( length(siz)==1 ); siz=[siz siz]; end;
% first check that x is numeric
if( ~isnumeric(x) ); er = [xname ' not numeric']; return; end;
% if x is a scalar, simply replicate it.
xorig = x; if( length(x)==1); x = x(ones(siz)); end;
% regardless, must have same number of x as n
if( length(siz)~=ndims(x) || ~all(size(x)==siz) )
er = ['has size = [' num2str(size(x)) '], '];
er = [er 'which is not the required size of [' num2str(siz) ']'];
er = createErrMsg( xname, xorig, er ); return;
end
% check that x are the right type of integers (unless intFlag==-1)
switch intFlag
case 0
if( ~all(mod(x,1)==0))
er = 'must have integer entries';
er = createErrMsg( xname, xorig, er); return;
end;
case 1
if( ~all(mod(x,2)==1))
er = 'must have odd integer entries';
er = createErrMsg( xname, xorig, er); return;
end;
case 2
if( ~all(mod(x,2)==0))
er = 'must have even integer entries';
er = createErrMsg( xname, xorig, er ); return;
end;
end;
% check sign of entries in x (unless signFlag==0)
switch signFlag
case -2
if( ~all(x<0))
er = 'must have strictly negative entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case -1
if( ~all(x<=0))
er = 'must have negative entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case 1
if( ~all(x>=0))
er = 'must have positive entries';
er = createErrMsg( xname, xorig, er ); return;
end;
case 2
if( ~all(x>0))
er = 'must have strictly positive entries';
er = createErrMsg( xname, xorig, er ); return;
end
end
function er = createErrMsg( xname, x, er )
if(numel(x)<10)
er = ['Numeric input argument ' xname '=[' num2str(x) '] ' er '.'];
else
er = ['Numeric input argument ' xname ' ' er '.'];
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
fevalDistr.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/matlab/fevalDistr.m
| 11,227 |
utf_8
|
7e4d5077ef3d7a891b2847cb858a2c6c
|
function [out,res] = fevalDistr( funNm, jobs, varargin )
% Wrapper for embarrassingly parallel function evaluation.
%
% Runs "r=feval(funNm,jobs{i}{:})" for each job in a parallel manner. jobs
% should be a cell array of length nJob and each job should be a cell array
% of parameters to pass to funNm. funNm must be a function in the path and
% must return a single value (which may be a dummy value if funNm writes
% results to disk). Different forms of parallelization are supported
% depending on the hardware and Matlab toolboxes available. The type of
% parallelization is determined by the parameter 'type' described below.
%
% type='LOCAL': jobs are executed using a simple "for" loop. This implies
% no parallelization and is the default fallback option.
%
% type='PARFOR': jobs are executed using a "parfor" loop. This option is
% only available if the Matlab *Parallel Computing Toolbox* is installed.
% Make sure to setup Matlab workers first using "matlabpool open".
%
% type='DISTR': jobs are executed on the Caltech cluster. Distributed
% queuing system must be installed separately. Currently this option is
% only supported on the Caltech cluster but could easily be installed on
% any Linux cluster as it requires only SSH and a shared filesystem.
% Parameter pLaunch is used for controller('launchQueue',pLaunch{:}) and
% determines cluster machines used (e.g. pLaunch={48,401:408}).
%
% type='COMPILED': jobs are executed locally in parallel by first compiling
% an executable and then running it in background. This option requires the
% *Matlab Compiler* to be installed (but does NOT require the Parallel
% Computing Toolbox). Compiling can take 1-10 minutes, so use this option
% only for large jobs. (On Linux alter startup.m by calling addpath() only
% if ~isdeployed, otherwise will get error about "CTF" after compiling).
% Note that relative paths will not work after compiling so all paths used
% by funNm must be absolute paths.
%
% type='WINHPC': jobs are executed on a Windows HPC Server 2008 cluster.
% Similar to type='COMPILED', except after compiling, the executable is
% queued to the HPC cluster where all computation occurs. This option
% likewise requires the *Matlab Compiler*. Paths to data, etc., must be
% absolute paths and available from HPC cluster. Parameter pLaunch must
% have two fields 'scheduler' and 'shareDir' that define the HPC Server.
% Extra parameters in pLaunch add finer control, see fedWinhpc for details.
% For example, at MSR one possible cluster is defined by scheduler =
% 'MSR-L25-DEV21' and shareDir = '\\msr-arrays\scratch\msr-pool\L25-dev21'.
% Note call to 'job submit' from Matlab will hang unless pwd is saved
% (simply call 'job submit' from cmd prompt and enter pwd).
%
% USAGE
% [out,res] = fevalDistr( funNm, jobs, [varargin] )
%
% INPUTS
% funNm - name of function that will process jobs
% jobs - [1xnJob] cell array of parameters for each job
% varargin - additional params (struct or name/value pairs)
% .type - ['local'], 'parfor', 'distr', 'compiled', 'winhpc'
% .pLaunch - [] extra params for type='distr' or type='winhpc'
% .group - [1] send jobs in batches (only relevant if type='distr')
%
% OUTPUTS
% out - 1 if jobs completed successfully
% res - [1xnJob] cell array containing results of each job
%
% EXAMPLE
% % Note: in this case parallel versions are slower since conv2 is so fast
% n=16; jobs=cell(1,n); for i=1:n, jobs{i}={rand(500),ones(25)}; end
% tic, [out,J1] = fevalDistr('conv2',jobs,'type','local'); toc,
% tic, [out,J2] = fevalDistr('conv2',jobs,'type','parfor'); toc,
% tic, [out,J3] = fevalDistr('conv2',jobs,'type','compiled'); toc
% [isequal(J1,J2), isequal(J1,J3)], figure(1); montage2(cell2array(J1))
%
% See also matlabpool mcc
%
% Piotr's Computer Vision Matlab Toolbox Version 3.26
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
dfs={'type','local','pLaunch',[],'group',1};
[type,pLaunch,group]=getPrmDflt(varargin,dfs,1); store=(nargout==2);
if(isempty(jobs)), res=cell(1,0); out=1; return; end
switch lower(type)
case 'local', [out,res]=fedLocal(funNm,jobs,store);
case 'parfor', [out,res]=fedParfor(funNm,jobs,store);
case 'distr', [out,res]=fedDistr(funNm,jobs,pLaunch,group,store);
case 'compiled', [out,res]=fedCompiled(funNm,jobs,store);
case 'winhpc', [out,res]=fedWinhpc(funNm,jobs,pLaunch,store);
otherwise, error('unkown type: ''%s''',type);
end
end
function [out,res] = fedLocal( funNm, jobs, store )
% Run jobs locally using for loop.
nJob=length(jobs); res=cell(1,nJob); out=1;
tid=ticStatus('collecting jobs');
for i=1:nJob, r=feval(funNm,jobs{i}{:});
if(store), res{i}=r; end; tocStatus(tid,i/nJob); end
end
function [out,res] = fedParfor( funNm, jobs, store )
% Run jobs locally using parfor loop.
nJob=length(jobs); res=cell(1,nJob); out=1;
parfor i=1:nJob, r=feval(funNm,jobs{i}{:});
if(store), res{i}=r; end; end
end
function [out,res] = fedDistr( funNm, jobs, pLaunch, group, store )
% Run jobs using Linux queuing system.
if(~exist('controller.m','file'))
msg='distributed queuing not installed, switching to type=''local''.';
warning(msg); [out,res]=fedLocal(funNm,jobs,store); return; %#ok<WNTAG>
end
nJob=length(jobs); res=cell(1,nJob); controller('launchQueue',pLaunch{:});
if( group>1 )
nJobGrp=ceil(nJob/group); jobsGrp=cell(1,nJobGrp); k=0;
for i=1:nJobGrp, k1=min(nJob,k+group);
jobsGrp{i}={funNm,jobs(k+1:k1),'type','local'}; k=k1; end
nJob=nJobGrp; jobs=jobsGrp; funNm='fevalDistr';
end
jids=controller('jobsAdd',nJob,funNm,jobs); k=0;
fprintf('Sent %i jobs...\n',nJob); tid=ticStatus('collecting jobs');
while( 1 )
jids1=controller('jobProbe',jids);
if(isempty(jids1)), pause(.1); continue; end
jid=jids1(1); [r,err]=controller('jobRecv',jid);
if(~isempty(err)), disp('ABORTING'); out=0; break; end
k=k+1; if(store), res{jid==jids}=r; end
tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end
end; controller('closeQueue');
end
function [out,res] = fedCompiled( funNm, jobs, store )
% Run jobs locally in background in parallel using compiled code.
nJob=length(jobs); res=cell(1,nJob); tDir=jobSetup('.',funNm,'',{});
cmd=[tDir 'fevalDistrDisk ' funNm ' ' tDir ' ']; i=0; k=0;
Q=feature('numCores'); q=0; tid=ticStatus('collecting jobs');
while( 1 )
% launch jobs until queue is full (q==Q) or all jobs launched (i==nJob)
while(q<Q && i<nJob), q=q+1; i=i+1; jobSave(tDir,jobs{i},i);
if(ispc), system2(['start /B /min ' cmd int2str2(i,10)],0);
else system2([cmd int2str2(i,10) ' &'],0); end
end
% collect completed jobs (k1 of them), release queue slots
done=jobFileIds(tDir,'done'); k1=length(done); k=k+k1; q=q-k1;
for i1=done, res{i1}=jobLoad(tDir,i1,store); end
pause(1); tocStatus(tid,k/nJob); if(k==nJob), out=1; break; end
end
for i=1:10, try rmdir(tDir,'s'); break; catch,pause(1),end; end %#ok<CTCH>
end
function [out,res] = fedWinhpc( funNm, jobs, pLaunch, store )
% Run jobs using Windows HPC Server.
nJob=length(jobs); res=cell(1,nJob);
dfs={'shareDir','REQ','scheduler','REQ','executable','fevalDistrDisk',...
'mccOptions',{},'coresPerTask',1,'minCores',1024,'priority',2000};
p = getPrmDflt(pLaunch,dfs,1);
tDir = jobSetup(p.shareDir,funNm,p.executable,p.mccOptions);
for i=1:nJob, jobSave(tDir,jobs{i},i); end
hpcSubmit(funNm,1:nJob,tDir,p); k=0;
ticId=ticStatus('collecting jobs');
while( 1 )
done=jobFileIds(tDir,'done'); k=k+length(done);
for i1=done, res{i1}=jobLoad(tDir,i1,store); end
pause(5); tocStatus(ticId,k/nJob); if(k==nJob), out=1; break; end
end
for i=1:10, try rmdir(tDir,'s'); break; catch,pause(5),end; end %#ok<CTCH>
end
function tids = hpcSubmit( funNm, ids, tDir, pLaunch )
% Helper: send jobs w given ids to HPC cluster.
n=length(ids); tids=cell(1,n); if(n==0), return; end;
scheduler=[' /scheduler:' pLaunch.scheduler ' '];
m=system2(['cluscfg view' scheduler],0);
minCores=(hpcParse(m,'total number of nodes',1) - ...
hpcParse(m,'Unreachable nodes',1) - 1)*8;
minCores=min([minCores pLaunch.minCores n*pLaunch.coresPerTask]);
m=system2(['job new /numcores:' int2str(minCores) '-*' scheduler ...
'/priority:' int2str(pLaunch.priority)],1);
jid=hpcParse(m,'created job, id',0);
s=min(ids); e=max(ids); p=n>1 && isequal(ids,s:e);
if(p), jid1=[jid '.1']; else jid1=jid; end
for i=1:n, tids{i}=[jid1 '.' int2str(i)]; end
cmd0=''; if(p), cmd0=['/parametric:' int2str(s) '-' int2str(e)]; end
cmd=@(id) ['job add ' jid scheduler '/workdir:' tDir ' /numcores:' ...
int2str(pLaunch.coresPerTask) ' ' cmd0 ' /stdout:stdout' id ...
'.txt ' pLaunch.executable ' ' funNm ' ' tDir ' ' id];
if(p), ids1='*'; n=1; else ids1=int2str2(ids); end
if(n==1), ids1={ids1}; end; for i=1:n, system2(cmd(ids1{i}),1); end
system2(['job submit /id:' jid scheduler],1); disp(repmat(' ',1,80));
end
function v = hpcParse( msg, key, tonum )
% Helper: extract val corresponding to key in hpc msg.
t=regexp(msg,': |\n','split'); t=strtrim(t(1:floor(length(t)/2)*2));
keys=t(1:2:end); vals=t(2:2:end); j=find(strcmpi(key,keys));
if(isempty(j)), error('key ''%s'' not found in:\n %s',key,msg); end
v=vals{j}; if(tonum==0), return; elseif(isempty(v)), v=0; return; end
if(tonum==1), v=str2double(v); return; end
v=regexp(v,' ','split'); v=str2double(regexp(v{1},':','split'));
if(numel(v)==4), v(5)=0; end; v=((v(1)*24+v(2))*60+v(3))*60+v(4)+v(5)/1000;
end
function tDir = jobSetup( rtDir, funNm, executable, mccOptions )
% Helper: prepare by setting up temporary dir and compiling funNm
t=clock; t=mod(t(end),1); t=round((t+rand)/2*1e15);
tDir=[rtDir filesep sprintf('fevalDistr-%015i',t) filesep]; mkdir(tDir);
if(~isempty(executable) && exist(executable,'file'))
fprintf('Reusing compiled executable...\n'); copyfile(executable,tDir);
else
t=clock; fprintf('Compiling (this may take a while)...\n');
[~,f,e]=fileparts(executable); if(isempty(f)), f='fevalDistrDisk'; end
mcc('-m','fevalDistrDisk','-d',tDir,'-o',f,'-a',funNm,mccOptions{:});
t=etime(clock,t); fprintf('Compile complete (%.1f seconds).\n',t);
if(~isempty(executable)), copyfile([tDir filesep f e],executable); end
end
end
function ids = jobFileIds( tDir, type )
% Helper: get list of job files ids on disk of given type
fs=dir([tDir '*-' type '*']); fs={fs.name}; n=length(fs);
ids=zeros(1,n); for i=1:n, ids(i)=str2double(fs{i}(1:10)); end
end
function jobSave( tDir, job, ind ) %#ok<INUSL>
% Helper: save job to temporary file for use with fevalDistrDisk()
save([tDir int2str2(ind,10) '-in'],'job');
end
function r = jobLoad( tDir, ind, store )
% Helper: load job and delete temporary files from fevalDistrDisk()
f=[tDir int2str2(ind,10)];
if(store), r=load([f '-out']); r=r.r; else r=[]; end
fs={[f '-done'],[f '-in.mat'],[f '-out.mat']};
delete(fs{:}); pause(.1);
for i=1:3, k=0; while(exist(fs{i},'file')==2) %#ok<ALIGN>
warning('Waiting to delete %s.',fs{i}); %#ok<WNTAG>
delete(fs{i}); pause(5); k=k+1; if(k>12), break; end;
end; end
end
function msg = system2( cmd, show )
% Helper: wraps system() call
if(show), disp(cmd); end
[status,msg]=system(cmd); msg=msg(1:end-1);
if(status), error(msg); end
if(show), disp(msg); end
end
|
github
|
garrickbrazil/SDS-RCNN-master
|
medfilt1m.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/filters/medfilt1m.m
| 2,998 |
utf_8
|
a3733d27c60efefd57ada9d83ccbaa3d
|
function y = medfilt1m( x, r, z )
% One-dimensional adaptive median filtering with missing values.
%
% Applies a width s=2*r+1 one-dimensional median filter to vector x, which
% may contain missing values (elements equal to z). If x contains no
% missing values, y(j) is set to the median of x(j-r:j+r). If x contains
% missing values, y(j) is set to the median of x(j-R:j+R), where R is the
% smallest radius such that sum(valid(x(j-R:j+R)))>=s, i.e. the number of
% valid values in the window is at least s (a value x is valid x~=z). Note
% that the radius R is adaptive and can vary as a function of j.
%
% This function uses a modified version of medfilt1.m from Matlab's 'Signal
% Processing Toolbox'. Note that if x contains no missing values,
% medfilt1m(x) and medfilt1(x) are identical execpt at boundary regions.
%
% USAGE
% y = medfilt1m( x, r, [z] )
%
% INPUTS
% x - [nx1] length n vector with possible missing entries
% r - filter radius
% z - [NaN] element that represents missing entries
%
% OUTPUTS
% y - [nx1] filtered vector x
%
% EXAMPLE
% x=repmat((1:4)',1,5)'; x=x(:)'; x0=x;
% n=length(x); x(rand(n,1)>.8)=NaN;
% y = medfilt1m(x,2); [x0; x; y; x0-y]
%
% See also MODEFILT1, MEDFILT1
%
% Piotr's Computer Vision Matlab Toolbox Version 2.35
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
% apply medfilt1 (standard median filter) to valid locations in x
if(nargin<3 || isempty(z)), z=NaN; end; x=x(:)'; n=length(x);
if(isnan(z)), valid=~isnan(x); else valid=x~=z; end; v=sum(valid);
if(v==0), y=repmat(z,1,n); return; end
if(v<2*r+1), y=repmat(median(x(valid)),1,n); return; end
y=medfilt1(x(valid),2*r+1);
% get radius R needed at each location j to span s=2r+1 valid values
% get start (a) and end (b) locations and map back to location in y
C=[0 cumsum(valid)]; s=2*r+1; R=find(C==s); R=R(1)-2; pos=zeros(1,n);
for j=1:n, R0=R;
R=R0-1; a=max(1,j-R); b=min(n,j+R);
if(C(b+1)-C(a)<s), R=R0; a=max(1,j-R); b=min(n,j+R);
if(C(b+1)-C(a)<s), R=R0+1; a=max(1,j-R); b=min(n,j+R); end
end
pos(j)=(C(b+1)+C(a+1))/2;
end
y=y(floor(pos));
end
function y = medfilt1( x, s )
% standard median filter (copied from medfilt1.m)
n=length(x); r=floor(s/2); indr=(0:s-1)'; indc=1:n;
ind=indc(ones(1,s),1:n)+indr(:,ones(1,n));
x0=x(ones(r,1))*0; X=[x0'; x'; x0'];
X=reshape(X(ind),s,n); y=median(X,1);
end
% function y = medfilt1( x, s )
% % standard median filter (slow)
% % get unique values in x
% [vals,disc,inds]=unique(x); m=length(vals); n=length(x);
% if(m>256), warning('x takes on large number of diff vals'); end %#ok<WNTAG>
% % create quantized representation [H(i,j)==1 iff x(j)==vals(i)]
% H=zeros(m,n); H(sub2ind2([m,n],[inds; 1:n]'))=1;
% % create histogram [H(i,j) is count of x(j-r:j+r)==vals(i)]
% H=localSum(H,[0 s],'same');
% % compute median for each j and map inds back to original vals
% [disc,inds]=max(cumsum(H,1)>s/2,[],1); y=vals(inds);
% end
|
github
|
garrickbrazil/SDS-RCNN-master
|
FbMake.m
|
.m
|
SDS-RCNN-master/external/pdollar_toolbox/filters/FbMake.m
| 6,692 |
utf_8
|
b625c1461a61485af27e490333350b4b
|
function FB = FbMake( dim, flag, show )
% Various 1D/2D/3D filterbanks (hardcoded).
%
% USAGE
% FB = FbMake( dim, flag, [show] )
%
% INPUTS
% dim - dimension
% flag - controls type of filterbank to create
% - if d==1
% 1: gabor filter bank for spatiotemporal stuff
% - if d==2
% 1: filter bank from Serge Belongie
% 2: 1st/2nd order DooG filters. Similar to Gabor filterbank.
% 3: similar to Laptev&Lindberg ICPR04
% 4: decent seperable steerable? filterbank
% 5: berkeley filterbank for textons papers
% 6: symmetric DOOG filters
% - if d==3
% 1: decent seperable steerable filterbank
% show - [0] figure to use for optional display
%
% OUTPUTS
%
% EXAMPLE
% FB = FbMake( 2, 1, 1 );
%
% See also FBAPPLY2D
%
% Piotr's Computer Vision Matlab Toolbox Version 2.0
% Copyright 2014 Piotr Dollar. [pdollar-at-gmail.com]
% Licensed under the Simplified BSD License [see external/bsd.txt]
if( nargin<3 || isempty(show) ); show=0; end
% create FB
switch dim
case 1
FB = FbMake1D( flag );
case 2
FB = FbMake2D( flag );
case 3
FB = FbMake3d( flag );
otherwise
error( 'dim must be 1 2 or 3');
end
% display
FbVisualize( FB, show );
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FB = FbMake1D( flag )
switch flag
case 1 %%% gabor filter bank for spatiotemporal stuff
omegas = 1 ./ [3 4 5 7.5 11];
sigmas = [3 4 5 7.5 11];
FB = FbMakegabor1D( 15, sigmas, omegas );
otherwise
error('none created.');
end
function FB = FbMakegabor1D( r, sigmas, omegas )
for i=1:length(omegas)
[feven,fodd]=filterGabor1d(r,sigmas(i),omegas(i));
if( i==1 ); FB=repmat(feven,[2*length(omegas) 1]); end
FB(i*2-1,:)=feven; FB(i*2,:)=fodd;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FB = FbMake2D( flag )
switch flag
case 1 %%% filter bank from Berkeley / Serge Belongie
r=15;
FB = FbMakegabor( r, 6, 3, 3, sqrt(2) );
FB2 = FbMakeDOG( r, .6, 2.8, 4);
FB = cat(3, FB, FB2);
%FB = FB(:,:,1:2:36); %include only even symmetric filters
%FB = FB(:,:,2:2:36); %include only odd symmetric filters
case 2 %%% 1st/2nd order DooG filters. Similar to Gabor filterbank.
FB = FbMakeDooG( 15, 6, 3, 5, .5) ;
case 3 %%% similar to Laptev&Lindberg ICPR04
% Wierd filterbank of Gaussian derivatives at various scales
% Higher order filters probably not useful.
r = 9; dims=[2*r+1 2*r+1];
sigs = [.5 1 1.5 3]; % sigs = [1,1.5,2];
derivs = [];
%derivs = [ derivs; 0 0 ]; % 0th order
%derivs = [ derivs; 1 0; 0 1 ]; % first order
%derivs = [ derivs; 2 0; 0 2; 1 1 ]; % 2nd order
%derivs = [ derivs; 3 0; 0 3; 1 2; 2 1 ]; % 3rd order
%derivs = [ derivs; 4 0; 0 4; 1 3; 3 1; 2 2 ]; % 4th order
derivs = [ derivs; 0 1; 0 2; 0 3; 0 4; 0 5]; % 0n order
derivs = [ derivs; 1 0; 2 0; 3 0; 4 0; 5 0]; % n0 order
cnt=1; nderivs = size(derivs,1);
for s=1:length(sigs)
for i=1:nderivs
dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 );
if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end
FB(:,:,cnt) = dG; cnt=cnt+1;
%dG = filterDoog( dims, [sigs(s)*3 sigs(s)], derivs(i,:), 0 );
%FB(:,:,cnt) = dG; cnt=cnt+1;
%dG = filterDoog( dims, [sigs(s) sigs(s)*3], derivs(i,:), 0 );
%FB(:,:,cnt) = dG; cnt=cnt+1;
end
end
case 4 % decent seperable steerable? filterbank
r = 9; dims=[2*r+1 2*r+1];
sigs = [.5 1.5 3];
derivs = [1 0; 0 1; 2 0; 0 2];
cnt=1; nderivs = size(derivs,1);
for s=1:length(sigs)
for i=1:nderivs
dG = filterDoog( dims, [sigs(s) sigs(s)], derivs(i,:), 0 );
if(s==1 && i==1); FB=repmat(dG,[1 1 length(sigs)*nderivs]); end
FB(:,:,cnt) = dG; cnt=cnt+1;
end
end
FB2 = FbMakeDOG( r, .6, 2.8, 4);
FB = cat(3, FB, FB2);
case 5 %%% berkeley filterbank for textons papers
FB = FbMakegabor( 7, 6, 1, 2, 2 );
case 6 %%% symmetric DOOG filters
FB = FbMakeDooGSym( 4, 2, [.5 1] );
otherwise
error('none created.');
end
function FB = FbMakegabor( r, nOrient, nScales, lambda, sigma )
% multi-scale even/odd gabor filters. Adapted from code by Serge Belongie.
cnt=1;
for m=1:nScales
for n=1:nOrient
[F1,F2]=filterGabor2d(r,sigma^m,lambda,180*(n-1)/nOrient);
if(m==1 && n==1); FB=repmat(F1,[1 1 nScales*nOrient*2]); end
FB(:,:,cnt)=F1; cnt=cnt+1; FB(:,:,cnt)=F2; cnt=cnt+1;
end
end
function FB = FbMakeDooGSym( r, nOrient, sigs )
% Adds symmetric DooG filters. These are similar to gabor filters.
cnt=1; dims=[2*r+1 2*r+1];
for s=1:length(sigs)
Fodd = -filterDoog( dims, [sigs(s) sigs(s)], [1 0], 0 );
Feven = filterDoog( dims, [sigs(s) sigs(s)], [2 0], 0 );
if(s==1); FB=repmat(Fodd,[1 1 length(sigs)*nOrient*2]); end
for n=1:nOrient
theta = 180*(n-1)/nOrient;
FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1;
FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1;
end
end
function FB = FbMakeDooG( r, nOrient, nScales, lambda, sigma )
% 1st/2nd order DooG filters. Similar to Gabor filterbank.
% Defaults: nOrient=6, nScales=3, lambda=5, sigma=.5,
cnt=1; dims=[2*r+1 2*r+1];
for m=1:nScales
sigma = sigma * m^.7;
Fodd = -filterDoog( dims, [sigma lambda*sigma^.6], [1,0], 0 );
Feven = filterDoog( dims, [sigma lambda*sigma^.6], [2,0], 0 );
if(m==1); FB=repmat(Fodd,[1 1 nScales*nOrient*2]); end
for n=1:nOrient
theta = 180*(n-1)/nOrient;
FB(:,:,cnt) = imrotate( Feven, theta, 'bil', 'crop' ); cnt=cnt+1;
FB(:,:,cnt) = imrotate( Fodd, theta, 'bil', 'crop' ); cnt=cnt+1;
end
end
function FB = FbMakeDOG( r, sigmaStr, sigmaEnd, n )
% adds a serires of difference of Gaussian filters.
sigs = sigmaStr:(sigmaEnd-sigmaStr)/(n-1):sigmaEnd;
for s=1:length(sigs)
FB(:,:,s) = filterDog2d(r,sigs(s),2); %#ok<AGROW>
if( s==1 ); FB=repmat(FB,[1 1 length(sigs)]); end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function FB = FbMake3d( flag )
switch flag
case 1 % decent seperable steerable filterbank
r = 25; dims=[2*r+1 2*r+1 2*r+1];
sigs = [.5 1.5 3];
derivs = [0 0 1; 0 1 0; 1 0 0; 0 0 2; 0 2 0; 2 0 0];
cnt=1; nderivs = size(derivs,1);
for s=1:length(sigs)
for i=1:nderivs
dG = filterDoog( dims, repmat(sigs(s),[1 3]), derivs(i,:), 0 );
if(s==1 && i==1); FB=repmat(dG,[1 1 1 nderivs*length(sigs)]); end
FB(:,:,:,cnt) = dG; cnt=cnt+1;
end
end
otherwise
error('none created.');
end
|
github
|
nscholtes/Default-Cascades-master
|
lnbin.m
|
.m
|
Default-Cascades-master/lnbin.m
| 1,412 |
utf_8
|
b27c6f1c9406b20ad7536b447c724a16
|
% This function take the input of a data vector x, which is to be binned;
% it also takes in the amount bins one would like the data binned into. The
% output is two vectors, one containing the normalised frequency of each bin
% (Freq), the other, the midpoint of each bin (midpts).
% Added and error to the binned frequency: eFreq (As of June 30 2010). If this
% option is not required, just call the function without including the third out
% put; i.e.: [midpts Freq]=lnbin(x,BinNum).
function [midpts Freq eFreq]=lnbin(x,BinNum)
x=sort(x);
i=1;
while x(i)<=0;
i=i+1;
end
str = num2str((length(x)-i)/length(x)*100);
%stuff='Percentage of input vec binned ';
%disp([stuff str])
FPT=x(i:length(x));
LFPT=log(FPT);
max1=log( ceil(max(FPT)) );
min1=log(floor(min(FPT)));
% min1=1;
LFreq=zeros(BinNum,1);
LTime=zeros(BinNum,1);
Lends=zeros(BinNum,2);
step=(max1-min1)/BinNum;
% ------------ LOG Binning Data ------------------------
for i=1:length(FPT)
for k=1:BinNum
if( (k-1)*step+min1 <= LFPT(i) && LFPT(i) < k*step+min1)
LFreq(k)=LFreq(k)+1;
end
LTime(k)=k*step-(0.5*step)+min1;
Lends(k,1)=(k-1)*step+min1;
Lends(k,2)=(k)*step+min1;
end
end
ends=exp(Lends);
widths=ends(1:length(ends),2)-ends(1:length(ends),1);
Freq=LFreq./widths./length(x);
eFreq=1./sqrt(LFreq).*Freq;
midpts = exp(LTime);
|
github
|
egg5562/Electronic-Nose-master
|
normalize_data.m
|
.m
|
Electronic-Nose-master/source_code/normalize_data.m
| 470 |
utf_8
|
5649f07241d28cea2852755d76f6e1ea
|
function normalized_data = normalize_data(set,m,s)
si= size(set);
ForRepmat = si(1);
new_mean = repmat(m,ForRepmat,1);
new_std = repmat(s,ForRepmat,1);
normalized_data = (set- new_mean)./new_std;
end
% si= size(tr_set(:,1:end-1));
% ForRepmat = si(2);
% new_mean = repmat(mean_f,ForRepmat,1);
% new_std = repmat(std_f,ForRepmat,1);
%
% normalized_data = (tr_set(:,1:end-1)- new_mean)./new_std;
|
github
|
egg5562/Electronic-Nose-master
|
cal_std.m
|
.m
|
Electronic-Nose-master/source_code/cal_std.m
| 547 |
utf_8
|
34787ea76a9210756ea14220a6d7de6f
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Mean and Std calculation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [mean_vec, std_vec] = cal_std(data);
[N_P, N_F] = size(data);
for j=1:N_F,
sum(j) = 0;
for i=1:N_P,
sum(j) = sum(j) + data(i,j);
end
mean_vec(j) = sum(j) / N_P;
end
for j=1:N_F,
sum(j) = 0;
for i=1:N_P,
sum(j) = sum(j) + (data(i,j)-mean_vec(j))^2;
end
std_vec(j) = sqrt(sum(j)/(N_P-1));
end
|
github
|
egg5562/Electronic-Nose-master
|
L1PCA.m
|
.m
|
Electronic-Nose-master/source_code/L1PCA.m
| 2,724 |
utf_8
|
ec8b30e80cd9ad3aac81864b7e7f4382
|
% 1DPCA
% by Spinoz Kim ([email protected])
% Dec. 8 2004
% n_it = iteration number
function [w, n_it, elap_time, tr_prj] = L1PCA(tr_data, Ns);
%Read input file
% [N, temp] = size(tr_data);
[N, N_f] = size(tr_data);
% N_f = temp-1; %N_Tr = 100*2, %N_F = 100*120
data_tr = tr_data(:,1:N_f);
%class_tr = tr_data(:,N_f+1);
%clear tr_data;
% [mean_f, std_f] = cal_std(data_tr);
if N < N_f % number of samples is smaller than dimension
comp_consider = 1;
r = rank(data_tr);
[w_pca, temp_time] = L2PCA_new(tr_data, comp_consider, r);
x = tr_data * w_pca;
else
comp_consider = 0;
x = data_tr;
r = N_f;
end
%Start the watch for lasting time of the feature extraction
t0 = clock;
%% from here: searching direction
%x = data_tr;
w = [];
for i=1:Ns
if i~=1
x = x - (x*w(:,i-1))*w(:,i-1)'; % x is a row vector, v is a column vector
end
n = 0;
% find maximum x_i
for j=1:N
norm_x(j) = norm(x(j,:));
end
[sorted_norm_x, ind] = sort(norm_x);
v = x(ind(end),:)' / sorted_norm_x(end);
%penalize
med_norm = median(norm_x);
for j=1:N
if norm_x(j) > med_norm
penal(j) = (med_norm/norm_x(j));
else
penal(j) = 1;
end
end
%% random direction
%index = ceil(rand(1)*N);
%v = x(index,:)' / norm(x(index,:));
%%initialize by PCA
%v = L2PCA(x, 1, 1);
v_old = zeros(r,1); % initial direction
while ((v ~= v_old))
v_old = v;
% check polarity of inner product
sum_x = zeros(1,r);
for j=1:N
if x(j,:) * v >= 0
p(j) = 1;
else
p(j) = -1;
end
sum_x = sum_x + penal(j)*p(j)*x(j,:);
end
%abs_sum_x = sqrt(sum(sum_x.^2));
v = sum_x'/norm(sum_x);%abs_sum_x;
n = n+1;
end
w = [w, v];
n_it(i) = n;
end
if comp_consider == 1,
w = w_pca*w;
end
%Finish the stop watch
elap_time = etime(clock, t0);
display('L1PCA end');
display(elap_time);
%% projection
% fid = fopen([out_file,'_pcaeig.dat'], 'w');
% for i=1:n_sel,
% fprintf(fid,'%.4f ', eig_val(i));
% end
% fprintf(fid,'\n\n');
% eig_tot = sum(eig_val);
% for i=1:n_sel,
% eig_extracted = sum(eig_val(1:i));
% eig_rate_vec(i) = (eig_extracted/eig_tot) * 100;
% fprintf(fid,'eig_rate(%d features) : %.2f\n', i, eig_rate_vec(i));
% end
% fprintf(fid,'\n\n');
% fprintf(fid,'elap_time : %.2f (sec)\n', elap_time);
% fclose(fid);
%% Tr. data projection
tr_prj = data_tr * w_pca;
clear data_tr;
%res = 1;
|
github
|
haitaozhao/Dynamic-Graph-Embedding-for-Fault-Detection-master
|
kde.m
|
.m
|
Dynamic-Graph-Embedding-for-Fault-Detection-master/Matlab_code/kde.m
| 5,361 |
utf_8
|
984530c222928bc6fba29542faa4d5cd
|
function [bandwidth,density,xmesh,cdf]=kde(data,n,MIN,MAX)
% Reliable and extremely fast kernel density estimator for one-dimensional data;
% Gaussian kernel is assumed and the bandwidth is chosen automatically;
% Unlike many other implementations, this one is immune to problems
% caused by multimodal densities with widely separated modes (see example). The
% estimation does not deteriorate for multimodal densities, because we never assume
% a parametric model for the data.
% INPUTS:
% data - a vector of data from which the density estimate is constructed;
% n - the number of mesh points used in the uniform discretization of the
% interval [MIN, MAX]; n has to be a power of two; if n is not a power of two, then
% n is rounded up to the next power of two, i.e., n is set to n=2^ceil(log2(n));
% the default value of n is n=2^12;
% MIN, MAX - defines the interval [MIN,MAX] on which the density estimate is constructed;
% the default values of MIN and MAX are:
% MIN=min(data)-Range/10 and MAX=max(data)+Range/10, where Range=max(data)-min(data);
% OUTPUTS:
% bandwidth - the optimal bandwidth (Gaussian kernel assumed);
% density - column vector of length 'n' with the values of the density
% estimate at the grid points;
% xmesh - the grid over which the density estimate is computed;
% - If no output is requested, then the code automatically plots a graph of
% the density estimate.
% cdf - column vector of length 'n' with the values of the cdf
% Reference:
% Kernel density estimation via diffusion
% Z. I. Botev, J. F. Grotowski, and D. P. Kroese (2010)
% Annals of Statistics, Volume 38, Number 5, pages 2916-2957.
%
% Example:
% data=[randn(100,1);randn(100,1)*2+35 ;randn(100,1)+55];
% kde(data,2^14,min(data)-5,max(data)+5);
% Notes: If you have a more reliable and accurate one-dimensional kernel density
% estimation software, please email me at [email protected]
data=data(:); %make data a column vector
if nargin<2 % if n is not supplied switch to the default
n=2^14;
end
n=2^ceil(log2(n)); % round up n to the next power of 2;
if nargin<4 %define the default interval [MIN,MAX]
minimum=min(data); maximum=max(data);
Range=maximum-minimum;
MIN=minimum-Range/10; MAX=maximum+Range/10;
end
% set up the grid over which the density estimate is computed;
R=MAX-MIN; dx=R/(n-1); xmesh=MIN+[0:dx:R]; N=length(unique(data));
%bin the data uniformly using the grid defined above;
initial_data=histc(data,xmesh)/N; initial_data=initial_data/sum(initial_data);
a=dct1d(initial_data); % discrete cosine transform of initial data
% now compute the optimal bandwidth^2 using the referenced method
I=[1:n-1]'.^2; a2=(a(2:end)/2).^2;
% use fzero to solve the equation t=zeta*gamma^[5](t)
try
t_star=fzero(@(t)fixed_point(t,N,I,a2),[0,.1]);
catch
t_star=.28*N^(-2/5);
end
% smooth the discrete cosine transform of initial data using t_star
a_t=a.*exp(-[0:n-1]'.^2*pi^2*t_star/2);
% now apply the inverse discrete cosine transform
if (nargout>1)|(nargout==0)
density=idct1d(a_t)/R;
end
% take the rescaling of the data into account
bandwidth=sqrt(t_star)*R;
if nargout==0
figure(1), plot(xmesh,density)
end
% for cdf estimation
if nargout>3
f=2*pi^2*sum(I.*a2.*exp(-I*pi^2*t_star));
t_cdf=(sqrt(pi)*f*N)^(-2/3);
% now get values of cdf on grid points using IDCT and cumsum function
a_cdf=a.*exp(-[0:n-1]'.^2*pi^2*t_cdf/2);
cdf=cumsum(idct1d(a_cdf))*(dx/R);
% take the rescaling into account if the bandwidth value is required
bandwidth_cdf=sqrt(t_cdf)*R;
end
end
%################################################################
function out=fixed_point(t,N,I,a2)
% this implements the function t-zeta*gamma^[l](t)
l=7;
f=2*pi^(2*l)*sum(I.^l.*a2.*exp(-I*pi^2*t));
for s=l-1:-1:2
K0=prod([1:2:2*s-1])/sqrt(2*pi); const=(1+(1/2)^(s+1/2))/3;
time=(2*const*K0/N/f)^(2/(3+2*s));
f=2*pi^(2*s)*sum(I.^s.*a2.*exp(-I*pi^2*time));
end
out=t-(2*N*sqrt(pi)*f)^(-2/5);
end
%##############################################################
function out = idct1d(data)
% computes the inverse discrete cosine transform
[nrows,ncols]=size(data);
% Compute weights
weights = nrows*exp(i*(0:nrows-1)*pi/(2*nrows)).';
% Compute x tilde using equation (5.93) in Jain
data = real(ifft(weights.*data));
% Re-order elements of each column according to equations (5.93) and
% (5.94) in Jain
out = zeros(nrows,1);
out(1:2:nrows) = data(1:nrows/2);
out(2:2:nrows) = data(nrows:-1:nrows/2+1);
% Reference:
% A. K. Jain, "Fundamentals of Digital Image
% Processing", pp. 150-153.
end
%##############################################################
function data=dct1d(data)
% computes the discrete cosine transform of the column vector data
[nrows,ncols]= size(data);
% Compute weights to multiply DFT coefficients
weight = [1;2*(exp(-i*(1:nrows-1)*pi/(2*nrows))).'];
% Re-order the elements of the columns of x
data = [ data(1:2:end,:); data(end:-2:2,:) ];
% Multiply FFT by weights:
data= real(weight.* fft(data));
end
|
github
|
ROCmSoftwarePlatform/CNTK-1-master
|
ComputeConfusion.m
|
.m
|
CNTK-1-master/Examples/Speech/Miscellaneous/TIMIT/AdditionalFiles/ComputeConfusion.m
| 6,047 |
utf_8
|
9c31b020d02c3e11bbdb1db0a04bcc32
|
function confusionData = ComputeConfusion(mlfFile)
% function confusionData = ComputeConfusion(mlfFile)
% Compute all the confusions for one experiment. Read in the TIMIT MLF file
% so we know which utterances we have. For each utterance, read in the
% CNTK output and compute the confusion matrix. Sum them all together.
if nargin < 1
mlfFile = 'TimitLabels.mlf';
end
%%
% Parse the Timit MLF file because it tells us the true phonetic labels
% for each segment of each utterance.
fp = fopen(mlfFile,'r');
segmentLabels = [];
scale=1e-7;
numberOfUtterances = 0;
confusionData = 0;
while 1
theLine = fgets(fp);
if isempty(theLine) || theLine(1) == -1
break;
end
if strncmp(theLine, '#!MLF!#', 7)
continue; % Ignore the header
end
if theLine(1) == '"' % Look for file name indication
numberOfUtterances = numberOfUtterances + 1;
fileName = strtok(theLine);
fileName = fileName(2:end-1);
segmentLabels = [];
end
if theLine(1) >= '0' && theLine(1) <= '9'
% Got a speech segment with times and phoneme label. Parse it.
c = textscan(theLine, '%d %d %s ');
b = double(c{1}(1)); e = double(c{2}); l = c{3}{1};
if isempty(segmentLabels)
clear segmentLabels;
segmentLabels(1000) = struct('begin', b, 'end', e, 'label', l);
segmentCount = 0;
end
segmentCount = segmentCount + 1;
% Add a new entry in the list of segments.
segmentLabels(segmentCount) = struct('begin', b*scale, 'end', e*scale, 'label', l);
end
if theLine(1) == '.'
% Found the end of the speech transcription. Process the new data.
c = ComputeConfusionOnce(fileName, segmentLabels(1:segmentCount));
confusionData = confusionData + c;
segmentLabels = [];
end
end
fclose(fp);
function Confusions = ComputeConfusionOnce(utteranceName, segmentLabels)
% function Confusions = ComputeConfusionOnce(utteranceName, labelData)
% Compute the confusion matrix for one TIMIT utterance. This routine takes
% the segment data (from the TIMIT label file) and a feature-file name. It
% transforms the feature file into a CNTK output file. It reads in the
% CNTK output file, and tabulates a confusion matrix. We do this one
% segment at a time, since TIMIT segments are variable length, and the CNTK
% output is sampled at regular intervals (10ms).
likelihoodName = strrep(strrep(utteranceName, 'Features/', 'Output/'), ...
'fbank_zda', 'log');
try
[likelihood,~] = htkread(likelihoodName);
catch me
fprintf('Can''t read %s using htkread. Ignoring.\n', likelihoodName);
Confusions = 0;
return
end
nStates = 183; % Preordained.
frameRate = 100; % Preordained
Confusions = zeros(nStates, nStates);
for i=1:size(segmentLabels, 2)
% Go through each entry in the MLF file for one utterance. Each entry
% lists the beginning and each of each speech state.
% Compare the true label with the winner of the maximum likelihood from
% CNTK.
beginIndex = max(1, round(segmentLabels(i).begin*frameRate));
endIndex = min(size(likelihood,1), round(segmentLabels(i).end*frameRate));
curIndices = beginIndex:endIndex;
[~,winners] = max(likelihood(curIndices,:),[], 2);
correctLabel = FindLabelNumber(segmentLabels(i).label);
for w=winners(:)' % increment one at a time
Confusions(correctLabel, w) = Confusions(correctLabel, w) + 1;
end
end
function labelNumber = FindLabelNumber(labelName)
% For each label name, turn the name into an index. The labels are listed,
% in order, in the TimitStateList file.
persistent stateList
if isempty(stateList)
stateList = ReadStateList('TimitStateList.txt');
end
for labelNumber=1:size(stateList,1)
if strcmp(labelName, stateList{labelNumber})
return;
end
end
labelNumber = [];
function stateList = ReadStateList(stateListFile)
% Read in the state list file. This file contains an ordered list of
% states, each corresponding to one label (and one output in the CNTK
% network.)
fp = fopen(stateListFile);
nStates = 183; % Preordained
stateList = cell(nStates, 1);
stateIndex = 1;
while true
theLine = fgets(fp);
if isempty(theLine) || theLine(1) == -1
break;
end
stateList{stateIndex} = theLine(1:end-1);
stateIndex = stateIndex + 1;
end
fclose(fp);
function [ DATA, HTKCode ] = htkread( Filename )
% [ DATA, HTKCode ] = htkread( Filename )
%
% Read DATA from possibly compressed HTK format file.
%
% Filename (string) - Name of the file to read from
% DATA (nSamp x NUMCOFS) - Output data array
% HTKCode - HTKCode describing file contents
%
% Compression is handled using the algorithm in 5.10 of the HTKBook.
% CRC is not implemented.
%
% Mark Hasegawa-Johnson
% July 3, 2002
% Based on function mfcc_read written by Alexis Bernard
% Found at: https://raw.githubusercontent.com/ronw/matlab_htk/master/htkread.m
%
fid=fopen(Filename,'r','b');
if fid<0,
error(sprintf('Unable to read from file %s',Filename));
end
% Read number of frames
nSamp = fread(fid,1,'int32');
% Read sampPeriod
sampPeriod = fread(fid,1,'int32');
% Read sampSize
sampSize = fread(fid,1,'int16');
% Read HTK Code
HTKCode = fread(fid,1,'int16');
%%%%%%%%%%%%%%%%%
% Read the data
if bitget(HTKCode, 11),
DIM=sampSize/2;
nSamp = nSamp-4;
%disp(sprintf('htkread: Reading %d frames, dim %d, compressed, from %s',nSamp,DIM,Filename));
% Read the compression parameters
A = fread(fid,[1 DIM],'float');
B = fread(fid,[1 DIM],'float');
% Read and uncompress the data
DATA = fread(fid, [DIM nSamp], 'int16')';
DATA = (repmat(B, [nSamp 1]) + DATA) ./ repmat(A, [nSamp 1]);
else
DIM=sampSize/4;
%disp(sprintf('htkread: Reading %d frames, dim %d, uncompressed, from %s',nSamp,DIM,Filename));
% If not compressed: Read floating point data
DATA = fread(fid, [DIM nSamp], 'float')';
end
fclose(fid);
|
github
|
ROCmSoftwarePlatform/CNTK-1-master
|
ShowConfusions.m
|
.m
|
CNTK-1-master/Examples/Speech/Miscellaneous/TIMIT/AdditionalFiles/ShowConfusions.m
| 2,174 |
utf_8
|
0e7784a2f2e8b497f6ad9e7cd07e9377
|
function ShowConfusions(confusionData, squeeze)
% function ShowConfusions(confusionData)
% Average the three-state confusion data into monophone confusions. Then
% display the data. A graphical interface lets you interrogate the data,
% by moving the mouse, and clicking at various points. The phonetic labels
% are shown on the graph.
confusionSmall = ( ...
confusionData(1:3:end,1:3:end) + confusionData(2:3:end, 1:3:end) + confusionData(3:3:end, 1:3:end) + ...
confusionData(1:3:end,2:3:end) + confusionData(2:3:end, 2:3:end) + confusionData(3:3:end, 2:3:end) + ...
confusionData(1:3:end,3:3:end) + confusionData(2:3:end, 3:3:end) + confusionData(3:3:end, 3:3:end))/9;
if nargin < 2
squeeze = 1;
end
imagesc(confusionSmall .^ squeeze)
axis ij
axis square
ylabel('True Label');
xlabel('CNTK Prediction');
%%
stateList = ReadStateList();
h = [];
fprintf('Select a point with the mouse, type return to end...\n');
while true
[x,y] = ginput(1);
if isempty(x) || isempty(y)
break;
end
if ~isempty(h)
delete(h);
h = [];
end
try
trueLabel = stateList{(round(x)-1)*3+1};
catch
trueLabel = 'Unknown';
end
try
likelihoodLabel = stateList{(round(y)-1)*3+1};
catch
likelihoodLabel = 'Unknown';
end
h = text(40, -2, sprintf('%s -> %s', trueLabel, likelihoodLabel));
% h = text(40, -2, sprintf('%g -> %g', x, y));
end
function stateList = ReadStateList(stateListFile)
% Read in the state list file. This file contains an ordered list of
% states, each corresponding to one label (and one output in the CNTK
% network.)
if nargin < 1
stateListFile = 'TimitStateList.txt';
end
% Read in the state list file.
fp = fopen(stateListFile);
nStates = 183; % Preordained
stateList = cell(nStates, 1);
stateIndex = 1;
while true
theLine = fgets(fp);
if isempty(theLine) || theLine(1) == -1
break;
end
f = find(theLine == '_');
if ~isempty(f)
label = theLine(1:f(1)-1);
else
label = theLine(1:end-1);
end
stateList{stateIndex} = label;
stateIndex = stateIndex + 1;
end
fclose(fp);
|
github
|
SNURobotics/AdaptiveControl_-master
|
skew.m
|
.m
|
AdaptiveControl_-master/IROS2018/adaptive control/matlab_code_MTtest/skew.m
| 436 |
utf_8
|
d16b20d6af4d5e9151fb41c84b47f8fd
|
%% return skew-symmetric matrix : r -> [r] or [r] - > r
function mat=skew(r)
% mat=[0 -r(3) r(2);
% r(3) 0 -r(1);
% -r(2) r(1) 0];
if (size(r) == [3,1])
mat=zeros(3);
mat(1,2)=-r(3);
mat(1,3)=r(2);
mat(2,1)=r(3);
mat(2,3)=-r(1);
mat(3,1)=-r(2);
mat(3,2)=r(1);
elseif (size(r) == [3,3])
mat=zeros(3,1);
mat(1,1)=r(3,2);
mat(2,1)=r(1,3);
mat(3,1)=r(2,1);
end
end
|
github
|
SNURobotics/AdaptiveControl_-master
|
robot_dyn_eq.m
|
.m
|
AdaptiveControl_-master/IROS2018/adaptive control/matlab_code_MTtest/robot_dyn_eq.m
| 1,057 |
utf_8
|
573fd2eca9a67040a6e9a0615df6ec80
|
% function [MM,CC,gg, Jt] = robot_dyn_eq(S, M, J,f_iti, q,q_dot)
function [MM,CC,gg] = robot_dyn_eq(robot,q,q_dot)
n_joints=robot.nDOF;
SS=zeros(n_joints*6,n_joints);
GG=eye(6*n_joints, 6*n_joints);
JJ=zeros(6*n_joints, 6*n_joints);
adV=zeros(6*n_joints, 6*n_joints);
f_=cell(n_joints,1);
% Ad_ft=zeros(6*n_joints, 6*n_joints);
for i=1:n_joints
SS(6*(i-1)+1:6*i,i)= robot.link(i).screw;
JJ(6*(i-1)+1:6*i,6*(i-1)+1:6*i)=robot.link(i).J;
f_{i}=robot.link(i).M*SE3_exp(robot.link(i).screw*q(i));
% Ad_ft(6*(i-1)+1:6*i,6*(i-1)+1:6*i)=Ad_T(invSE3(f_iti{i}));
if i>1
f_ji=f_{i};
for j=(i-1):-1:1
GG(6*(i-1)+1:6*i,6*(j-1)+1:6*j)=Ad_T(invSE3(f_ji));
f_ji=f_{j}*f_ji;
end
end
end
V=GG*SS*q_dot;
for i=1:n_joints
adV(6*(i-1)+1:6*i,6*(i-1)+1:6*i)=ad_V(V(6*(i-1)+1:6*i,1));
end
P0=zeros(6*n_joints,6);
P0(1:6,1:6)=Ad_T(invSE3(f_{1}));
MM=SS'*GG'*JJ*GG*SS;
CC=SS'*GG'*(JJ*GG*adV-adV'*JJ*GG)*SS;
gg=SS'*GG'*JJ*GG*P0*[0;0;0;0;0;9.8];
% Jt=-Ad_ft*GG*SS;
end
|
github
|
SukritGupta17/Chess-Board-Recognition-master
|
DeepLearningImageClassificationExample.m
|
.m
|
Chess-Board-Recognition-master/Code/DeepLearningImageClassificationExample.m
| 15,434 |
utf_8
|
07974ce7f3f0aa58be243f2f530bd2d5
|
%% Image Category Classification Using Deep Learning
% This example shows how to use a pre-trained Convolutional Neural Network
% (CNN) as a feature extractor for training an image category classifier.
%
% Copyright 2016 The MathWorks, Inc.
%% Overview
% A Convolutional Neural Network (CNN) is a powerful machine learning
% technique from the field of deep learning. CNNs are trained using large
% collections of diverse images. From these large collections, CNNs can
% learn rich feature representations for a wide range of images. These
% feature representations often outperform hand-crafted features such as
% HOG, LBP, or SURF. An easy way to leverage the power of CNNs, without
% investing time and effort into training, is to use a pre-trained CNN as a
% feature extractor.
%
% In this example, images from Caltech 101 are classified into categories
% using a multiclass linear SVM trained with CNN features extracted from
% the images. This approach to image category classification follows the
% standard practice of training an off-the-shelf classifier using features
% extracted from images. For example, the
% <matlab:showdemo('ImageCategoryClassificationExample') Image Category
% Classification Using Bag Of Features> example uses SURF features within a
% bag of features framework to train a multiclass SVM. The difference here
% is that instead of using image features such as HOG or SURF, features are
% extracted using a CNN. And, as this example will show, the classifier
% trained using CNN features provides close to 100% accuracy, which
% is higher than the accuracy achieved using bag of features and SURF.
%
% Note: This example requires Computer Vision System Toolbox(TM), Image
% Processing Toolbox(TM), Neural Network Toolbox(TM), Parallel Computing
% Toolbox(TM), Statistics and Machine Learning Toolbox(TM), and a
% CUDA-capable NVIDIA(TM) GPU with compute capability 3.0 or higher.
function DeepLearningImageClassificationExample
%% Check System Requirements
% A CUDA-capable NVIDIA(TM) GPU with compute capability 3.0 or higher is
% highly recommended to run this example. Query the GPU device to check if
% it can run this example:
% Get GPU device information
% deviceInfo = gpuDevice;
%
% % Check the GPU compute capability
% computeCapability = str2double(deviceInfo.ComputeCapability);
% assert(computeCapability > 3.0, ...
% 'This example requires a GPU device with compute capability 3.0 or higher.')
%% Download Image Data
% The category classifier will be trained on images from
% <http://www.vision.caltech.edu/Image_Datasets/Caltech101 Caltech 101>.
% Caltech 101 is one of the most widely cited and used image data sets,
% collected by Fei-Fei Li, Marco Andreetto, and Marc 'Aurelio Ranzato.
% Download the compressed data set from the following location
url = 'http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz';
% Store the output in a temporary folder
outputFolder = fullfile(tempdir, 'caltech101'); % define output folder
%%
% Note: Download time of the data depends on your internet connection. The
% next set of commands use MATLAB to download the data and will block
% MATLAB. Alternatively, you can use your web browser to first download the
% dataset to your local disk. To use the file you downloaded from the web,
% change the 'outputFolder' variable above to the location of the
% downloaded file.
if ~exist(outputFolder, 'dir') % download only once
disp('Downloading 126MB Caltech101 data set...');
untar(url, outputFolder);
end
%% Load Images
% Instead of operating on all of Caltech 101, which is time consuming, use
% three of the categories: airplanes, ferry, and laptop. The image category
% classifier will be trained to distinguish amongst these six categories.
rootFolder = fullfile(outputFolder, '101_ObjectCategories');
categories = {'airplanes', 'ferry', 'laptop'};
%%
% Create an |ImageDatastore| to help you manage the data. Because
% |ImageDatastore| operates on image file locations, images are not loaded
% into memory until read, making it efficient for use with large image
% collections.
imds = imageDatastore(fullfile(rootFolder, categories), 'LabelSource', 'foldernames');
%%
% The |imds| variable now contains the images and the category labels
% associated with each image. The labels are automatically assigned from
% the folder names of the image files. Use |countEachLabel| to summarize
% the number of images per category.
tbl = countEachLabel(imds)
%%
% Because |imds| above contains an unequal number of images per category,
% let's first adjust it, so that the number of images in the training set
% is balanced.
minSetCount = min(tbl{:,2}); % determine the smallest amount of images in a category
% Use splitEachLabel method to trim the set.
imds = splitEachLabel(imds, minSetCount, 'randomize');
% Notice that each set now has exactly the same number of images.
countEachLabel(imds)
%%
% Below, you can see example images from three of the categories included
% in the dataset.
% Find the first instance of an image for each category
airplanes = find(imds.Labels == 'airplanes', 1);
ferry = find(imds.Labels == 'ferry', 1);
laptop = find(imds.Labels == 'laptop', 1);
figure
subplot(1,3,1);
imshow(readimage(imds,airplanes))
subplot(1,3,2);
imshow(readimage(imds,ferry))
subplot(1,3,3);
imshow(readimage(imds,laptop))
%% Download Pre-trained Convolutional Neural Network (CNN)
% Now that the images are prepared, you will need to download a pre-trained
% CNN model for this example. There are several pre-trained networks that
% have gained popularity. Most of these have been trained on the ImageNet
% dataset, which has 1000 object categories and 1.2 million training
% images[1]. "AlexNet" is one such model and can be downloaded from
% MatConvNet[2,3]:
% Location of pre-trained "AlexNet"
cnnURL = 'http://www.vlfeat.org/matconvnet/models/beta16/imagenet-caffe-alex.mat';
% Store CNN model in a temporary folder
cnnMatFile = fullfile(tempdir, 'imagenet-caffe-alex.mat');
%%
% Note: Download time of the data depends on your internet connection. The
% next set of commands use MATLAB to download the data and will block
% MATLAB. Alternatively, you can use your web browser to first download the
% dataset to your local disk. To use the file you downloaded from the web,
% change the 'cnnMatFile' variable above to the location of the downloaded
% file.
if ~exist(cnnMatFile, 'file') % download only once
disp('Downloading pre-trained CNN model...');
websave(cnnMatFile, cnnURL);
end
%% Load Pre-trained CNN
% The CNN model is saved in MatConvNet's format [3]. Load the MatConvNet
% network data into |convnet|, a |SeriesNetwork| object from Neural Network
% Toolbox(TM), using the helper function |helperImportMatConvNet|. A
% SeriesNetwork object can be used to inspect the network architecture,
% classify new data, and extract network activations from specific layers.
% Load MatConvNet network into a SeriesNetwork
convnet = helperImportMatConvNet(cnnMatFile)
%%
% |convnet.Layers| defines the architecture of the CNN.
% View the CNN architecture
convnet.Layers
%%
% The first layer defines the input dimensions. Each CNN has a different
% input size requirements. The one used in this example requires image
% input that is 227-by-227-by-3.
% Inspect the first layer
convnet.Layers(1)
%%
% The intermediate layers make up the bulk of the CNN. These are a series
% of convolutional layers, interspersed with rectified linear units (ReLU)
% and max-pooling layers [2]. Following the these layers are 3
% fully-connected layers.
%
% The final layer is the classification layer and its properties depend on
% the classification task. In this example, the CNN model that was loaded
% was trained to solve a 1000-way classification problem. Thus the
% classification layer has 1000 classes from the ImageNet dataset.
% Inspect the last layer
convnet.Layers(end)
% Number of class names for ImageNet classification task
numel(convnet.Layers(end).ClassNames)
%%
% Note that the CNN model is not going to be used for the original
% classification task. It is going to be re-purposed to solve a different
% classification task on the Caltech 101 dataset.
%% Pre-process Images For CNN
% As mentioned above, |convnet| can only process RGB images that are
% 227-by-227. To avoid re-saving all the images in Caltech 101 to this
% format, setup the |imds| read function, |imds.ReadFcn|, to pre-process
% images on-the-fly. The |imds.ReadFcn| is called every time an image is
% read from the |ImageDatastore|.
% Set the ImageDatastore ReadFcn
imds.ReadFcn = @(filename)readAndPreprocessImage(filename);
%%
% Note that other CNN models will have different input size constraints,
% and may require other pre-processing steps.
function Iout = readAndPreprocessImage(filename)
I = imread(filename);
% Some images may be grayscale. Replicate the image 3 times to
% create an RGB image.
if ismatrix(I)
I = cat(3,I,I,I);
end
% Resize the image as required for the CNN.
Iout = imresize(I, [227 227]);
% Note that the aspect ratio is not preserved. In Caltech 101, the
% object of interest is centered in the image and occupies a
% majority of the image scene. Therefore, preserving the aspect
% ratio is not critical. However, for other data sets, it may prove
% beneficial to preserve the aspect ratio of the original image
% when resizing.
end
%% Prepare Training and Test Image Sets
% Split the sets into training and validation data. Pick 30% of images
% from each set for the training data and the remainder, 70%, for the
% validation data. Randomize the split to avoid biasing the results. The
% training and test sets will be processed by the CNN model.
[trainingSet, testSet] = splitEachLabel(imds, 0.3, 'randomize');
%% Extract Training Features Using CNN
% Each layer of a CNN produces a response, or activation, to an input
% image. However, there are only a few layers within a CNN that are
% suitable for image feature extraction. The layers at the beginning of the
% network capture basic image features, such as edges and blobs. To see
% this, visualize the network filter weights from the first convolutional
% layer. This can help build up an intuition as to why the features
% extracted from CNNs work so well for image recognition tasks. Note that
% visualizing deeper layer weights is beyond the scope of this example. You
% can read more about that in the work of Zeiler and Fergus [4].
% Get the network weights for the second convolutional layer
w1 = convnet.Layers(2).Weights;
% Scale and resize the weights for visualization
w1 = mat2gray(w1);
w1 = imresize(w1,5);
% Display a montage of network weights. There are 96 individual sets of
% weights in the first layer.
figure
montage(w1)
title('First convolutional layer weights')
%%
% Notice how the first layer of the network has learned filters for
% capturing blob and edge features. These "primitive" features are then
% processed by deeper network layers, which combine the early features to
% form higher level image features. These higher level features are better
% suited for recognition tasks because they combine all the primitive
% features into a richer image representation [5].
%
% You can easily extract features from one of the deeper layers using the
% |activations| method. Selecting which of the deep layers to choose is a
% design choice, but typically starting with the layer right before the
% classification layer is a good place to start. In |convnet|, the this
% layer is named 'fc7'. Let's extract training features using that layer.
featureLayer = 'fc7';
trainingFeatures = activations(convnet, trainingSet, featureLayer, ...
'MiniBatchSize', 32, 'OutputAs', 'columns');
%%
% Note that the activations function automatically uses a GPU for
% processing if one is available, otherwise, a CPU is used. Because of the
% number of layers in AlexNet, using a GPU is highly recommended. Using a
% the CPU to run the network will greatly increase the time it takes to
% extract features.
%
% In the code above, the 'MiniBatchSize' is set 32 to ensure that the CNN
% and image data fit into GPU memory. You may need to lower the
% 'MiniBatchSize' if your GPU runs out of memory. Also, the activations
% output is arranged as columns. This helps speed-up the multiclass linear
% SVM training that follows.
%% Train A Multiclass SVM Classifier Using CNN Features
% Next, use the CNN image features to train a multiclass SVM classifier. A
% fast Stochastic Gradient Descent solver is used for training by setting
% the |fitcecoc| function's 'Learners' parameter to 'Linear'. This helps
% speed-up the training when working with high-dimensional CNN feature
% vectors, which each have a length of 4096.
% Get training labels from the trainingSet
trainingLabels = trainingSet.Labels;
% Train multiclass SVM classifier using a fast linear solver, and set
% 'ObservationsIn' to 'columns' to match the arrangement used for training
% features.
classifier = fitcecoc(trainingFeatures, trainingLabels, ...
'Learners', 'Linear', 'Coding', 'onevsall', 'ObservationsIn', 'columns');
%% Evaluate Classifier
% Repeat the procedure used earlier to extract image features from
% |testSet|. The test features can then be passed to the classifier to
% measure the accuracy of the trained classifier.
% Extract test features using the CNN
testFeatures = activations(convnet, testSet, featureLayer, 'MiniBatchSize',32);
% Pass CNN image features to trained classifier
predictedLabels = predict(classifier, testFeatures);
% Get the known labels
testLabels = testSet.Labels;
% Tabulate the results using a confusion matrix.
confMat = confusionmat(testLabels, predictedLabels);
% Convert confusion matrix into percentage form
confMat = bsxfun(@rdivide,confMat,sum(confMat,2))
%%
% Display the mean accuracy
mean(diag(confMat))
%% Try the Newly Trained Classifier on Test Images
% You can now apply the newly trained classifier to categorize new images.
newImage = fullfile(rootFolder, 'airplanes', 'image_0690.jpg');
% Pre-process the images as required for the CNN
img = readAndPreprocessImage(newImage);
% Extract image features using the CNN
imageFeatures = activations(convnet, img, featureLayer);
%%
% Make a prediction using the classifier
label = predict(classifier, imageFeatures)
%% References
% [1] Deng, Jia, et al. "Imagenet: A large-scale hierarchical image
% database." Computer Vision and Pattern Recognition, 2009. CVPR 2009. IEEE
% Conference on. IEEE, 2009.
%
% [2] Krizhevsky, Alex, Ilya Sutskever, and Geoffrey E. Hinton. "Imagenet
% classification with deep convolutional neural networks." Advances in
% neural information processing systems. 2012.
%
% [3] Vedaldi, Andrea, and Karel Lenc. "MatConvNet-convolutional neural
% networks for MATLAB." arXiv preprint arXiv:1412.4564 (2014).
%
% [4] Zeiler, Matthew D., and Rob Fergus. "Visualizing and understanding
% convolutional networks." Computer Vision-ECCV 2014. Springer
% International Publishing, 2014. 818-833.
%
% [5] Donahue, Jeff, et al. "Decaf: A deep convolutional activation feature
% for generic visual recognition." arXiv preprint arXiv:1310.1531 (2013).
displayEndOfDemoMessage(mfilename)
end
|
github
|
zhoujinglin/matlab-master
|
mkR.m
|
.m
|
matlab-master/video_fusion/mkR.m
| 807 |
utf_8
|
1d284110ac41a7451780fa347b65ff9f
|
% IM = mkR(SIZE, EXPT, ORIGIN)
%
% Compute a matrix of dimension SIZE (a [Y X] 2-vector, or a scalar)
% containing samples of a radial ramp function, raised to power EXPT
% (default = 1), with given ORIGIN (default = (size+1)/2, [1 1] =
% upper left). All but the first argument are optional.
% Eero Simoncelli, 6/96.
function [res] = mkR(sz, expt, origin)
sz = sz(:);
if (size(sz,1) == 1)
sz = [sz,sz];
end
% -----------------------------------------------------------------
% OPTIONAL args:
if (exist('expt') ~= 1)
expt = 1;
end
if (exist('origin') ~= 1)
origin = (sz+1)/2;
end
% -----------------------------------------------------------------
[xramp,yramp] = meshgrid( [1:sz(2)]-origin(2), [1:sz(1)]-origin(1) );
res = (xramp.^2 + yramp.^2).^(expt/2);
|
github
|
zhoujinglin/matlab-master
|
mkZonePlate.m
|
.m
|
matlab-master/video_fusion/mkZonePlate.m
| 666 |
utf_8
|
c8865ffd7d38f1f3cb5c4593ee1f7ff9
|
% IM = mkZonePlate(SIZE, AMPL, PHASE)
%
% Make a "zone plate" image:
% AMPL * cos( r^2 + PHASE)
% SIZE specifies the matrix size, as for zeros().
% AMPL (default = 1) and PHASE (default = 0) are optional.
% Eero Simoncelli, 6/96.
function [res] = mkZonePlate(sz, ampl, ph)
sz = sz(:);
if (size(sz,1) == 1)
sz = [sz,sz];
end
mxsz = max(sz(1),sz(2));
%------------------------------------------------------------
%% OPTIONAL ARGS:
if (exist('ampl') ~= 1)
ampl = 1;
end
if (exist('ph') ~= 1)
ph = 0;
end
%------------------------------------------------------------
res = ampl * cos( (pi/mxsz) * mkR(sz,2) + ph );
|
github
|
zhoujinglin/matlab-master
|
ucurvrec3d.m
|
.m
|
matlab-master/video_fusion/ucurvrec3d.m
| 3,171 |
utf_8
|
0f315695d3e044d0a538bef4d38e96db
|
function im = ucurvrec3d(ydec, Cf, F)
% UCURVREC3D 3-d ucurvelet reconstruction using normal 3-D window
%
% im = ucurvrec3d_s(ydec, Cf, F)
%
% Input:
% Sz : size of the generated window
% Cf : number of directional curvelet. In uniform curvelet, n is 3*2^n
% r : parameter of the meyer window used in diameter direction
% alpha : paramter for meyer window used in angle function
%
% Output:
% FL: 2-D window of low pass function for lower resolution curvelet
% F : cell of size n containing 2-D matrices of size s*s
%
% Example
%
% S = 512;
% Cf = [6 6];
% alpha = 0.15;
% r = pi*[0.3 0.5 0.85 1.15];
% Sz = 64;Lt = 2;
% F = ucurv_win(S, N, r, alpha);
%
% See also FUN_MEYER
%
% tic
% the multiresolution length
if size(Cf,1) == 1
Cf = kron(ones(3,1), Cf);
end
% the multiresolution length
Lt = size(Cf,2);
% Size of image at lowest resolution
SzL = size(ydec{1});
Sz = 2^Lt*SzL;
% locate im
imhf = zeros(SzL.*2^(Lt));
decim = 2^Lt*[1 1 1];
dir = 1;
Dec = sqrt(prod(decim));
% low resolution image
imhf = (1./sqrt(2))*upsamp_filtfft(ydec{1}, F{1}{1}, decim);
% for each resolution estimation
for inres = 2:(Lt+1)
% parameter for the resolution ---------------------------------------
% current size of image at resoltuion
cs = SzL.*2^(inres-1);
ncf = Cf(:,inres - 1);
% tmp_cs_com = zeros(cs+1)+sqrt(-1)*zeros(cs+1);
for dir = 1:3
switch dir
case {1}
n1 = ncf(2);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2, 2*n1/3, 2*n2/3];
case {2}
n1 = ncf(1);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2, 2*n2/3];
case {3}
n1 = ncf(1);
n2 = ncf(2);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2*n2/3, 2];
otherwise
disp('Error');
end
% switch n
% case {12}
% decim = 2^(Lt+1-inres)*[2 8 8; 8 2 8; 8 8 2];
% Dec = 16;
% case {6}
% decim = 2^(Lt+1-inres)*[2 4 4; 4 2 4; 4 4 2];
% Dec = 8;
% case {3}
% decim = 2^(Lt+1-inres)*[2 2 2; 2 2 2; 2 2 2];
% Dec = 4;
% end
% the main loop ------------------------------------------------------
for in1 = 1:n1
for in2 = 1:n2
Fc = F{inres}{dir}{in1,in2} ;
imhf = imhf + ...
upsamp_filtfft(ydec{inres}{dir}{in1,in2}, Fc, decim2);
end
end
end
% im = real(im3a+im3b);
end
im = real(ifftn(imhf));
end
% =========================================================================
function interp_fft = upsamp_filtfft(subband, filtfft, decim)
% toc
% size of subband
% disp('processing subband ...');
sz1 = size(subband);
% upsampled in freq domain
tmp = fftn(subband);
interp_fft = repmat(tmp, decim);
clear tmp;
Dec = sqrt(2*prod(decim));
% filtering
interp_fft = Dec*interp_fft.*filtfft;
% tic
end
% =========================================================================
|
github
|
zhoujinglin/matlab-master
|
ucurvdec3d_s.m
|
.m
|
matlab-master/video_fusion/ucurvdec3d_s.m
| 4,297 |
utf_8
|
8bac35e6f8a639b0f5f585c2b8feb2bc
|
function [ydec, cf_ydec] = ucurvdec3d_s(im, Cf, F2, ind2, cfind )
% UCURVDEC3D_S 3-d ucurvelet decomposition using sparse 3-D window
%
% ydec = ucurvdec3d_s(im, Cf, F2, ind2, cfind )
%
% Input:
% Sz : size of the generated window
% Cf : number of directional curvelet. In uniform curvelet, n is 3*2^n
% r : parameter of the meyer window used in diameter direction
% alpha : paramter for meyer window used in angle function
%
% Output:
% FL: 2-D window of low pass function for lower resolution curvelet
%
% Example
%
% See also FUN_MEYER
%
% History
% tic
%
%
if size(Cf,1) == 1
Cf = kron(ones(3,1), Cf);
end
% the multiresolution length
Lt = size(Cf,2);
% Size of window
im = single(im);
%
Sz = size(im);
% image for processing
% cim = im;
fim3 = fftn(im);
clear im;
% low pass band ----------------------------------------------------------
sbind = 1;
% Fc = ucurwin_extract(F2, ind2, cfind, sbind, Sz);
max_ind2 = cfind(end,1);
Fc2 = fim3(ind2(1:max_ind2)).*F2(1:max_ind2);
clear fim3 F2;
% tmp_cs_com =
ucurwin_extract(Fc2, ind2, cfind, sbind, Sz);
decim = 2^(Lt)*[1 1 1];
ydec{1} = (1./sqrt(2))*filter_decim(tmp_cs_com, decim);
Lcol = size(cfind, 1);
for incol = 2: Lcol
% incol;
% Fc = ucurwin_extract(F2, ind2, cfind, incol, Sz);
% resolution index
inres = cfind(incol, 2);
% parameter for the resolution ---------------------------------------
% current size of image at resoltuion
cs = Sz./2^(inres-1);
ncf = Cf(:,inres - 1);
in1 = cfind(incol, 3);
in2 = cfind(incol, 4);
dir = cfind(incol, 5);
% decimation ratio
switch dir
case {1}
n1 = ncf(2);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2, 2*n1/3, 2*n2/3];
case {2}
n1 = ncf(1);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2, 2*n2/3];
case {3}
n1 = ncf(1);
n2 = ncf(2);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2*n2/3, 2];
otherwise
disp('Error');
end
% tmp_cs_com =
ucurwin_extract(Fc2, ind2, cfind, incol, Sz);
ydec{inres}{dir}{in1,in2} = filter_decim(tmp_cs_com, decim2);
% tmp = filter_decim(tmp_cs_com, decim, dir);
% ltmp = prod(size(tmp));
% cf_ydec(incol,1) = cf_ydec(incol-1,1)+ltmp;
%
% % resolution - dir - dir - pyramid
% cf_ydec(incol,2:5) = cfind(incol+1,2:5);
% ydec(cf_ydec(incol-1,1)+1:cf_ydec(incol,1)) = tmp(:);
end
% =========================================================================
function ucurwin_extract(F2, ind2, cfind, sbind, Sz)
tmp_cs_com = single(zeros(Sz));
if (sbind==1)
st = 1;
else
st = cfind(sbind-1, 1)+1;
end
ind_tmp = ind2(st:cfind(sbind, 1));
val_tmp = F2(st:cfind(sbind,1));
tmp_cs_com(ind_tmp) = val_tmp;
end
% =========================================================================
% % =========================================================================
% function ucurwin_extract(F2, ind2, cfind, sbind, Sz)
% tmp_cs_com = single(zeros(Sz));
% ind_tmp = ind2(cfind(sbind, 1)+1:cfind(sbind+1, 1));
% val_tmp = F2(cfind(sbind)+1:cfind(sbind+1));
% tmp_cs_com(ind_tmp) = val_tmp;
% end
% % =========================================================================
end
% =========================================================================
function subband = filter_decim(tmp, decim)
% toc
% dir
% disp('processing subband ...');
% tmp = datfft.*filtfft;
% size of image
sz1 = size(tmp);
% decimation ratio
% decim2 = decim(dir,:);
% size of subband and shifting step
sz2 = sz1./decim;
% decim in freq domain
tmp2 = zeros(sz2);
for in1 = 0:decim(1)-1
for in2 = 0:decim(2)-1
for in3 = 0:decim(3)-1
p1 = [in1, in2, in3].*sz2+1 ;
p2 = ([in1, in2, in3]+1).*sz2;
tmp2 = tmp2 + ...
tmp(p1(1):p2(1), p1(2):p2(2), p1(3):p2(3));
end
end
end
subband = single(sqrt(2/prod(decim)).*ifftn(tmp2));
% tic
end
%
% % =========================================================================
% function Fc = ucurwin_extract(F2, ind2, cfind, sbind, Sz)
% Fc = single(zeros(Sz));
% ind_tmp = ind2(cfind(sbind, 1)+1:cfind(sbind+1, 1));
% val_tmp = F2(cfind(sbind)+1:cfind(sbind+1));
% Fc(ind_tmp) = val_tmp;
% end
|
github
|
zhoujinglin/matlab-master
|
ucurvrec3d_s.m
|
.m
|
matlab-master/video_fusion/ucurvrec3d_s.m
| 3,421 |
utf_8
|
6ef728e9d4077d1fe26222dd8d6bb03a
|
function im = ucurvrec3d_s(ydec, Cf, F2, ind2, cfind )
% UCURVREC3D_S 3-d ucurvelet reconstruction using sparse 3-D window
%
% im = ucurvrec3d_s(ydec, Cf, F2, ind2, cfind )
%
% Input:
% Sz : size of the generated window
% Cf : number of directional curvelet. In uniform curvelet, n is 3*2^n
% r : parameter of the meyer window used in diameter direction
% alpha : paramter for meyer window used in angle function
%
% Output:
% im : Reconstructed image
%
% Example
%
% Sz = [32 64 128];
% Cf = [3 6];
% r = pi*[0.3 0.5 0.85 1.15];
% alpha = 0.15;
% F2 = ucurvwin3d(Sz, Cf, r, alpha);
% im = rand(Sz);
% [F2, ind, cf] = ucurvwin3d_s(Sz, 6, r, alpha);
% ydec = ucurvdec3d_s(im, 6, F2, ind, cf );
% imr = ucurvrec3d_s(ydec, 6, F2, ind, cf );
%
% See also UCURVDEC3D_S, UCURVWIN3D_S
%
% tic
if size(Cf,1) == 1
Cf = kron(ones(3,1), Cf);
end
% the multiresolution length
Lt = size(Cf,2);
% Size of image at lowest resolution
SzL = size(ydec{1});
Sz = 2^Lt*SzL;
% locate im
imhf = zeros(SzL.*2^(Lt));
decim = 2^Lt*[1 1 1];
dir = 1;
Dec = sqrt(prod(decim));
% low resolution image
sbind = 1;
Fc = ucurwin_extract(F2, ind2, cfind, sbind, Sz);
imhf = (1./sqrt(2))*upsamp_filtfft(ydec{1}, Fc, decim);
% for each resolution estimation
Lcol = size(cfind, 1);
for incol = 2: Lcol
Fc = ucurwin_extract(F2, ind2, cfind, incol, Sz);
% resolution index
inres = cfind(incol, 2);
% parameter for the resolution ---------------------------------------
% current size of image at resoltuion
cs = SzL.*2^(inres-1);
ncf = Cf(:,inres - 1);
in1 = cfind(incol, 3);
in2 = cfind(incol, 4);
dir = cfind(incol, 5);
% decimation ratio
switch dir
case {1}
n1 = ncf(2);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2, 2*n1/3, 2*n2/3];
case {2}
n1 = ncf(1);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2, 2*n2/3];
case {3}
n1 = ncf(1);
n2 = ncf(2);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2*n2/3, 2];
otherwise
disp('Error');
end
imhf = imhf + ...
upsamp_filtfft(ydec{inres}{dir}{in1,in2}, Fc, decim2);
end
im = real(ifftn(imhf));
end
% =========================================================================
function interp_fft = upsamp_filtfft(subband, filtfft, decim)
% toc
% size of subband
% disp('processing subband ...');
sz1 = size(subband);
% decimation ratio
% decim2 = decim(dir,:);
% upsampled in freq domain
tmp = fftn(subband);
interp_fft = repmat(tmp, decim);
clear tmp;
Dec = sqrt(2*prod(decim));
% filtering
interp_fft = Dec*interp_fft.*filtfft;
% tic
end
% % =========================================================================
% function ucurwin_extract(F2, ind2, cfind, sbind, Sz)
% tmp_cs_com = single(zeros(Sz));
% if (sbind>0)
% st = 1;
% else
% st = cfind(sbind-1, 1)+1;
% end
%
% ind_tmp = ind2(st:cfind(sbind, 1));
% val_tmp = F2(st:cfind(sbind));
% tmp_cs_com(ind_tmp) = val_tmp;
% end
% % =========================================================================
% =========================================================================
function Fc = ucurwin_extract(F2, ind2, cfind, sbind, Sz)
Fc = zeros(Sz);
if (sbind==1)
st = 1;
else
st = cfind(sbind-1, 1)+1;
end
ind_tmp = ind2(st:cfind(sbind, 1));
val_tmp = F2(st:cfind(sbind));
Fc(ind_tmp) = val_tmp;
end
|
github
|
zhoujinglin/matlab-master
|
ucurvdec3d.m
|
.m
|
matlab-master/video_fusion/ucurvdec3d.m
| 3,537 |
utf_8
|
3c1056a7c969012669fc15cdb74d7a32
|
function ydec = ucurvdec3d(im, Cf, F)
% UCURVDEC3D 3-d ucurvelet decomposition using normal 3-D window
%
% ydec = ucurvdec3d_s(im, Cf, F)
%
% Input:
% Sz : size of the generated window
% Cf : number of directional curvelet. In uniform curvelet, n is 3*2^n
% r : parameter of the meyer window used in diameter direction
% alpha : paramter for meyer window used in angle function
%
% Output:
% FL: 2-D window of low pass function for lower resolution curvelet
% F : cell of size n containing 2-D matrices of size s*s
%
% Example
%
% See also FUN_MEYER
%
% History
%
% tic
if size(Cf,1) == 1
Cf = kron(ones(3,1), Cf);
end
% the multiresolution length
Lt = size(Cf,2);
% Size of window
Sz = size(im);
% image for processing
% cim = im;
fim3 = fftn(im);
% low pass band -----------------------------------------------------------
FL = F{1}{1};
tmp_cs_com = fim3.*FL;
decim = 2^(Lt)*[1 1 1];
ydec{1} = (1./sqrt(2))*filter_decim(tmp_cs_com, decim);
clear FL n;
clear tmp_cs_real tmp_cs_com;
% for each resolution estimation
for inres = 2:Lt+1
% parameter for the resolution ----------------------------------------
% current size of image at resoltuion
cs = Sz./2^(inres-1);
ncf = Cf(:,inres - 1);
for dir = 1:3
switch dir
case {1}
n1 = ncf(2);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2, 2*n1/3, 2*n2/3];
case {2}
n1 = ncf(1);
n2 = ncf(3);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2, 2*n2/3];
case {3}
n1 = ncf(1);
n2 = ncf(2);
decim2 = 2^(Lt+1-inres)*[2*n1/3, 2*n2/3, 2];
otherwise
disp('Error');
end
% % decimation ratio
% switch n
% case {12}
% decim = 2^(Lt+1-inres)*[2 8 8; 8 2 8; 8 8 2];
% Dec = 16;
% case {6}
% decim = 2^(Lt+1-inres)*[2 4 4; 4 2 4; 4 4 2];
% Dec = 8;
% case {3}
% decim = 2^(Lt+1-inres)*[2 2 2; 2 2 2; 2 2 2];
% Dec = 4;
% end
%
% FFT image at current resolution
% fim3 = fftn(cim);
% clear cim;
% the main loop ---------------------------------------------------
% in = 0;
for in1 = 1:n1
for in2 = 1:n2
Fc = F{inres}{dir}{in1,in2} ;
tmp_cs_com = fim3.*Fc;
ydec{inres}{dir}{in1,in2} = filter_decim(tmp_cs_com,decim2);
end
end
end
end
% ydec{1} = cim;
end
% =========================================================================
function subband = filter_decim(tmp, decim)
% toc
% dir
% disp('processing subband ...');
% tmp = datfft.*filtfft;
% size of image
sz1 = size(tmp);
% decimation ratio
% decim2 = decim(dir,:);
% size of subband and shifting ste
sz2 = sz1./decim;
% decim in freq domain
tmp2 = zeros(sz2);
for in1 = 0:decim(1)-1
for in2 = 0:decim(2)-1
for in3 = 0:decim(3)-1
p1 = [in1, in2, in3].*sz2+1 ;
p2 = ([in1, in2, in3]+1).*sz2;
tmp2 = tmp2 + ...
tmp(p1(1):p2(1), p1(2):p2(2), p1(3):p2(3));
end
end
end
subband = single(sqrt(2/prod(decim)).*ifftn(tmp2));
% tic
end
% =========================================================================
|
github
|
zhoujinglin/matlab-master
|
ucurvwin3d_s.m
|
.m
|
matlab-master/video_fusion/ucurvwin3d_s.m
| 13,516 |
utf_8
|
a62c1b03857e727311b10e423f6b00f4
|
function [F2, ind2, cf] = ucurvwin3d_s(Sz, Cf, r, alpha)
% UCURVWIN3D_S Generate the sparse curvelet windows that used in 3-D
% uniform curvelet inverse and foward transform
%
% [F2, ind2, cf] = ucurvwin3d_s(Sz, Cf, r, alpha)
%
% Input:
% Sz : size of the generated window
% Cf : number of directional curvelet. In uniform curvelet, n is 3*2^n
% r : parameter of the meyer window used in diameter direction
% alpha : paramter for meyer window used in angle function
%
% Output:
% F2 : a column of curvelet window value that are diff. from zero
% ind : index of position correspond to value stored in F
% cf : configuration paramter, specify ending point of window value in F
% and ind.
%
% Example
%
% Sz = [32 64 128];
% Cf = [3 6];
% r = pi*[0.3 0.5 0.85 1.15];
% alpha = 0.15;
% F2 = ucurvwin3d(Sz, Cf, r, alpha);
% im = rand(Sz);
% [F2, ind, cf] = ucurvwin3d_s(Sz, 6, r, alpha);
% ydec = ucurvdec3d_s(im, 6, F2, ind, cf );
% imr = ucurvrec3d_s(ydec, 6, F2, ind, cf );
%
% running time 6*64 - 6 sec, 6*128 - 53 sec
%
% See also UCURVDEC3D_S UCURVREC3D_S
%
if size(Cf,1) == 1
Cf = kron(ones(3,1), Cf);
end
% preallocate memory for F2 and ind2
Lcf = 1.5*prod(Sz);
F2 = single(zeros(Lcf, 1));
ind2 = uint32(zeros(Lcf, 1));
% tic
% the multiresolution length
Lt = size(Cf,2);
r = [r(1:2); r(3:4)];
for in = 1: Lt-1
r = [0.5*r(1,:); r ];
end
% Size of window
if max(size(Sz)) == 1
Sz = [Sz Sz Sz];
end
cs = Sz;
% create the grid
S1 = -1.5*pi:pi/(cs(1)/2):(0.5*pi-pi/(cs(1)/2));
S2 = -1.5*pi:pi/(cs(2)/2):(0.5*pi-pi/(cs(2)/2));
S3 = -1.5*pi:pi/(cs(3)/2):(0.5*pi-pi/(cs(3)/2));
% create the mesh for estimate the angle function v(T(theta)) ---------
[M31, M32] = adapt_grid(S1, S2);
[M12, M13] = adapt_grid(S2, S3);
[M21, M23] = adapt_grid(S1, S3);
% pack;
% for each resolution estimation
for inres = 2:Lt+1
% parameter for the resolution ---------------------------------------
% current size of image at resoltuion
cs = Sz;
% inres2 = Lt +2 - inres;
ncf = Cf(:,inres-1);
mncf = max(ncf);
clear tmp_cs_real tmp_cs_com;
% Low - high pass window ---------------------------------------------
f1 = single(fun_meyer(abs(S1),[-2 -1 r(inres-1,:)]));
f2 = single(fun_meyer(abs(S2),[-2 -1 r(inres-1,:)]));
f3 = single(fun_meyer(abs(S3),[-2 -1 r(inres-1,:)]));
% 3-d window
FL3 = repmat(f1(:), [1, cs(2), cs(3)]).* ...
permute(repmat(f2(:), [1, cs(1), cs(3)]),[2, 1, 3] ).* ...
permute(repmat(f3(:), [1, cs(1), cs(2)]),[2, 3, 1]);
f1 = single(fun_meyer(abs(S1),[-2 -1 r(inres,:)]));
f2 = single(fun_meyer(abs(S2),[-2 -1 r(inres,:)]));
f3 = single(fun_meyer(abs(S3),[-2 -1 r(inres,:)]));
% 3-d window
FR3 = repmat(f1(:), [1, cs(2), cs(3)]).* ...
permute(repmat(f2(:), [1, cs(1), cs(3)]),[2, 1, 3] ).* ...
permute(repmat(f3(:), [1, cs(1), cs(2)]),[2, 3, 1]);
% high pass window
FR3 = single(sqrt(FR3-FL3));
% low pass band ------------------------------------------------------
% if inres == 2
% FL = sqrt(circshift(FL3(1:cs(1),1:cs(2),1:cs(3)), 0.25*cs ));
% F2{1}{inres-1} = FL;
% clear FL FL3;
% end
% low pass band ------------------------------------------------------
if inres == 2
sbind = 1;
FL = sqrt(circshift(FL3, 0.25*cs ));
ind3 = find(FL);
lind3 = length(ind3);
% append index to ind2
ind2(1: lind3) = uint32(ind3(:));
% append value F2
F2(1: lind3) = FL(ind3);
% append configuration information
% cf = [cf; cf(end,1)+lind3, inres, in1, in2, dir];
% ind2 = find(FL);
% F2 = FL(ind2);
cf(sbind, 1) = lind3;
cf(sbind, 2:5) = [1 1 1 1];
% cf = cf(:);
clear FL FL3;
end
% angle meyer window -------------------------------------------------
% angd = 4/(2*mncf);
% ang = angd*[-alpha alpha 1-alpha 1+alpha];
% angex = angd*[-2*alpha 2*alpha 1-2*alpha 1+2*alpha];
alpha2 = alpha*4/(2*mncf);
for in = 1:3
n = ncf(in);
angd = 4/(2*n);
ang = [-alpha2,alpha2,(angd-alpha2),(angd+alpha2)];
if (n == 3)
n2 = 2;
else
n2 = n/2;
end
for in2 = 1:n2
ang2 = -1+(in2-1)*angd+ang;
switch in
case {1}
fang{3}{1}{in2} = sqrt(single(fun_meyer(M21,ang2)));
fang{2}{1}{in2} = sqrt(single(fun_meyer(M31,ang2)));
case {2}
fang{1}{1}{in2} = sqrt(single(fun_meyer(M32,ang2)));
fang{3}{2}{in2} = sqrt(single(fun_meyer(M12,ang2)));
case {3}
fang{2}{2}{in2} = sqrt(single(fun_meyer(M13,ang2)));
fang{1}{2}{in2} = sqrt(single(fun_meyer(M23,ang2)));
end
end
end
% the very first filter require special handling
% estimate the index of the point that need to be scale ---------------
% first 3-D angle
FA = repmat(fang{1}{1}{1},[1, 1, cs(3)]);
FB = repmat(fang{1}{2}{1},[1, 1, cs(2)]);
ang1 = FA.*permute(FB,[1, 3, 2]);
% second 3-D angle
FA = repmat(fang{2}{1}{1},[1, 1, cs(3)]);
FB = repmat(fang{2}{2}{1},[1, 1, cs(1)]);
ang2 = FA.*permute(FB,[3, 1, 2]);
% third 3-D angle
FA = repmat(fang{3}{1}{1},[1, 1, cs(2)]);
FB = repmat(fang{3}{2}{1},[1, 1, cs(1)]);
ang3 = permute(FA,[1, 3, 2]).*...
permute(FB,[3, 1, 2]);
ind = find(and( and ((ang1>0), (ang2>0)), (ang3>0) ));
G1ex = ang1.^2 + ang2.^2 + ang3.^2;
G1ex = sqrt(G1ex(ind));
clear ang1 ang2 ang3;
% finish estimate ind and summation.
clear n
for in = 1:3
if (ncf(in) == 3)
ncf2(in) = 2;
else
ncf2(in) = ncf(in)/2;
end
end
% the main loop ------------------------------------------------------
% in = 0;
for dir = 1:3
switch dir
case {1}
for in1 = 1:ncf2(2)
for in2 = 1:ncf2(3)
FA = repmat(fang{1}{1}{in1},[1, 1, cs(3)]);
FB = permute(repmat(fang{1}{2}{in2},[1, 1, cs(2)]),[1, 3, 2]);
tmp_cs_real = FA.*FB.*FR3;
% now normalize those points in the angle wedge
tmp_cs_real(ind) = tmp_cs_real(ind)./G1ex;
clear FA FB;
F = circshift((tmp_cs_real(1:cs(1), 1:cs(2), 1:cs(3))), ...
[0.25*cs(1), 0.25*cs(2) , 0.25*cs(3)]);
% F2{inres}{dir}{in1,in2} = F;
addwindow2(F, inres, in1, in2, dir);
if (in2~=ncf(3)+1-in2)
Fc = rotate_ucurv3d_nest(F, 3);
% F2{inres}{dir}{in1, ncf(3)+1-in2} = Fc;
addwindow2(Fc, inres, in1, ncf(3)+1-in2, dir);
end
if (in1~=ncf(2)+1-in1)
Fc = rotate_ucurv3d_nest(F, 2);
% F2{inres}{dir}{ncf(2)+1-in1,in2} = Fc;
addwindow2(Fc, inres, ncf(2)+1-in1, in2, dir);
end
if and(in1~=ncf(2)+1-in1, in2~=ncf(3)+1-in2)
Fc = rotate_ucurv3d_nest(F, [3 ,2]);
% F2{inres}{dir}{ncf(2)+1-in1,ncf(3)+1-in2} = Fc;
addwindow2(Fc, inres, ncf(2)+1-in1, ncf(3)+1-in2, dir);
end
end
end
case {2}
for in1 = 1:ncf2(1)
for in2 = 1:ncf2(3)
FA = repmat(fang{2}{1}{in1},[1, 1, cs(3)]);
FB = permute(repmat(fang{2}{2}{in2},[1, 1, cs(1)]),[3, 1, 2]);
tmp_cs_real = FA.*FB.*FR3;
% now normalize those points in the angle wedge
tmp_cs_real(ind) = tmp_cs_real(ind)./G1ex;
clear FA FB;
F = circshift((tmp_cs_real(1:cs(1), 1:cs(2), 1:cs(3))), ...
[0.25*cs(1), 0.25*cs(2) , 0.25*cs(3)]);
% F2{inres}{dir}{in1,in2} = F;
addwindow2(F, inres, in1, in2, dir);
if (in2~=ncf(3)+1-in2)
Fc = rotate_ucurv3d_nest(F, 3);
% F2{inres}{dir}{in1, ncf(3)+1-in2} = Fc;
addwindow2(Fc, inres, in1, ncf(3)+1-in2, dir);
end
if (in1~=ncf(1)+1-in1)
Fc = rotate_ucurv3d_nest(F, 1);
% F2{inres}{dir}{ncf(1)+1-in1,in2} = Fc;
addwindow2(Fc, inres, ncf(1)+1-in1, in2, dir);
end
if and(in1~=ncf(1)+1-in1, in2~=ncf(3)+1-in2)
Fc = rotate_ucurv3d_nest(F, [3, 1]);
% F2{inres}{dir}{ncf(1)+1-in1,ncf(3)+1-in2} = Fc;
addwindow2(Fc, inres, ncf(1)+1-in1, ncf(3)+1-in2, dir);
end
end
end
case {3}
for in1 = 1:ncf2(1)
for in2 = 1:ncf2(2)
FA = permute(repmat(fang{3}{1}{in1},[1, 1, cs(2)]),[ 1 3 2]);
FB = permute(repmat(fang{3}{2}{in2},[1, 1, cs(1)]),[3, 1, 2]);
tmp_cs_real = FA.*...
FB.*FR3;
% now normalize those points in the angle wedge
tmp_cs_real(ind) = tmp_cs_real(ind)./G1ex;
clear FA FB;
F = circshift((tmp_cs_real(1:cs(1), 1:cs(2), 1:cs(3))), ...
[0.25*cs(1), 0.25*cs(2) , 0.25*cs(3)]);
% F2{inres}{dir}{in1,in2} = F;
addwindow2(F, inres, in1, in2, dir);
if (in2~=ncf(2)+1-in2)
Fc = rotate_ucurv3d_nest(F, 2);
% F2{inres}{dir}{in1, ncf(2)+1-in2} = Fc;
addwindow2(Fc, inres, in1, ncf(2)+1-in2, dir);
end
if (in1~=ncf(1)+1-in1)
Fc = rotate_ucurv3d_nest(F, 1);
% F2{inres}{dir}{ncf(1)+1-in1, in2} = Fc;
addwindow2(Fc, inres, ncf(1)+1-in1, in2, dir);
end
if and(in1~=ncf(1)+1-in1, in2~=ncf(2)+1-in2)
Fc = rotate_ucurv3d_nest(F, [1, 2]);
% F2{inres}{dir}{ncf(1)+1-in1,ncf(2)+1-in2} = Fc;
addwindow2(Fc, inres, ncf(1)+1-in1, ncf(2)+1-in2, dir);
end
end
end
otherwise
disp('Error switch');
end
end
end
% addwindow2 --------------------------------------------------------------
% nested function to handle sbind, F2, ind2, cf
function addwindow2(tmp, inres, in1, in2, dir)
sbind = sbind+1;
% index and length
ind3 = find(tmp); %
lind3 = length(ind3);
% append index to ind2
ind2(cf(end,1)+1: cf(end,1)+lind3) = uint32(ind3(:));
% append value F2
F2(cf(end,1)+1: cf(end,1)+lind3) = tmp(ind3);
% append configuration information
cf = [cf; cf(end,1)+lind3, inres, in1, in2, dir];
end
% ------------------------------------------------------------------------
end
%--------------------------------------------------------------------------
% utility functions
%--------------------------------------------------------------------------
% flip 3-D matrix function ------------------------------------------------
function Fc = rotate_ucurv3d_nest(F, para)
Fc = F;
for in = 1: length(para)
switch para(in)
case {1}
Fc = circshift(flipdim(Fc, 1), [1 0 0]);
case {2}
Fc = circshift(flipdim(Fc, 2), [0 1 0]);
case {3}
Fc = circshift(flipdim(Fc, 3), [0 0 1]);
otherwise
disp('Error');
end
end
end
% create 2-D grid function-------------------------------------------------
function [M1, M2] = adapt_grid(S1, S2)
[x1, x2] = meshgrid(S2,S1);
% scale the grid approximate the tan theta function ------------------
% creat two scale grid for mostly horizontal and vertical direction
% first grid
t1 = zeros(size(x1));
ind = and(x1~=0, abs(x2) <= abs(x1));
t1(ind) = -x2(ind)./x1(ind);
t2 = zeros(size(x1));
ind = and(x2~=0, abs(x1) < abs(x2));
t2(ind) = x1(ind)./x2(ind);
t3 = t2;
t3(t2<0) = t2(t2<0)+2;
t3(t2>0) = t2(t2>0)-2;
M1 = t1+t3;
M1(x1>=0) = -2;
% second grid
t1 = zeros(size(x1));
ind = and(x2~=0, abs(x1) <= abs(x2));
t1(ind) = -x1(ind)./x2(ind);
t2 = zeros(size(x1));
ind = and(x1~=0, abs(x2) < abs(x1));
t2(ind) = x2(ind)./x1(ind);
t3 = t2;
t3(t2<0) = t2(t2<0)+2;
t3(t2>0) = t2(t2>0)-2;
M2 = t1+t3;
M2(x2>=0) = -2;
clear t1 t2 t3;
end
% addwindow --------------------------------------------------------------
function [sbind, F2, ind, cf] = addwindow(sbind, F2, ind, cf, tmp, inres, in1, in2, dir)
sbind = sbind+1;
ind2 = find(abs(tmp)>10^(-9));
ind = [ind;ind2];
F2 = [F2;tmp(ind2)];
cf = [cf;length(F2), inres, in1, in2, dir];
end
|
github
|
zhoujinglin/matlab-master
|
ucurvwin3d.m
|
.m
|
matlab-master/video_fusion/ucurvwin3d.m
| 9,774 |
utf_8
|
b2d4a9150b181494e86ae0331f19eb0d
|
function F2 = ucurvwin3d(Sz, Cf, r, alpha)
% UCURV_WIN3D Generate the curvelet windows that used in 3-D uniform curvelet
% inverse and foward transform
%
% F = ucurv_win(Sz, Cf, r, alpha)
%
% Input:
% Sz : size of the generated window
% Cf : number of directional curvelet. In uniform curvelet, n is 3*2^n
% r : parameter of the meyer window used in diameter direction
% alpha : paramter for meyer window used in angle function
%
% Output:
% FL: 2-D window of low pass function for lower resolution curvelet
% F : cell of size n containing 2-D matrices of size s*s
%
% Example
%
% S = 512;
% Cf = [6 6];
% alpha = 0.15;
% r = pi*[0.3 0.5 0.85 1.15];
% Sz = 64;Lt = 2;
% F = ucurv_win(S, N, r, alpha);
%
% See also UCURVDEC3D_S UCURVREC3D_S
%
% tic
% the multiresolution length
%
if size(Cf,1) == 1
Cf = kron(ones(3,1), Cf);
end
Lt = size(Cf,2);
r = [r(1:2); r(3:4)];
for in = 1: Lt-1
r = [0.5*r(1,:); r ];
end
% Size of window
if max(size(Sz)) == 1
Sz = [Sz Sz Sz];
end
cs = Sz;
% create the grid
S1 = -1.5*pi:pi/(cs(1)/2):(0.5*pi-pi/(cs(1)/2));
S2 = -1.5*pi:pi/(cs(2)/2):(0.5*pi-pi/(cs(2)/2));
S3 = -1.5*pi:pi/(cs(3)/2):(0.5*pi-pi/(cs(3)/2));
% create the mesh for estimate the angle function v(T(theta)) ---------
[M31, M32] = adapt_grid(S1, S2);
[M12, M13] = adapt_grid(S2, S3);
[M21, M23] = adapt_grid(S1, S3);
% for each resolution estimation
for inres = 2:Lt+1
% parameter for the resolution ---------------------------------------
% current size of image at resoltuion
cs = Sz;
% inres2 = Lt +2 - inres;
ncf = Cf(:,inres-1);
mncf = max(ncf);
clear tmp_cs_real tmp_cs_com;
% Low - high pass window ---------------------------------------------
f1 = single(fun_meyer(abs(S1),[-2 -1 r(inres-1,:)]));
f2 = single(fun_meyer(abs(S2),[-2 -1 r(inres-1,:)]));
f3 = single(fun_meyer(abs(S3),[-2 -1 r(inres-1,:)]));
% 3-d window
FL3 = repmat(f1(:), [1, cs(2), cs(3)]).* ...
permute(repmat(f2(:), [1, cs(1), cs(3)]),[2, 1, 3] ).* ...
permute(repmat(f3(:), [1, cs(1), cs(2)]),[2, 3, 1]);
f1 = single(fun_meyer(abs(S1),[-2 -1 r(inres,:)]));
f2 = single(fun_meyer(abs(S2),[-2 -1 r(inres,:)]));
f3 = single(fun_meyer(abs(S3),[-2 -1 r(inres,:)]));
% 3-d window
FR3 = repmat(f1(:), [1, cs(2), cs(3)]).* ...
permute(repmat(f2(:), [1, cs(1), cs(3)]),[2, 1, 3] ).* ...
permute(repmat(f3(:), [1, cs(1), cs(2)]),[2, 3, 1]);
% high pass window
FR3 = FR3-FL3;
% low pass band ------------------------------------------------------
if inres == 2
FL = sqrt(circshift(FL3(1:cs(1),1:cs(2),1:cs(3)), 0.25*cs ));
F2{1}{inres-1} = FL;
clear FL FL3;
end
% angle meyer window -------------------------------------------------
% angd = 4/(2*mncf);
% ang = angd*[-alpha alpha 1-alpha 1+alpha];
% angex = angd*[-2*alpha 2*alpha 1-2*alpha 1+2*alpha];
alpha2 = alpha*4/(2*mncf);
for in = 1:3
n = ncf(in);
angd = 4/(2*n);
ang = [-alpha2,alpha2,(angd-alpha2),(angd+alpha2)];
if (n == 3)
n2 = 2;
else
n2 = n/2;
end
for in2 = 1:n2
ang2 = -1+(in2-1)*angd+ang;
switch in
case {1}
fang{3}{1}{in2} = single(fun_meyer(M21,ang2));
fang{2}{1}{in2} = single(fun_meyer(M31,ang2));
case {2}
fang{1}{1}{in2} = single(fun_meyer(M32,ang2));
fang{3}{2}{in2} = single(fun_meyer(M12,ang2));
case {3}
fang{2}{2}{in2} = single(fun_meyer(M13,ang2));
fang{1}{2}{in2} = single(fun_meyer(M23,ang2));
end
end
end
% the very first filter require special handling
% estimate the index of the point that need to be scale ---------------
% first 3-D angle
FA = repmat(fang{1}{1}{1},[1, 1, cs(3)]);
FB = repmat(fang{1}{2}{1},[1, 1, cs(2)]);
ang1 = FA.*permute(FB,[1, 3, 2]);
% second 3-D angle
FA = repmat(fang{2}{1}{1},[1, 1, cs(3)]);
FB = repmat(fang{2}{2}{1},[1, 1, cs(1)]);
ang2 = FA.*permute(FB,[3, 1, 2]);
% third 3-D angle
FA = repmat(fang{3}{1}{1},[1, 1, cs(2)]);
FB = repmat(fang{3}{2}{1},[1, 1, cs(1)]);
ang3 = permute(FA,[1, 3, 2]).*...
permute(FB,[3, 1, 2]);
ind = and( and ((ang1>0), (ang2>0)), (ang3>0) );
G1ex = ang1 + ang2 + ang3;
clear ang1 ang2 ang3;
% finish estimate ind and summation.
clear n
for in = 1:3
if (ncf(in) == 3)
ncf2(in) = 2;
else
ncf2(in) = ncf(in)/2;
end
end
% the main loop ------------------------------------------------------
% in = 0;
for dir = 1:3
switch dir
case {1}
for in1 = 1:ncf2(2)
for in2 = 1:ncf2(3)
FA = repmat(fang{1}{1}{in1},[1, 1, cs(3)]);
FB = repmat(fang{1}{2}{in2},[1, 1, cs(2)]);
tmp_cs_real = FA.*permute(FB,[1, 3, 2]).*FR3;
% now normalize those points in the angle wedge
tmp_cs_real(ind) = tmp_cs_real(ind)./G1ex(ind);
clear FA FB;
F = circshift(sqrt(tmp_cs_real(1:cs(1), 1:cs(2), 1:cs(3))), ...
[0.25*cs(1), 0.25*cs(2) , 0.25*cs(3)]);
F2{inres}{dir}{in1,in2} = F;
Fc = rotate_ucurv3d_nest(F, 3);
F2{inres}{dir}{in1, ncf(3)+1-in2} = Fc;
Fc = rotate_ucurv3d_nest(F, 2);
F2{inres}{dir}{ncf(2)+1-in1,in2} = Fc;
Fc = rotate_ucurv3d_nest(F, [3 ,2]);
F2{inres}{dir}{ncf(2)+1-in1,ncf(3)+1-in2} = Fc;
end
end
case {2}
for in1 = 1:ncf2(1)
for in2 = 1:ncf2(3)
FA = repmat(fang{2}{1}{in1},[1, 1, cs(3)]);
FB = repmat(fang{2}{2}{in2},[1, 1, cs(1)]);
tmp_cs_real = FA.*permute(FB,[3, 1, 2]).*FR3;
% now normalize those points in the angle wedge
tmp_cs_real(ind) = tmp_cs_real(ind)./G1ex(ind);
clear FA FB;
F = circshift(sqrt(tmp_cs_real(1:cs(1), 1:cs(2), 1:cs(3))), ...
[0.25*cs(1), 0.25*cs(2) , 0.25*cs(3)]);
F2{inres}{dir}{in1,in2} = F;
Fc = rotate_ucurv3d_nest(F, 3);
F2{inres}{dir}{in1, ncf(3)+1-in2} = Fc;
Fc = rotate_ucurv3d_nest(F, 1);
F2{inres}{dir}{ncf(1)+1-in1,in2} = Fc;
Fc = rotate_ucurv3d_nest(F, [3, 1]);
F2{inres}{dir}{ncf(1)+1-in1,ncf(3)+1-in2} = Fc;
end
end
case {3}
for in1 = 1:ncf2(1)
for in2 = 1:ncf2(2)
FA = repmat(fang{3}{1}{in1},[1, 1, cs(2)]);
FB = repmat(fang{3}{2}{in2},[1, 1, cs(1)]);
tmp_cs_real = permute(FA,[ 1 3 2]).*...
permute(FB,[3, 1, 2]).*FR3;
% now normalize those points in the angle wedge
tmp_cs_real(ind) = tmp_cs_real(ind)./G1ex(ind);
clear FA FB;
F = circshift(sqrt(tmp_cs_real(1:cs(1), 1:cs(2), 1:cs(3))), ...
[0.25*cs(1), 0.25*cs(2) , 0.25*cs(3)]);
F2{inres}{dir}{in1,in2} = F;
Fc = rotate_ucurv3d_nest(F, 2);
F2{inres}{dir}{in1, ncf(2)+1-in2} = Fc;
Fc = rotate_ucurv3d_nest(F, 1);
F2{inres}{dir}{ncf(1)+1-in1, in2} = Fc;
Fc = rotate_ucurv3d_nest(F, [1, 2]);
F2{inres}{dir}{ncf(1)+1-in1,ncf(2)+1-in2} = Fc;
end
end
otherwise
disp('Error switch');
end
end
end
end
%--------------------------------------------------------
% utility function
%--------------------------------------------------------
% flip 3-D matrix function ------------------------------------------------
function Fc = rotate_ucurv3d_nest(F, para)
Fc = F;
for in = 1: length(para)
switch para(in)
case {1}
Fc = circshift(flipdim(Fc, 1), [1 0 0]);
case {2}
Fc = circshift(flipdim(Fc, 2), [0 1 0]);
case {3}
Fc = circshift(flipdim(Fc, 3), [0 0 1]);
otherwise
disp('Error');
end
end
end
% create 2-D grid function-------------------------------------------------
function [M1, M2] = adapt_grid(S1, S2)
[x1, x2] = meshgrid(S2,S1);
% scale the grid approximate the tan theta function ------------------
% creat two scale grid for mostly horizontal and vertical direction
% firt grid
t1 = zeros(size(x1));
ind = and(x1~=0, abs(x2) <= abs(x1));
t1(ind) = -x2(ind)./x1(ind);
t2 = zeros(size(x1));
ind = and(x2~=0, abs(x1) < abs(x2));
t2(ind) = x1(ind)./x2(ind);
t3 = t2;
t3(t2<0) = t2(t2<0)+2;
t3(t2>0) = t2(t2>0)-2;
M1 = t1+t3;
M1(x1>=0) = -2;
% second grid
t1 = zeros(size(x1));
ind = and(x2~=0, abs(x1) <= abs(x2));
t1(ind) = -x1(ind)./x2(ind);
t2 = zeros(size(x1));
ind = and(x1~=0, abs(x2) < abs(x1));
t2(ind) = x2(ind)./x1(ind);
t3 = t2;
t3(t2<0) = t2(t2<0)+2;
t3(t2>0) = t2(t2>0)-2;
M2 = t1+t3;
M2(x2>=0) = -2;
clear t1 t2 t3;
end
|
github
|
zhoujinglin/matlab-master
|
iisum.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/iisum.m
| 390 |
utf_8
|
065f814dffc187bce6e3caf48b6b642a
|
%---------------------------------------------------------
%---------------------------------------------------------
function sum = iisum(iimg,x1,y1,x2,y2)
if(x1>1 && y1>1)
sum = iimg(y2,x2)+iimg(y1-1,x1-1)-iimg(y1-1,x2)-iimg(y2,x1-1);
elseif(x1<=1 && y1>1)
sum = iimg(y2,x2)-iimg(y1-1,x2);
elseif(y1<=1 && x1>1)
sum = iimg(y2,x2)-iimg(y2,x1-1);
else
sum = iimg(y2,x2);
end
|
github
|
zhoujinglin/matlab-master
|
fdct_wrapping_dispcoef.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/fdct_wrapping_matlab/fdct_wrapping_dispcoef.m
| 1,919 |
utf_8
|
2af5a55f76ce583e6879244514db1b37
|
function img = fdct_wrapping_dispcoef(C)
% fdct_wrapping_dispcoef - returns an image containing all the curvelet coefficients
%
% Inputs
% C Curvelet coefficients
%
% Outputs
% img Image containing all the curvelet coefficients. The coefficents are rescaled so that
% the largest coefficent in each subband has unit norm.
%
[m,n] = size(C{end}{1});
nbscales = floor(log2(min(m,n)))-3;
img = C{1}{1}; img = img/max(max(abs(img))); %normalize
for sc=2:nbscales-1
nd = length(C{sc})/4;
wcnt = 0;
ONE = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
ONE = [ONE, fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w})];
end
wcnt = wcnt+nd;
TWO = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
TWO = [TWO; fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w})];
end
wcnt = wcnt+nd;
THREE = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
THREE = [fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w}), THREE];
end
wcnt = wcnt+nd;
FOUR = [];
[u,v] = size(C{sc}{wcnt+1});
for w=1:nd
FOUR = [fdct_wrapping_dispcoef_expand(u,v,C{sc}{wcnt+w}); FOUR];
end
wcnt = wcnt+nd;
[p,q] = size(img);
[a,b] = size(ONE);
[g,h] = size(TWO);
m = 2*a+g; n = 2*h+b; %size of new image
scale = max(max( max(max(abs(ONE))),max(max(abs(TWO))) ), max(max(max(abs(THREE))), max(max(abs(FOUR))) )); %scaling factor
new = 0.5 * ones(m,n);%background value
new(a+1:a+g,1:h) = FOUR/scale;
new(a+g+1:2*a+g,h+1:h+b) = THREE/scale;
new(a+1:a+g,h+b+1:2*h+b) = TWO/scale;
new(1:a,h+1:h+b) = ONE/scale;%normalize
dx = floor((g-p)/2); dy = floor((b-q)/2);
new(a+1+dx:a+p+dx,h+1+dy:h+q+dy) = img;
img = new;
end
function A = fdct_wrapping_dispcoef_expand(u,v,B)
A = zeros(u,v);
[p,q] = size(B);
A(1:p,1:q) = B;
|
github
|
zhoujinglin/matlab-master
|
extend2.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/nsct_toolbox/extend2.m
| 1,792 |
utf_8
|
607c7de17e89483c3983b26b6987cb80
|
function y = extend2(x, ru, rd, cl, cr, extmod)
% EXTEND2 2D extension
%
% y = extend2(x, ru, rd, cl, cr, extmod)
%
% Input:
% x: input image
% ru, rd: amount of extension, up and down, for rows
% cl, cr: amount of extension, left and rigth, for column
% extmod: extension mode. The valid modes are:
% 'per': periodized extension (both direction)
% 'qper_row': quincunx periodized extension in row
% 'qper_col': quincunx periodized extension in column
%
% Output:
% y: extended image
%
% Note:
% Extension modes 'qper_row' and 'qper_col' are used multilevel
% quincunx filter banks, assuming the original image is periodic in
% both directions. For example:
% [y0, y1] = fbdec(x, h0, h1, 'q', '1r', 'per');
% [y00, y01] = fbdec(y0, h0, h1, 'q', '2c', 'qper_col');
% [y10, y11] = fbdec(y1, h0, h1, 'q', '2c', 'qper_col');
%
% See also: FBDEC
[rx, cx] = size(x);
switch extmod
case 'per'
I = getPerIndices(rx, ru, rd);
y = x(I, :);
I = getPerIndices(cx, cl, cr);
y = y(:, I);
case 'qper_row'
rx2 = round(rx / 2);
y = [[x(rx2+1:rx, cx-cl+1:cx); x(1:rx2, cx-cl+1:cx)], x, ...
[x(rx2+1:rx, 1:cr); x(1:rx2, 1:cr)]];
I = getPerIndices(rx, ru, rd);
y = y(I, :);
case 'qper_col'
cx2 = round(cx / 2);
y = [x(rx-ru+1:rx, cx2+1:cx), x(rx-ru+1:rx, 1:cx2); x; ...
x(1:rd, cx2+1:cx), x(1:rd, 1:cx2)];
I = getPerIndices(cx, cl, cr);
y = y(:, I);
otherwise
error('Invalid input for EXTMOD')
end
%----------------------------------------------------------------------------%
% Internal Function(s)
%----------------------------------------------------------------------------%
function I = getPerIndices(lx, lb, le)
I = [lx-lb+1:lx , 1:lx , 1:le];
if (lx < lb) | (lx < le)
I = mod(I, lx);
I(I==0) = lx;
end
|
github
|
zhoujinglin/matlab-master
|
gen_x_y_cordinates.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/shearlet_toolbox/gen_x_y_cordinates.m
| 2,307 |
utf_8
|
48e8b6cf36ec28307441e81a22da1b11
|
function [x1n,y1n,x2n,y2n,D]=gen_x_y_cordinates(n)
%
% This function generates the x and y vectors that contain
% the i,j coordinates to extract radial slices
%
% Input: n is the order of the block to be used
%
% Outputs: x1,y1 are the i,j values that correspond to
% the radial slices from the endpoints 1,1 to n,1
% through the origin
%
% x2,y2 are the i,j values that correspond to
% the radial slices from the endpoints 1,1 to 1,n
% through the origin
%
% D is the matrix that contains the number of times
% the polar grid points go through the rectangular grid
%
% Written by Glenn Easley on December 11, 2001.
% Copyright 2011 by Glenn R. Easley. All Rights Reserved.
%
n=n+1;
% initialize vectors
x1=zeros(n,n);
y1=zeros(n,n);
x2=zeros(n,n);
y2=zeros(n,n);
xt=zeros(1,n);
m=zeros(1,n);
for i=1:n,
y0=1; x0=i; x_n=n-i+1; y_n=n;
if (x_n==x0),
flag=1;
else
m1(i)= (y_n-y0)/(x_n-x0);
flag=0;
end
xt(i,:)=linspace(x0,x_n,n);
for j=1:n,
if flag==0,
y1(i,j)=m1(i)*(xt(i,j)-x0)+y0;
y1(i,j)=round(y1(i,j));
x1(i,j)=round(xt(i,j));
x2(i,j)=y1(i,j);
y2(i,j)=x1(i,j);
else
x1(i,j)=(n-1)/2+1;
y1(i,j)=j;
x2(i,j)=j;
y2(i,j)=(n-1)/2+1;
end
end
end
n=n-1;
x1n=zeros(n,n);
y1n=zeros(n,n);
x2n=zeros(n,n);
y2n=zeros(n,n);
for i=1:n,
for j=1:n,
x1n(i,j)=x1(i,j);
y1n(i,j)=y1(i,j);
x2n(i,j)=x2(i+1,j);
y2n(i,j)=y2(i+1,j);
end
end
% correct for portion outside boundry
x1n=flipud(x1n);
y2n(n,1)=n;
%y2n=flipud(y2n);
D=avg_pol(n,x1n,y1n,x2n,y2n);
% end of gen_x_y_cord function
function D=avg_pol(L,x1,y1,x2,y2)
%
% This function generates the matrix that contains the number
% of times the polar grid points go through the rectangular grid
% point i,j
%
% Input: L is the order of the block matrix
%
% Output: D is the common grid point values
%
% Written by Glenn Easley on December 11, 2001.
%
D=zeros(L);
for i=1:L,
for j=1:L,
D(y1(i,j),x1(i,j))=D(y1(i,j),x1(i,j))+1;
end
end
for i=1:L,
for j=1:L,
D(y2(i,j),x2(i,j))=D(y2(i,j),x2(i,j))+1;
end
end
% end of avg_pol function
|
github
|
zhoujinglin/matlab-master
|
colorspace.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/dtcwt_toolbox/colorspace.m
| 13,590 |
utf_8
|
b1a9eb973fa39950345a1df707b5d2c8
|
function varargout = colorspace(Conversion,varargin)
%COLORSPACE Convert a color image between color representations.
% B = COLORSPACE(S,A) converts the color representation of image A
% where S is a string specifying the conversion. S tells the
% source and destination color spaces, S = 'dest<-src', or
% alternatively, S = 'src->dest'. Supported color spaces are
%
% 'RGB' R'G'B' Red Green Blue (ITU-R BT.709 gamma-corrected)
% 'YPbPr' Luma (ITU-R BT.601) + Chroma
% 'YCbCr'/'YCC' Luma + Chroma ("digitized" version of Y'PbPr)
% 'YUV' NTSC PAL Y'UV Luma + Chroma
% 'YIQ' NTSC Y'IQ Luma + Chroma
% 'YDbDr' SECAM Y'DbDr Luma + Chroma
% 'JPEGYCbCr' JPEG-Y'CbCr Luma + Chroma
% 'HSV'/'HSB' Hue Saturation Value/Brightness
% 'HSL'/'HLS'/'HSI' Hue Saturation Luminance/Intensity
% 'XYZ' CIE XYZ
% 'Lab' CIE L*a*b* (CIELAB)
% 'Luv' CIE L*u*v* (CIELUV)
% 'Lch' CIE L*ch (CIELCH)
%
% All conversions assume 2 degree observer and D65 illuminant. Color
% space names are case insensitive. When R'G'B' is the source or
% destination, it can be omitted. For example 'yuv<-' is short for
% 'yuv<-rgb'.
%
% MATLAB uses two standard data formats for R'G'B': double data with
% intensities in the range 0 to 1, and uint8 data with integer-valued
% intensities from 0 to 255. As MATLAB's native datatype, double data is
% the natural choice, and the R'G'B' format used by colorspace. However,
% for memory and computational performance, some functions also operate
% with uint8 R'G'B'. Given uint8 R'G'B' color data, colorspace will
% first cast it to double R'G'B' before processing.
%
% If A is an Mx3 array, like a colormap, B will also have size Mx3.
%
% [B1,B2,B3] = COLORSPACE(S,A) specifies separate output channels.
% COLORSPACE(S,A1,A2,A3) specifies separate input channels.
% Pascal Getreuer 2005-2006
%%% Input parsing %%%
if nargin < 2, error('Not enough input arguments.'); end
[SrcSpace,DestSpace] = parse(Conversion);
if nargin == 2
Image = varargin{1};
elseif nargin >= 3
Image = cat(3,varargin{:});
else
error('Invalid number of input arguments.');
end
FlipDims = (size(Image,3) == 1);
if FlipDims, Image = permute(Image,[1,3,2]); end
if ~isa(Image,'double'), Image = double(Image)/255; end
if size(Image,3) ~= 3, error('Invalid input size.'); end
SrcT = gettransform(SrcSpace);
DestT = gettransform(DestSpace);
if ~ischar(SrcT) & ~ischar(DestT)
% Both source and destination transforms are affine, so they
% can be composed into one affine operation
T = [DestT(:,1:3)*SrcT(:,1:3),DestT(:,1:3)*SrcT(:,4)+DestT(:,4)];
Temp = zeros(size(Image));
Temp(:,:,1) = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
Temp(:,:,2) = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
Temp(:,:,3) = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
Image = Temp;
elseif ~ischar(DestT)
Image = rgb(Image,SrcSpace);
Temp = zeros(size(Image));
Temp(:,:,1) = DestT(1)*Image(:,:,1) + DestT(4)*Image(:,:,2) + DestT(7)*Image(:,:,3) + DestT(10);
Temp(:,:,2) = DestT(2)*Image(:,:,1) + DestT(5)*Image(:,:,2) + DestT(8)*Image(:,:,3) + DestT(11);
Temp(:,:,3) = DestT(3)*Image(:,:,1) + DestT(6)*Image(:,:,2) + DestT(9)*Image(:,:,3) + DestT(12);
Image = Temp;
else
Image = feval(DestT,Image,SrcSpace);
end
%%% Output format %%%
if nargout > 1
varargout = {Image(:,:,1),Image(:,:,2),Image(:,:,3)};
else
if FlipDims, Image = permute(Image,[1,3,2]); end
varargout = {Image};
end
return;
function [SrcSpace,DestSpace] = parse(Str)
% Parse conversion argument
if isstr(Str)
Str = lower(strrep(strrep(Str,'-',''),' ',''));
k = find(Str == '>');
if length(k) == 1 % Interpret the form 'src->dest'
SrcSpace = Str(1:k-1);
DestSpace = Str(k+1:end);
else
k = find(Str == '<');
if length(k) == 1 % Interpret the form 'dest<-src'
DestSpace = Str(1:k-1);
SrcSpace = Str(k+1:end);
else
error(['Invalid conversion, ''',Str,'''.']);
end
end
SrcSpace = alias(SrcSpace);
DestSpace = alias(DestSpace);
else
SrcSpace = 1; % No source pre-transform
DestSpace = Conversion;
if any(size(Conversion) ~= 3), error('Transformation matrix must be 3x3.'); end
end
return;
function Space = alias(Space)
Space = strrep(Space,'cie','');
if isempty(Space)
Space = 'rgb';
end
switch Space
case {'ycbcr','ycc'}
Space = 'ycbcr';
case {'hsv','hsb'}
Space = 'hsv';
case {'hsl','hsi','hls'}
Space = 'hsl';
case {'rgb','yuv','yiq','ydbdr','ycbcr','jpegycbcr','xyz','lab','luv','lch'}
return;
end
return;
function T = gettransform(Space)
% Get a colorspace transform: either a matrix describing an affine transform,
% or a string referring to a conversion subroutine
switch Space
case 'ypbpr'
T = [0.299,0.587,0.114,0;-0.1687367,-0.331264,0.5,0;0.5,-0.418688,-0.081312,0];
case 'yuv'
% R'G'B' to NTSC/PAL YUV
% Wikipedia: http://en.wikipedia.org/wiki/YUV
T = [0.299,0.587,0.114,0;-0.147,-0.289,0.436,0;0.615,-0.515,-0.100,0];
case 'ydbdr'
% R'G'B' to SECAM YDbDr
% Wikipedia: http://en.wikipedia.org/wiki/YDbDr
T = [0.299,0.587,0.114,0;-0.450,-0.883,1.333,0;-1.333,1.116,0.217,0];
case 'yiq'
% R'G'B' in [0,1] to NTSC YIQ in [0,1];[-0.595716,0.595716];[-0.522591,0.522591];
% Wikipedia: http://en.wikipedia.org/wiki/YIQ
T = [0.299,0.587,0.114,0;0.595716,-0.274453,-0.321263,0;0.211456,-0.522591,0.311135,0];
case 'ycbcr'
% R'G'B' (range [0,1]) to ITU-R BRT.601 (CCIR 601) Y'CbCr
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
% Poynton, Equation 3, scaling of R'G'B to Y'PbPr conversion
T = [65.481,128.553,24.966,16;-37.797,-74.203,112.0,128;112.0,-93.786,-18.214,128];
case 'jpegycbcr'
% Wikipedia: http://en.wikipedia.org/wiki/YCbCr
T = [0.299,0.587,0.114,0;-0.168736,-0.331264,0.5,0.5;0.5,-0.418688,-0.081312,0.5]*255;
case {'rgb','xyz','hsv','hsl','lab','luv','lch'}
T = Space;
otherwise
error(['Unknown color space, ''',Space,'''.']);
end
return;
function Image = rgb(Image,SrcSpace)
% Convert to Rec. 709 R'G'B' from 'SrcSpace'
switch SrcSpace
case 'rgb'
return;
case 'hsv'
% Convert HSV to R'G'B'
Image = huetorgb((1 - Image(:,:,2)).*Image(:,:,3),Image(:,:,3),Image(:,:,1));
case 'hsl'
% Convert HSL to R'G'B'
L = Image(:,:,3);
Delta = Image(:,:,2).*min(L,1-L);
Image = huetorgb(L-Delta,L+Delta,Image(:,:,1));
case {'xyz','lab','luv','lch'}
% Convert to CIE XYZ
Image = xyz(Image,SrcSpace);
% Convert XYZ to RGB
T = [3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3); % R
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3); % G
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3); % B
% Desaturate and rescale to constrain resulting RGB values to [0,1]
AddWhite = -min(min(min(R,G),B),0);
Scale = max(max(max(R,G),B)+AddWhite,1);
R = (R + AddWhite)./Scale;
G = (G + AddWhite)./Scale;
B = (B + AddWhite)./Scale;
% Apply gamma correction to convert RGB to Rec. 709 R'G'B'
Image(:,:,1) = gammacorrection(R); % R'
Image(:,:,2) = gammacorrection(G); % G'
Image(:,:,3) = gammacorrection(B); % B'
otherwise % Conversion is through an affine transform
T = gettransform(SrcSpace);
temp = inv(T(:,1:3));
T = [temp,-temp*T(:,4)];
R = T(1)*Image(:,:,1) + T(4)*Image(:,:,2) + T(7)*Image(:,:,3) + T(10);
G = T(2)*Image(:,:,1) + T(5)*Image(:,:,2) + T(8)*Image(:,:,3) + T(11);
B = T(3)*Image(:,:,1) + T(6)*Image(:,:,2) + T(9)*Image(:,:,3) + T(12);
AddWhite = -min(min(min(R,G),B),0);
Scale = max(max(max(R,G),B)+AddWhite,1);
R = (R + AddWhite)./Scale;
G = (G + AddWhite)./Scale;
B = (B + AddWhite)./Scale;
Image(:,:,1) = R;
Image(:,:,2) = G;
Image(:,:,3) = B;
end
% Clip to [0,1]
Image = min(max(Image,0),1);
return;
function Image = xyz(Image,SrcSpace)
% Convert to CIE XYZ from 'SrcSpace'
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'xyz'
return;
case 'luv'
% Convert CIE L*uv to XYZ
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
L = Image(:,:,1);
Y = (L + 16)/116;
Y = invf(Y)*WhitePoint(2);
U = Image(:,:,2)./(13*L + 1e-6*(L==0)) + WhitePointU;
V = Image(:,:,3)./(13*L + 1e-6*(L==0)) + WhitePointV;
Image(:,:,1) = -(9*Y.*U)./((U-4).*V - U.*V); % X
Image(:,:,2) = Y; % Y
Image(:,:,3) = (9*Y - (15*V.*Y) - (V.*Image(:,:,1)))./(3*V); % Z
case {'lab','lch'}
Image = lab(Image,SrcSpace);
% Convert CIE L*ab to XYZ
fY = (Image(:,:,1) + 16)/116;
fX = fY + Image(:,:,2)/500;
fZ = fY - Image(:,:,3)/200;
Image(:,:,1) = WhitePoint(1)*invf(fX); % X
Image(:,:,2) = WhitePoint(2)*invf(fY); % Y
Image(:,:,3) = WhitePoint(3)*invf(fZ); % Z
otherwise % Convert from some gamma-corrected space
% Convert to Rec. 701 R'G'B'
Image = rgb(Image,SrcSpace);
% Undo gamma correction
R = invgammacorrection(Image(:,:,1));
G = invgammacorrection(Image(:,:,2));
B = invgammacorrection(Image(:,:,3));
% Convert RGB to XYZ
T = inv([3.240479,-1.53715,-0.498535;-0.969256,1.875992,0.041556;0.055648,-0.204043,1.057311]);
Image(:,:,1) = T(1)*R + T(4)*G + T(7)*B; % X
Image(:,:,2) = T(2)*R + T(5)*G + T(8)*B; % Y
Image(:,:,3) = T(3)*R + T(6)*G + T(9)*B; % Z
end
return;
function Image = hsv(Image,SrcSpace)
% Convert to HSV
Image = rgb(Image,SrcSpace);
V = max(Image,[],3);
S = (V - min(Image,[],3))./(V + (V == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = V;
return;
function Image = hsl(Image,SrcSpace)
% Convert to HSL
switch SrcSpace
case 'hsv'
% Convert HSV to HSL
MaxVal = Image(:,:,3);
MinVal = (1 - Image(:,:,2)).*MaxVal;
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
Image(:,:,2) = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,3) = L;
otherwise
Image = rgb(Image,SrcSpace); % Convert to Rec. 701 R'G'B'
% Convert R'G'B' to HSL
MinVal = min(Image,[],3);
MaxVal = max(Image,[],3);
L = 0.5*(MaxVal + MinVal);
temp = min(L,1-L);
S = 0.5*(MaxVal - MinVal)./(temp + (temp == 0));
Image(:,:,1) = rgbtohue(Image);
Image(:,:,2) = S;
Image(:,:,3) = L;
end
return;
function Image = lab(Image,SrcSpace)
% Convert to CIE L*a*b* (CIELAB)
WhitePoint = [0.950456,1,1.088754];
switch SrcSpace
case 'lab'
return;
case 'lch'
% Convert CIE L*CH to CIE L*ab
C = Image(:,:,2);
Image(:,:,2) = cos(Image(:,:,3)*pi/180).*C; % a*
Image(:,:,3) = sin(Image(:,:,3)*pi/180).*C; % b*
otherwise
Image = xyz(Image,SrcSpace); % Convert to XYZ
% Convert XYZ to CIE L*a*b*
X = Image(:,:,1)/WhitePoint(1);
Y = Image(:,:,2)/WhitePoint(2);
Z = Image(:,:,3)/WhitePoint(3);
fX = f(X);
fY = f(Y);
fZ = f(Z);
Image(:,:,1) = 116*fY - 16; % L*
Image(:,:,2) = 500*(fX - fY); % a*
Image(:,:,3) = 200*(fY - fZ); % b*
end
return;
function Image = luv(Image,SrcSpace)
% Convert to CIE L*u*v* (CIELUV)
WhitePoint = [0.950456,1,1.088754];
WhitePointU = (4*WhitePoint(1))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
WhitePointV = (9*WhitePoint(2))./(WhitePoint(1) + 15*WhitePoint(2) + 3*WhitePoint(3));
Image = xyz(Image,SrcSpace); % Convert to XYZ
U = (4*Image(:,:,1))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));
V = (9*Image(:,:,2))./(Image(:,:,1) + 15*Image(:,:,2) + 3*Image(:,:,3));
Y = Image(:,:,2)/WhitePoint(2);
L = 116*f(Y) - 16;
Image(:,:,1) = L; % L*
Image(:,:,2) = 13*L.*(U - WhitePointU); % u*
Image(:,:,3) = 13*L.*(V - WhitePointV); % v*
return;
function Image = lch(Image,SrcSpace)
% Convert to CIE L*ch
Image = lab(Image,SrcSpace); % Convert to CIE L*ab
H = atan2(Image(:,:,3),Image(:,:,2));
H = H*180/pi + 360*(H < 0);
Image(:,:,2) = sqrt(Image(:,:,2).^2 + Image(:,:,3).^2); % C
Image(:,:,3) = H; % H
return;
function Image = huetorgb(m0,m2,H)
% Convert HSV or HSL hue to RGB
N = size(H);
H = min(max(H(:),0),360)/60;
m0 = m0(:);
m2 = m2(:);
F = H - round(H/2)*2;
M = [m0, m0 + (m2-m0).*abs(F), m2];
Num = length(m0);
j = [2 1 0;1 2 0;0 2 1;0 1 2;1 0 2;2 0 1;2 1 0]*Num;
k = floor(H) + 1;
Image = reshape([M(j(k,1)+(1:Num).'),M(j(k,2)+(1:Num).'),M(j(k,3)+(1:Num).')],[N,3]);
return;
function H = rgbtohue(Image)
% Convert RGB to HSV or HSL hue
[M,i] = sort(Image,3);
i = i(:,:,3);
Delta = M(:,:,3) - M(:,:,1);
Delta = Delta + (Delta == 0);
R = Image(:,:,1);
G = Image(:,:,2);
B = Image(:,:,3);
H = zeros(size(R));
k = (i == 1);
H(k) = (G(k) - B(k))./Delta(k);
k = (i == 2);
H(k) = 2 + (B(k) - R(k))./Delta(k);
k = (i == 3);
H(k) = 4 + (R(k) - G(k))./Delta(k);
H = 60*H + 360*(H < 0);
H(Delta == 0) = nan;
return;
function Rp = gammacorrection(R)
Rp = real(1.099*R.^0.45 - 0.099);
i = (R < 0.018);
Rp(i) = 4.5138*R(i);
return;
function R = invgammacorrection(Rp)
R = real(((Rp + 0.099)/1.099).^(1/0.45));
i = (R < 0.018);
R(i) = Rp(i)/4.5138;
return;
function fY = f(Y)
fY = real(Y.^(1/3));
i = (Y < 0.008856);
fY(i) = Y(i)*(841/108) + (4/29);
return;
function Y = invf(fY)
Y = fY.^3;
i = (Y < 0.008856);
Y(i) = (fY(i) - 4/29)*(108/841);
return;
|
github
|
zhoujinglin/matlab-master
|
dtwaveifm.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/dtcwt_toolbox/dtwaveifm.m
| 3,486 |
utf_8
|
07a0631bc29c7e92d8255a7f52ecec0b
|
function Z = dtwaveifm(Yl,Yh,biort,qshift,gain_mask);
% Function to perform an n-level dual-tree complex wavelet (DTCWT)
% 1-D reconstruction.
%
% Z = dtwaveifm(Yl,Yh,biort,qshift,gain_mask);
%
% Yl -> The real lowpass subband from the final level
% Yh -> A cell array containing the complex highpass subband for each level.
%
% biort -> 'antonini' => Antonini 9,7 tap filters.
% 'legall' => LeGall 5,3 tap filters.
% 'near_sym_a' => Near-Symmetric 5,7 tap filters.
% 'near_sym_b' => Near-Symmetric 13,19 tap filters.
%
% qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters,
% (only 6,6 non-zero taps).
% 'qshift_a' => Q-shift 10,10 tap filters,
% (with 10,10 non-zero taps, unlike qshift_06).
% 'qshift_b' => Q-Shift 14,14 tap filters.
% 'qshift_c' => Q-Shift 16,16 tap filters.
% 'qshift_d' => Q-Shift 18,18 tap filters.
%
% gain_mask -> Gain to be applied to each subband.
% gain_mask(l) is gain for wavelet subband at level l.
% If gain_mask(l) == 0, no computation is performed for band (l).
% Default gain_mask = ones(1,length(Yh)).
%
% Z -> Reconstructed real signal vector (or matrix).
%
%
% For example: Z = dtwaveifm(Yl,Yh,'near_sym_b','qshift_b');
% performs a reconstruction from Yl,Yh using the 13,19-tap filters
% for level 1 and the Q-shift 14-tap filters for levels >= 2.
%
% Nick Kingsbury and Cian Shaffrey
% Cambridge University, May 2002
a = length(Yh); % No of levels.
if nargin < 5, gain_mask = ones(1,a); end % Default gain_mask.
if isstr(biort) & isstr(qshift) %Check if the inputs are strings
biort_exist = exist([biort '.mat']);
qshift_exist = exist([qshift '.mat']);
if biort_exist == 2 & qshift_exist == 2; %Check to see if the inputs exist as .mat files
load (biort);
load (qshift);
else
error('Please enter the correct names of the Biorthogonal or Q-Shift Filters, see help DTWAVEIFM for details.');
end
else
error('Please enter the names of the Biorthogonal or Q-Shift Filters as shown in help DTWAVEIFM.');
end
level = a; % No of levels = no of rows in L.
Lo = Yl;
while level >= 2; % Reconstruct levels 2 and above in reverse order.
Hi = c2q1d(Yh{level}*gain_mask(level));
Lo = colifilt(Lo, g0b, g0a) + colifilt(Hi, g1b, g1a);
if size(Lo,1) ~= 2*size(Yh{level-1},1) % If Lo is not the same length as the next Yh => t1 was extended.
Lo = Lo(2:size(Lo,1)-1,:); % Therefore we have to clip Lo so it is the same height as the next Yh.
end
if any(size(Lo) ~= size(Yh{level-1}).*[2 1]),
error('Yh sizes are not valid for DTWAVEIFM');
end
level = level - 1;
end
if level == 1; % Reconstruct level 1.
Hi = c2q1d(Yh{level}*gain_mask(level));
Z = colfilter(Lo,g0o) + colfilter(Hi,g1o);
end
return
%==========================================================================================
% ********** INTERNAL FUNCTION **********
%==========================================================================================
function z = c2q1d(x)
% An internal function to convert a 1D Complex vector back to a real array,
% which is twice the height of x.
[a b] = size(x);
z = zeros(a*2,b);
skip = 1:2:(a*2);
z(skip,:) = real(x);
z(skip+1,:) = imag(x);
return
|
github
|
zhoujinglin/matlab-master
|
dDTCWT.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/dtcwt_toolbox/dDTCWT.m
| 1,565 |
utf_8
|
8c9992a796e21805fbcd88f6acc567bd
|
function [Y1 h11]=derotated_dtcwt(I1,n,biot,Qshift)
% X -> 2D real matrix/Image
%
% nlevels -> No. of levels of wavelet decomposition
%
% biort -> 'antonini' => Antonini 9,7 tap filters.
% 'legall' => LeGall 5,3 tap filters.
% 'near_sym_a' => Near-Symmetric 5,7 tap filters.
% 'near_sym_b' => Near-Symmetric 13,19 tap filters.
%
% qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters,
% (only 6,6 non-zero taps).
% 'qshift_a' => Q-shift 10,10 tap filters,
% (with 10,10 non-zero taps, unlike qshift_06).
% 'qshift_b' => Q-Shift 14,14 tap filters.
% 'qshift_c' => Q-Shift 16,16 tap filters.
% 'qshift_d' => Q-Shift 18,18 tap filters.
%
%
% Y1 -> The real lowpass image from the final level
% h11 -> A cell array containing the 6 complex highpass subimages
% for each level.
%clear all;
%clc;
[Y1,h1] = dtwavexfm2(I1,n,biot,Qshift);
%[Y2,h2] = dtwavexfm2(I2,n,biot,Qshift);
h11{n}=h1{n};
for k=n:-1:2
for m=1:6
xp=imresize(h1{k}(:,:,m),2);%
argxp=angle(xp);
argx=angle(h1{k-1}(:,:,m));
argx=argx-2.*argxp;
absx=abs(h1{k-1}(:,:,m));
xa=absx.*cos(argx);
xb=absx.*sin(argx);
h11{k-1}(:,:,m)=complex(xa,xb);
end
end
%figure;
%cimage5(h11{1}(:,:,4));
%figure;
%cimage5(h1{1}(:,:,4));
%figure;
%cimage5(h11{2}(:,:,4));
%figure;
%cimage5(h1{2}(:,:,4));
|
github
|
zhoujinglin/matlab-master
|
dtwavexfm2.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/dtcwt_toolbox/dtwavexfm2.m
| 6,425 |
utf_8
|
dc2ac3ba8198284e20b2982574de6174
|
function [Yl,Yh,Yscale] = dtwavexfm2(X,nlevels,biort,qshift);
% Function to perform a n-level DTCWT-2D decompostion on a 2D matrix X
%
% [Yl,Yh,Yscale] = dtwavexfm2(X,nlevels,biort,qshift);
%
% X -> 2D real matrix/Image
%
% nlevels -> No. of levels of wavelet decomposition
%
% biort -> 'antonini' => Antonini 9,7 tap filters.
% 'legall' => LeGall 5,3 tap filters.
% 'near_sym_a' => Near-Symmetric 5,7 tap filters.
% 'near_sym_b' => Near-Symmetric 13,19 tap filters.
%
% qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters,
% (only 6,6 non-zero taps).
% 'qshift_a' => Q-shift 10,10 tap filters,
% (with 10,10 non-zero taps, unlike qshift_06).
% 'qshift_b' => Q-Shift 14,14 tap filters.
% 'qshift_c' => Q-Shift 16,16 tap filters.
% 'qshift_d' => Q-Shift 18,18 tap filters.
%
%
% Yl -> The real lowpass image from the final level
% Yh -> A cell array containing the 6 complex highpass subimages for each level.
% Yscale -> This is an OPTIONAL output argument, that is a cell array containing
% real lowpass coefficients for every scale.
%
%
% Example: [Yl,Yh] = dtwavexfm2(X,3,'near_sym_b','qshift_b');
% performs a 3-level transform on the real image X using the 13,19-tap filters
% for level 1 and the Q-shift 14-tap filters for levels >= 2.
%
% Nick Kingsbury and Cian Shaffrey
% Cambridge University, Sept 2001
if isstr(biort) & isstr(qshift) %Check if the inputs are strings
biort_exist = exist([biort '.mat']);
qshift_exist = exist([qshift '.mat']);
if biort_exist == 2 & qshift_exist == 2; %Check to see if the inputs exist as .mat files
load (biort);
load (qshift);
else
error('Please enter the correct names of the Biorthogonal or Q-Shift Filters, see help DTWAVEXFM2 for details.');
end
else
error('Please enter the names of the Biorthogonal or Q-Shift Filters as shown in help DTWAVEXFM2.');
end
orginal_size = size(X);
if ndims(X) >= 3;
error(sprintf('The entered image is %dx%dx%d, please enter each image slice separately.',orginal_size(1),orginal_size(2),orginal_size(3)));
end
% The next few lines of code check to see if the image is odd in size, if so an extra ...
% row/column will be added to the bottom/right of the image
initial_row_extend = 0; %initialise
initial_col_extend = 0;
if any(rem(orginal_size(1),2)), %if sx(1) is not divisable by 2 then we need to extend X by adding a row at the bottom
X = [X; X(end,:)]; %Any further extension will be done in due course.
initial_row_extend = 1;
end
if any(rem(orginal_size(2),2)), %if sx(2) is not divisable by 2 then we need to extend X by adding a col to the left
X = [X X(:,end)]; %Any further extension will be done in due course.
initial_col_extend = 1;
end
extended_size = size(X);
if nlevels == 0, return; end
%initialise
Yh=cell(nlevels,1);
if nargout == 3
Yscale=cell(nlevels,1); %this is only required if the user specifies a third output component.
end
S = [];
sx = size(X);
if nlevels >= 1,
% Do odd top-level filters on cols.
Lo = colfilter(X,h0o).';
Hi = colfilter(X,h1o).';
% Do odd top-level filters on rows.
LoLo = colfilter(Lo,h0o).'; % LoLo
Yh{1} = zeros([size(LoLo)/2 6]);
Yh{1}(:,:,[1 6]) = q2c(colfilter(Hi,h0o).'); % Horizontal pair
Yh{1}(:,:,[3 4]) = q2c(colfilter(Lo,h1o).'); % Vertical pair
Yh{1}(:,:,[2 5]) = q2c(colfilter(Hi,h1o).'); % Diagonal pair
S = [ size(LoLo) ;S];
if nargout == 3
Yscale{1} = LoLo;
end
end
if nlevels >= 2;
for level = 2:nlevels;
[row_size col_size] = size(LoLo);
if any(rem(row_size,4)), % Extend by 2 rows if no. of rows of LoLo are divisable by 4;
LoLo = [LoLo(1,:); LoLo; LoLo(end,:)];
end
if any(rem(col_size,4)), % Extend by 2 cols if no. of cols of LoLo are divisable by 4;
LoLo = [LoLo(:,1) LoLo LoLo(:,end)];
end
% Do even Qshift filters on rows.
Lo = coldfilt(LoLo,h0b,h0a).';
Hi = coldfilt(LoLo,h1b,h1a).';
% Do even Qshift filters on columns.
LoLo = coldfilt(Lo,h0b,h0a).'; %LoLo
Yh{level} = zeros([size(LoLo)/2 6]);
Yh{level}(:,:,[1 6]) = q2c(coldfilt(Hi,h0b,h0a).'); % Horizontal
Yh{level}(:,:,[3 4]) = q2c(coldfilt(Lo,h1b,h1a).'); % Vertical
Yh{level}(:,:,[2 5]) = q2c(coldfilt(Hi,h1b,h1a).'); % Diagonal
S = [ size(LoLo) ;S];
if nargout == 3
Yscale{level} = LoLo;
end
end
end
Yl = LoLo;
if initial_row_extend == 1 & initial_col_extend == 1;
warning(sprintf(' \r\r The image entered is now a %dx%d NOT a %dx%d \r The bottom row and rightmost column have been duplicated, prior to decomposition. \r\r ',...
extended_size(1),extended_size(2),orginal_size(1),orginal_size(2)));
end
if initial_row_extend == 1 ;
warning(sprintf(' \r\r The image entered is now a %dx%d NOT a %dx%d \r Row number %d has been duplicated, and added to the bottom of the image, prior to decomposition. \r\r',...
extended_size(1),extended_size(2),orginal_size(1),orginal_size(2),orginal_size(1)));
end
if initial_col_extend == 1;
warning(sprintf(' \r\r The image entered is now a %dx%d NOT a %dx%d \r Col number %d has been duplicated, and added to the right of the image, prior to decomposition. \r\r',...
extended_size(1),extended_size(2),orginal_size(1),orginal_size(2),orginal_size(2)));
end
return
%==========================================================================================
% ********** INTERNAL FUNCTION **********
%==========================================================================================
function z = q2c(y)
% function z = q2c(y)
% Convert from quads in y to complex numbers in z.
sy = size(y);
t1 = 1:2:sy(1); t2 = 1:2:sy(2);
j2 = sqrt([0.5 -0.5]);
% Arrange pixels from the corners of the quads into
% 2 subimages of alternate real and imag pixels.
% a----b
% | |
% | |
% c----d
% Combine (a,b) and (d,c) to form two complex subimages.
p = y(t1,t2)*j2(1) + y(t1,t2+1)*j2(2); % p = (a + jb) / sqrt(2)
q = y(t1+1,t2+1)*j2(1) - y(t1+1,t2)*j2(2); % q = (d - jc) / sqrt(2)
% Form the 2 subbands in z.
z = cat(3,p-q,p+q);
return
|
github
|
zhoujinglin/matlab-master
|
dtwaveifm2.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/dtcwt_toolbox/dtwaveifm2.m
| 4,884 |
utf_8
|
b7b8d7bbbe5209e8550b34297949f93c
|
function Z = dtwaveifm2(Yl,Yh,biort,qshift,gain_mask);
% Function to perform an n-level dual-tree complex wavelet (DTCWT)
% 2-D reconstruction.
%
% Z = dtwaveifm2(Yl,Yh,biort,qshift,gain_mask);
%
% Yl -> The real lowpass image from the final level
% Yh -> A cell array containing the 6 complex highpass subimages for each level.
%
% biort -> 'antonini' => Antonini 9,7 tap filters.
% 'legall' => LeGall 5,3 tap filters.
% 'near_sym_a' => Near-Symmetric 5,7 tap filters.
% 'near_sym_b' => Near-Symmetric 13,19 tap filters.
%
% qshift -> 'qshift_06' => Quarter Sample Shift Orthogonal (Q-Shift) 10,10 tap filters,
% (only 6,6 non-zero taps).
% 'qshift_a' => Q-shift 10,10 tap filters,
% (with 10,10 non-zero taps, unlike qshift_06).
% 'qshift_b' => Q-Shift 14,14 tap filters.
% 'qshift_c' => Q-Shift 16,16 tap filters.
% 'qshift_d' => Q-Shift 18,18 tap filters.
%
% gain_mask -> Gain to be applied to each subband.
% gain_mask(d,l) is gain for subband with direction d at level l.
% If gain_mask(d,l) == 0, no computation is performed for band (d,l).
% Default gain_mask = ones(6,length(Yh)).
%
% Z -> Reconstructed real image matrix
%
%
% For example: Z = dtwaveifm2(Yl,Yh,'near_sym_b','qshift_b');
% performs a 3-level reconstruction from Yl,Yh using the 13,19-tap filters
% for level 1 and the Q-shift 14-tap filters for levels >= 2.
%
% Nick Kingsbury and Cian Shaffrey
% Cambridge University, May 2002
a = length(Yh); % No of levels.
if nargin < 5, gain_mask = ones(6,a); end % Default gain_mask.
if isstr(biort) & isstr(qshift) %Check if the inputs are strings
biort_exist = exist([biort '.mat']);
qshift_exist = exist([qshift '.mat']);
if biort_exist == 2 & qshift_exist == 2; %Check to see if the inputs exist as .mat files
load (biort);
load (qshift);
else
error('Please enter the correct names of the Biorthogonal or Q-Shift Filters, see help DTWAVEIFM2 for details.');
end
else
error('Please enter the names of the Biorthogonal or Q-Shift Filters as shown in help DTWAVEIFM2.');
end
current_level = a;
Z = Yl;
while current_level >= 2; ; %this ensures that for level -1 we never do the following
lh = c2q(Yh{current_level}(:,:,[1 6]),gain_mask([1 6],current_level));
hl = c2q(Yh{current_level}(:,:,[3 4]),gain_mask([3 4],current_level));
hh = c2q(Yh{current_level}(:,:,[2 5]),gain_mask([2 5],current_level));
% Do even Qshift filters on columns.
y1 = colifilt(Z,g0b,g0a) + colifilt(lh,g1b,g1a);
y2 = colifilt(hl,g0b,g0a) + colifilt(hh,g1b,g1a);
% Do even Qshift filters on rows.
Z = (colifilt(y1.',g0b,g0a) + colifilt(y2.',g1b,g1a)).';
% Check size of Z and crop as required
[row_size col_size] = size(Z);
S = 2*size(Yh{current_level-1});
if row_size ~= S(1) %check to see if this result needs to be cropped for the rows
Z = Z(2:row_size-1,:);
end
if col_size ~= S(2) %check to see if this result needs to be cropped for the cols
Z = Z(:,2:col_size-1);
end
if any(size(Z) ~= S(1:2)),
error('Sizes of subbands are not valid for DTWAVEIFM2');
end
current_level = current_level - 1;
end
if current_level == 1;
lh = c2q(Yh{current_level}(:,:,[1 6]),gain_mask([1 6],current_level));
hl = c2q(Yh{current_level}(:,:,[3 4]),gain_mask([3 4],current_level));
hh = c2q(Yh{current_level}(:,:,[2 5]),gain_mask([2 5],current_level));
% Do odd top-level filters on columns.
y1 = colfilter(Z,g0o) + colfilter(lh,g1o);
y2 = colfilter(hl,g0o) + colfilter(hh,g1o);
% Do odd top-level filters on rows.
Z = (colfilter(y1.',g0o) + colfilter(y2.',g1o)).';
end
return
%==========================================================================================
% ********** INTERNAL FUNCTION **********
%==========================================================================================
function x = c2q(w,gain)
% function z = c2q(w,gain)
% Scale by gain and convert from complex w(:,:,1:2) to real quad-numbers in z.
%
% Arrange pixels from the real and imag parts of the 2 subbands
% into 4 separate subimages .
% A----B Re Im of w(:,:,1)
% | |
% | |
% C----D Re Im of w(:,:,2)
sw = size(w);
x = zeros(2*sw(1:2));
if any(w(:)) & any(gain)
sc = sqrt(0.5) * gain;
P = w(:,:,1)*sc(1) + w(:,:,2)*sc(2);
Q = w(:,:,1)*sc(1) - w(:,:,2)*sc(2);
t1 = 1:2:size(x,1);
t2 = 1:2:size(x,2);
% Recover each of the 4 corners of the quads.
x(t1,t2) = real(P); % a = (A+C)*sc;
x(t1,t2+1) = imag(P); % b = (B+D)*sc;
x(t1+1,t2) = imag(Q); % c = (B-D)*sc;
x(t1+1,t2+1) = -real(Q); % d = (C-A)*sc;
end
return
|
github
|
zhoujinglin/matlab-master
|
ompdemo.m
|
.m
|
matlab-master/video_fusion/MST_SR_fusion_toolbox/sparsefusion/ksvdbox/ompbox/ompdemo.m
| 2,294 |
utf_8
|
330e3e897edffa6b88c516d30fc4e96b
|
function ompdemo
%OMPDEMO Demonstration of the OMP toolbox.
% OMPDEMO generates a random sparse mixture of cosines and spikes, adds
% noise, and applies OMP to recover the original signal.
%
% To run the demo, type OMPDEMO from the Matlab prompt.
%
% See also OMPSPEEDTEST.
% Ron Rubinstein
% Computer Science Department
% Technion, Haifa 32000 Israel
% ronrubin@cs
%
% April 2009
disp(' ');
disp(' ********** OMP Demo **********');
disp(' ');
disp(' This demo generates a random mixture of cosines and spikes, adds noise,');
disp(' and uses OMP to recover the mixture and the original signal. The graphs');
disp(' show the original, noisy and recovered signal with the corresponding SNR');
disp(' values. The true and recovered coefficients are shown in the bar graphs.');
disp(' ');
% generate DCT-spike dictionary %
n = 256;
D = zeros(n);
D(:,1) = 1/sqrt(n);
for i = 2:n
v = cos((0:n-1)*pi*(i-1)/n)';
v = v-mean(v);
D(:,i) = v/norm(v);
end
D = [D eye(n)];
% generate random sparse mixture of cosines and spikes %
g = sparse(2*n,1);
% sinusoid coefs are random within +/-[0.5,1.5]
lowfreq = 20;
p = randperm(lowfreq);
g(p(1:2)) = (rand(2,1)+0.5).*randsig(2,1); % two random low frequencies
p = randperm(n-lowfreq);
g(lowfreq+p(1:2)) = (rand(2,1)+0.5).*randsig(2,1); % two random high frequencies
% spike coefs are random within +/-[0.25,0.75]
p = randperm(n);
g(p(1:3)+n) = (rand(3,1)/2+0.25).*randsig(3,1); % three random spikes
x = D*g;
% add gaussian noise %
r = randn(size(x));
r = r/norm(r)*norm(x)/4;
y = x + r;
% perform omp %
gamma = omp(D'*y, D'*D, nnz(g));
err = x-D*gamma;
% show results %
v=[1 n -max(abs([x;y]))*1.1 max(abs([x;y]))*1.1];
figure; plot(x); axis(v); title('Original signal');
figure; plot(y); axis(v); title(sprintf('Noisy signal, SNR=%.1fdB', 10*log10((x'*x)/(r'*r))));
figure; plot(D*gamma); axis(v); title(sprintf('Reconstructed signal, SNR=%.1fdB', 10*log10((x'*x)/(err'*err))));
v = [1 2*n -max(abs([g;gamma]))*1.1 max(abs([g;gamma]))*1.1];
figure; bar(full(g)); axis(v); title('True signal decomposition');
figure; bar(full(gamma)); axis(v); title('Decomposition recovered by OMP');
return;
% random matrix with +/-1
function y = randsig(varargin)
y = round(rand(varargin{:}))*2 - 1;
return;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.