plateform
stringclasses
1 value
repo_name
stringlengths
13
113
name
stringlengths
3
74
ext
stringclasses
1 value
path
stringlengths
12
229
size
int64
23
843k
source_encoding
stringclasses
9 values
md5
stringlengths
32
32
text
stringlengths
23
843k
github
jacksky64/imageProcessing-master
viewer3d_contrast.m
.m
imageProcessing-master/Matlab Viewer3D/SubFunctions/viewer3d_contrast.m
8,521
utf_8
23f75c7fe9be514aa92a196006737ece
function varargout = viewer3d_contrast(varargin) % VIEWER3D_CONTRAST M-file for viewer3d_contrast.fig % VIEWER3D_CONTRAST, by itself, creates a new VIEWER3D_CONTRAST or raises the existing % singleton*. % % H = VIEWER3D_CONTRAST returns the handle to a new VIEWER3D_CONTRAST or the handle to % the existing singleton*. % % VIEWER3D_CONTRAST('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in VIEWER3D_CONTRAST.M with the given input arguments. % % VIEWER3D_CONTRAST('Property','Value',...) creates a new VIEWER3D_CONTRAST or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before viewer3d_contrast_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to viewer3d_contrast_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help viewer3d_contrast % Last Modified by GUIDE v2.5 25-Jan-2011 11:41:10 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @viewer3d_contrast_OpeningFcn, ... 'gui_OutputFcn', @viewer3d_contrast_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end % End initialization code - DO NOT EDIT % --- Executes just before viewer3d_contrast is made visible. function viewer3d_contrast_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to viewer3d_contrast (see VARARGIN) % Choose default command line output for viewer3d_contrast handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes viewer3d_contrast wait for user response (see UIRESUME) % uiwait(handles.figurecontrast); % --- Outputs from this function are returned to the command line. function varargout = viewer3d_contrast_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on slider movement. function slider_window_level_Callback(hObject, eventdata, handles) % hObject handle to slider_window_level (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function slider_window_level_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_window_level (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on slider movement. function slider_window_width_Callback(hObject, eventdata, handles) % hObject handle to slider_window_width (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'Value') returns position of slider % get(hObject,'Min') and get(hObject,'Max') to determine range of slider % --- Executes during object creation, after setting all properties. function slider_window_width_CreateFcn(hObject, eventdata, handles) % hObject handle to slider_window_width (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on mouse motion over figure - except title and menu. function figurecontrast_WindowButtonMotionFcn(hObject, eventdata, handles) % hObject handle to figurecontrast (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on button press in pushbutton_reset. function pushbutton_reset_Callback(hObject, eventdata, handles) % hObject handle to pushbutton_reset (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) function edit_window_level_Callback(hObject, eventdata, handles) % hObject handle to edit_window_level (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_window_level as text % str2double(get(hObject,'String')) returns contents of edit_window_level as a double % --- Executes during object creation, after setting all properties. function edit_window_level_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_window_level (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function edit_window_width_Callback(hObject, eventdata, handles) % hObject handle to edit_window_width (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Hints: get(hObject,'String') returns contents of edit_window_width as text % str2double(get(hObject,'String')) returns contents of edit_window_width as a double % --- Executes during object creation, after setting all properties. function edit_window_width_CreateFcn(hObject, eventdata, handles) % hObject handle to edit_window_width (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles empty - handles not created until after all CreateFcns called % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end % --- If Enable == 'on', executes on mouse press in 5 pixel border. % --- Otherwise, executes on mouse press in 5 pixel border or over pushbutton_autocontrast. function pushbutton_autocontrast_ButtonDownFcn(hObject, eventdata, handles) % hObject handle to pushbutton_autocontrast (see GCBO) % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % --- Executes on key press with focus on pushbutton_autocontrast and none of its controls. function pushbutton_autocontrast_KeyPressFcn(hObject, eventdata, handles) % hObject handle to pushbutton_autocontrast (see GCBO) % eventdata structure with the following fields (see UICONTROL) % Key: name of the key that was pressed, in lower case % Character: character interpretation of the key(s) that was pressed % Modifier: name(s) of the modifier key(s) (i.e., control, shift) pressed % handles structure with handles and user data (see GUIDATA)
github
jacksky64/imageProcessing-master
structfind.m
.m
imageProcessing-master/Matlab Viewer3D/SubFunctions/structfind.m
3,025
utf_8
2f5a54606251beb957c2f30704c5435d
function index=structfind(a,field,value) % StructFind, Find the index of a certain string or value in a struct % % index=structfind(a,field,value) % % inputs, % a : A Matlab struct, for example a(1).name='red', a(2).name='blue'; % field : The name of the field which is searched, for example 'name' % value : The search value, for example 'blue' % % outputs, % index : The Struct index which match the search % % % Example, % % a(1).name='blue'; % a(1).index=0; % a(1).val='g'; % % a(2).name='red'; % a(2).index=1; % a(2).val=[1 0]; % % a(3).name='green'; % a(3).index=2; % a(3).val='g'; % % a(4).name='black'; % a(4).index=3; % a(4).val=[0 0 0]; % % a(5).name='yellow'; % a(5).index=NaN; % a(5).val=[0 1 1]; % % a(6).name='orange'; % a(6).index=[]; % a(6).val=[1 1 0]; % % a(7).name='brown'; % a(7).index=6; % a(7).val={'12'}; % % a(8).name='white'; % a(8).index=7; % a(8).val.x=1; % % a(8).name='purple'; % a(8).index=8; % a(8).val.child.value=2; % % index=structfind(a,'name','red'); % disp(['index : ' num2str(index)]) % % index=structfind(a,'index',1); % disp(['index : ' num2str(index)]) % % index=structfind(a,'val',[0 0 0]); % disp(['index : ' num2str(index)]) % % index=structfind(a,'val','g'); % disp(['index : ' num2str(index)]) % % index=structfind(a,'index',NaN); % disp(['index : ' num2str(index)]) % % index=structfind(a,'index',[]); % disp(['index : ' num2str(index)]) % % index=structfind(a,'val',{'12'}); % disp(['index : ' num2str(index)]) % % index=structfind(a,'val.child.value',2); % disp(['index : ' num2str(index)]) % % Function is written by D.Kroon University of Twente (December 2010) % We don't compare structs if(isstruct(value)), error('structfind:inputs','search value can not be a struct'); end % Stop if field doesn't exist if(~isfield(a,field)) index=find(arrayfun(@(x)(cmp(x,field,value)),a,'uniformoutput',true)); else index=find(arrayfun(@(x)(cmp(x,field,value)),a,'uniformoutput',true)); end function check=cmp(x,field,value) check=false; if(isfield(x,field)) % Simple field like x.tag x=x.(field); else % Complex field like x.tag.child.value in=find(field=='.'); s=[1 in+1]; e=[in-1 length(field)]; for i=1:length(s) fieldt=field(s(i):e(i)); if(isfield(x,fieldt)), x=x.(fieldt); else return; end end end % We don't compare structs if(isstruct(x)), return; end % Values can only be equal, if they equal in length if(length(x)==length(value)), % This part compares the NaN values if((~iscell(x))&&(~iscell(value))&&any(isnan(value))), checkv=isnan(value); checkx=isnan(x); if(~all(checkx==checkv)), return; end x(checkx)=0; value(checkv)=0; end % This part compares for both string as numerical values if(iscell(x)||iscell(value)) check=all(strcmp(x,value)); else check=all(x==value); end end
github
jacksky64/imageProcessing-master
SnakeInternalForceMatrix3D.m
.m
imageProcessing-master/Matlab Viewer3D/SubFunctions/BasicSnake_version2d/SnakeInternalForceMatrix3D.m
1,430
utf_8
4d138c391cf1d34306cc2c49246b80c1
function B=SnakeInternalForceMatrix3D(FV,alpha,beta,gamma) % % B=SnakeInternalForceMatrix3D(F,alpha,beta,gamma) % % inputs, % FV : Struct (Patch) with the triangulated surface % alpha : membrame energy (first order) % beta : thin plate energy (second order) % gamma : Step Size (Time) % % outputs, % B : The Snake Smoothness regulation matrix % % Function is written by D.Kroon University of Twente (July 2010) Ne=VertexNeighbours(FV.faces,FV.vertices); nV=size(FV.vertices,1); % Matrix for umbrella mesh derivative function in (sparce) matrix form NeMatrix = spalloc(nV,nV,nV*10); for i=1:nV Nc=Ne{i}; % Add the neighbours NeMatrix(i,Nc)=1/length(Nc); % Add the vertex it self NeMatrix(i,i)=-1; end % Total internal force matrix B=speye(nV,nV)+gamma*(alpha*NeMatrix-beta*NeMatrix*NeMatrix); function Ne=VertexNeighbours(F,V) % Function which return the neighbouring vertices of every vertex % in a cell array list. (Basic version, not sorted by rotation) % Neighbourh cell array Ne=cell(1,size(V,1)); % Loop through all faces for i=1:length(F) % Add the neighbors of each vertice of a face % to his neighbors list. Ne{F(i,1)}=[Ne{F(i,1)} [F(i,2) F(i,3)]]; Ne{F(i,2)}=[Ne{F(i,2)} [F(i,3) F(i,1)]]; Ne{F(i,3)}=[Ne{F(i,3)} [F(i,1) F(i,2)]]; end % Remove duplicate vertices for i=1:size(V,1), Ne{i}=unique(Ne{i}); end
github
jacksky64/imageProcessing-master
MakeContourClockwise3D.m
.m
imageProcessing-master/Matlab Viewer3D/SubFunctions/BasicSnake_version2d/MakeContourClockwise3D.m
1,065
utf_8
967b2d3c686076cf81947641372d0de8
function FV=MakeContourClockwise3D(FV) % This function MakeContourClockwise will make a surface clockwise % contour clockwise. This is done by calculating the volume inside the % surface, if it is negative we change the surface orientation. % % FV=MakeContourClockwise2D(FV); % % input/output, % FV : Triangulated surface description with FV.faces and FV.vertices % % Function is written by D.Kroon University of Twente (July 2010) % Volume inside contour volume=0; for i=1:size(FV.faces,1) a=FV.vertices(FV.faces(i,1),:); b=FV.vertices(FV.faces(i,2),:); c=FV.vertices(FV.faces(i,3),:); k=cross(b,c); v = (a(1)*k(1)+a(2)*k(2)+a(3)*k(3))/6; volume=volume+v; end volume=-(volume); % If the area inside the contour is positive, change from counter-clockwise to % clockwise if(volume<0), FV.faces=[FV.faces(:,3) FV.faces(:,2) FV.faces(:,1)]; end function c=cross(a,b) a=a(:); b=b(:); c = [a(2,:).*b(3,:)-a(3,:).*b(2,:) a(3,:).*b(1,:)-a(1,:).*b(3,:) a(1,:).*b(2,:)-a(2,:).*b(1,:)];
github
jacksky64/imageProcessing-master
SeparateKernel.m
.m
imageProcessing-master/Matlab Viewer3D/SubFunctions/BasicSnake_version2d/SeparateKernel.m
8,608
utf_8
460ab595164db33cf427c62f3a4f0e3b
function [K1 KN ERR]=SeparateKernel(H) % This function SEPARATEKERNEL will separate ( do decomposition ) any % 2D, 3D or nD kernel into 1D kernels. Ofcourse only a sub-set of Kernels % are separable such as a Gaussian Kernel, but it will give least-squares % sollutions for non-separatable kernels. % % Separating a 3D or 4D image filter in to 1D filters will give an large % speed-up in image filtering with for instance the function imfilter. % % [K1 KN ERR]=SeparateKernel(H); % % inputs, % H : The 2D, 3D ..., ND kernel % % outputs, % K1 : Cell array with the 1D kernels % KN : Approximation of the ND input kernel by the 1D kernels % ERR : The sum of absolute difference between approximation and input kernel % % % How the algorithm works: % If we have a separable kernel like % % H = [1 2 1 % 2 4 2 % 3 6 3]; % % We like to solve unknow 1D kernels, % a=[a(1) a(2) a(3)] % b=[b(1) b(2) b(3)] % % We know that, % H = a'*b % % b(1) b(2) b(3) % -------------------- % a(1)|h(1,1) h(1,2) h(1,3) % a(2)|h(2,1) h(2,2) h(2,3) % a(3)|h(3,1) h(3,2) h(3,3) % % Thus, % h(1,1) == a(1)*b(1) % h(2,1) == a(2)*b(1) % h(3,1) == a(3)*b(1) % h(4,1) == a(1)*b(2) % ... % % We want to solve this by using fast matrix (least squares) math, % % c = M * d; % % c a column vector with all kernel values H % d a column vector with the unknown 1D kernels % % But matrices "add" values and we have something like h(1,1) == a(1)*b(1); % We solve this by taking the log at both sides % (We replace zeros by a small value. Whole lines/planes of zeros are % removed at forehand and re-added afterwards) % % log( h(1,1) ) == log(a(1)) + log b(1)) % % The matrix is something like this, % % a1 a2 a3 b1 b2 b3 % M = [1 0 0 1 0 0; h11 % 0 1 0 1 0 0; h21 % 0 0 1 1 0 0; h31 % 1 0 0 0 1 0; h21 % 0 1 0 0 1 0; h22 % 0 0 1 0 1 0; h23 % 1 0 0 0 0 1; h31 % 0 1 0 0 0 1; h32 % 0 0 1 0 0 1]; h33 % % Least squares solution % d = exp(M\log(c)) % % with the 1D kernels % % [a(1);a(2);a(3);b(1);b(2);b(3)] = d % % The Problem of Negative Values!!! % % The log of a negative value is possible it gives a complex value, log(-1) = i*pi % if we take the expontential it is back to the old value, exp(i*pi) = -1 % % But if we use the solver with on of the 1D vectors we get something like, this : % % input result abs(result) angle(result) % -1 -0.0026 + 0.0125i 0.0128 1.7744 % 2 0.0117 + 0.0228i 0.0256 1.0958 % -3 -0.0078 + 0.0376i 0.0384 1.7744 % 4 0.0234 + 0.0455i 0.0512 1.0958 % 5 0.0293 + 0.0569i 0.0640 1.0958 % % The absolute value is indeed correct (difference in scale is compensated % by the order 1D vectors) % % As you can see the angle is correlated with the sign of the values. But I % didn't found the correlation yet. For some matrices it is something like % % sign=mod(angle(solution)*scale,pi) == pi/2; % % In the current algorithm, we just flip the 1D kernel values one by one. % The sign change which gives the smallest error is permanently swapped. % Until swapping signs no longer decreases the error % % Examples, % a=permute(rand(5,1),[1 2 3 4])-0.5; % b=permute(rand(5,1),[2 1 3 4])-0.5; % c=permute(rand(5,1),[3 2 1 4])-0.5; % d=permute(rand(5,1),[4 2 3 1])-0.5; % H = repmat(a,[1 5 5 5]).*repmat(b,[5 1 5 5]).*repmat(c,[5 5 1 5]).*repmat(d,[5 5 5 1]); % [K,KN,err]=SeparateKernel(H); % disp(['Summed Absolute Error between Real and approximation by 1D filters : ' num2str(err)]); % % a=permute(rand(3,1),[1 2 3])-0.5; % b=permute(rand(3,1),[2 1 3])-0.5; % c=permute(rand(3,1),[3 2 1])-0.5; % H = repmat(a,[1 3 3]).*repmat(b,[3 1 3 ]).*repmat(c,[3 3 1 ]) % [K,KN,err]=SeparateKernel(H); err % % a=permute(rand(4,1),[1 2 3])-0.5; % b=permute(rand(4,1),[2 1 3])-0.5; % H = repmat(a,[1 4]).*repmat(b,[4 1]); % [K,KN,err]=SeparateKernel(H); err % % Function is written by D.Kroon, uses "log idea" from A. J. Hendrikse, % University of Twente (July 2010) % We first make some structure which contains information about % the transformation from kernel to 1D kernel array, number of dimensions % and other stuff data=InitializeDataStruct(H); % Make the matrix of c = M * d; M=makeMatrix(data); % Solve c = M * d with least squares warning('off','MATLAB:rankDeficientMatrix'); par=exp(M\log(abs(data.H(:)))); % Improve the values by solving the remaining difference KN = Filter1DtoFilterND(par,data); par2=exp(M\log(abs(KN(:)./data.H(:)))); par=par./par2; % Change the sign of a 1D filtering value if it decrease the error par = FilterCorrSign(par,data); % Split the solution d in separate 1D kernels K1 = ValueList2Filter1D(par,data); % Re-add the removed zero rows/planes to the 1D vectors K1=re_add_zero_rows(data,K1); % Calculate the approximation of the ND kernel if using the 1D kernels KN = Filter1DtoFilterND(par,data,K1); % Calculate the absolute error ERR =sum(abs(H(:)-KN(:))); function par = FilterCorrSign(par,data) Ert=zeros(1,length(par)); ERR=inf; t=0; par=sign(rand(size(par))-0.5).*par; while(t<ERR) % Calculate the approximation of the ND kernel if using the 1D kernels KN = Filter1DtoFilterND(par,data); % Calculate the absolute error ERR =sum(abs(data.H(:)-KN(:))); % Flip the sign of every 1D filter value, and look if the error % improves for i=1:length(par) par2=par; par2(i)=-par2(i); KN = Filter1DtoFilterND(par2,data); Ert(i) =sum(abs(data.H(:)-KN(:))); end % Flip the sign of the 1D filter value with the largest improvement [t,j]=min(Ert); if(t<ERR), par(j)=-par(j); end end function data=InitializeDataStruct(H) data.sizeHreal=size(H); data.nreal=ndims(H); [H,preserve_zeros]=remove_zero_rows(H); data.H=H; data.n=ndims(H); data.preserve_zeros=preserve_zeros; data.H(H==0)=eps; data.sizeH=size(data.H); data.sep_parb=cumsum([1 data.sizeH(1:data.n-1)]); data.sep_pare=cumsum(data.sizeH); data.sep_parl=data.sep_pare-data.sep_parb+1; data.par=(1:numel(H))+1; function [H,preserve_zeros]=remove_zero_rows(H) % Remove whole columns/rows/planes with zeros, % because we know at forehand that they will give a kernel 1D value of 0 % and will otherwise increase the error in the end result. preserve_zeros=zeros(numel(H),2); pz=0; sizeH=size(H); for i=1:ndims(H) H2D=reshape(H,size(H,1),[]); check_zero=~any(H2D,2); if(any(check_zero)) zero_rows=find(check_zero); for j=1:length(zero_rows) pz=pz+1; preserve_zeros(pz,:)=[i zero_rows(j)]; sizeH(1)=sizeH(1)-1; end H2D(check_zero,:)=[]; H=reshape(H2D,sizeH); end H=shiftdim(H,1); sizeH=circshift(sizeH,[0 -1]); H=reshape(H,sizeH); end preserve_zeros=preserve_zeros(1:pz,:); function K1=re_add_zero_rows(data,K1) % Re-add the 1D kernel values responding to a whole column/row or plane % of zeros for i=1:size(data.preserve_zeros,1) di=data.preserve_zeros(i,1); pos=data.preserve_zeros(i,2); if(di>length(K1)), K1{di}=1; end val=K1{di}; val=val(:); val=[val(1:pos-1);0;val(pos:end)]; dim=ones(1,data.nreal); dim(di)=length(val); K1{di}=reshape(val,dim); end function M=makeMatrix(data) M = zeros(numel(data.H),sum(data.sizeH)); K1 = (1:numel(data.H))'; for i=1:data.n; p=data.par(data.sep_parb(i):data.sep_pare(i)); p=p(:); dim=ones(1,data.n); dim(i)=data.sep_parl(i); Ki=reshape(p(:),dim); dim=data.sizeH; dim(i)=1; K2=repmat(Ki,dim)-1; M(sub2ind(size(M),K1(:),K2(:)))=1; end function Kt = Filter1DtoFilterND(par,data,K1) if(nargin==2) Kt=ones(data.sizeH); for i=1:data.n p=par(data.sep_parb(i):data.sep_pare(i)); p=p(:); dim=ones(1,data.n); dim(i)=data.sep_parl(i); Ki=reshape(p(:),dim); dim=data.sizeH; dim(i)=1; Kt=Kt.*repmat(Ki,dim); end else Kt=ones(data.sizeHreal); for i=1:data.n dim=data.sizeHreal; dim(i)=1; Kt=Kt.*repmat(K1{i},dim); end end function K = ValueList2Filter1D(par,data) K=cell(1,data.n); for i=1:data.n p=par(data.sep_parb(i):data.sep_pare(i)); p=p(:); dim=ones(1,data.n); dim(i)=data.sep_parl(i); K{i}=reshape(p(:),dim); end
github
jacksky64/imageProcessing-master
savepgm.m
.m
imageProcessing-master/cameraCalibration/savepgm.m
447
utf_8
b8fe9ed33cbd68ea4b83271b431e3667
%SAVEPGM Write a PGM format file % % SAVEPGM(filename, im) % % Saves the specified image array in a binary (P5) format PGM image file. % % SEE ALSO: loadpgm % % Copyright (c) Peter Corke, 1999 Machine Vision Toolbox for Matlab % Peter Corke 1994 function savepgm(fname, im) fid = fopen(fname, 'w'); [r,c] = size(im'); fprintf(fid, 'P5\n'); fprintf(fid, '%d %d\n', r, c); fprintf(fid, '255\n'); fwrite(fid, im', 'uchar'); fclose(fid);
github
jacksky64/imageProcessing-master
ginput4.m
.m
imageProcessing-master/cameraCalibration/ginput4.m
7,121
utf_8
1d7231b0daed3533514a77f79f4e096a
function [out1,out2,out3] = ginput4(arg1) [out1,out2,out3] = ginput(arg1); return; %GINPUT Graphical input from mouse. % [X,Y] = GINPUT(N) gets N points from the current axes and returns % the X- and Y-coordinates in length N vectors X and Y. The cursor % can be positioned using a mouse (or by using the Arrow Keys on some % systems). Data points are entered by pressing a mouse button % or any key on the keyboard except carriage return, which terminates % the input before N points are entered. % % [X,Y] = GINPUT gathers an unlimited number of points until the % return key is pressed. % % [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that % contains a vector of integers specifying which mouse button was % used (1,2,3 from left) or ASCII numbers if a key on the keyboard % was used. % % Examples: % [x,y] = ginput; % % [x,y] = ginput(5); % % [x, y, button] = ginput(1); % % See also GTEXT, UIRESTORE, UISUSPEND, WAITFORBUTTONPRESS. % Copyright 1984-2006 The MathWorks, Inc. % $Revision: 5.32.4.9 $ $Date: 2006/12/20 07:19:10 $ P = NaN*ones(16,16); P(1:15,1:15) = 2*ones(15,15); P(2:14,2:14) = ones(13,13); P(3:13,3:13) = NaN*ones(11,11); P(6:10,6:10) = 2*ones(5,5); P(7:9,7:9) = 1*ones(3,3); out1 = []; out2 = []; out3 = []; y = []; c = computer; if ~strcmp(c(1:2),'PC') tp = get(0,'TerminalProtocol'); else tp = 'micro'; end if ~strcmp(tp,'none') && ~strcmp(tp,'x') && ~strcmp(tp,'micro'), if nargout == 1, if nargin == 1, out1 = trmginput(arg1); else out1 = trmginput; end elseif nargout == 2 || nargout == 0, if nargin == 1, [out1,out2] = trmginput(arg1); else [out1,out2] = trmginput; end if nargout == 0 out1 = [ out1 out2 ]; end elseif nargout == 3, if nargin == 1, [out1,out2,out3] = trmginput(arg1); else [out1,out2,out3] = trmginput; end end else fig = gcf; figure(gcf); if nargin == 0 how_many = -1; b = []; else how_many = arg1; b = []; if ischar(how_many) ... || size(how_many,1) ~= 1 || size(how_many,2) ~= 1 ... || ~(fix(how_many) == how_many) ... || how_many < 0 error('MATLAB:ginput:NeedPositiveInt', 'Requires a positive integer.') end if how_many == 0 ptr_fig = 0; while(ptr_fig ~= fig) ptr_fig = get(0,'PointerWindow'); end scrn_pt = get(0,'PointerLocation'); loc = get(fig,'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; out1 = pt(1); y = pt(2); elseif how_many < 0 error('MATLAB:ginput:InvalidArgument', 'Argument must be a positive integer.') end end % Suspend figure functions state = uisuspend(fig); toolbar = findobj(allchild(fig),'flat','Type','uitoolbar'); if ~isempty(toolbar) ptButtons = [uigettool(toolbar,'Plottools.PlottoolsOff'), ... uigettool(toolbar,'Plottools.PlottoolsOn')]; ptState = get (ptButtons,'Enable'); set (ptButtons,'Enable','off'); end %set(fig,'pointer','fullcrosshair'); set(fig,'Pointer','custom','PointerShapeCData',P,'PointerShapeHotSpot',[8,8]); fig_units = get(fig,'units'); char = 0; % We need to pump the event queue on unix % before calling WAITFORBUTTONPRESS drawnow while how_many ~= 0 % Use no-side effect WAITFORBUTTONPRESS waserr = 0; try keydown = wfbp; catch waserr = 1; end if(waserr == 1) if(ishandle(fig)) set(fig,'units',fig_units); uirestore(state); error('MATLAB:ginput:Interrupted', 'Interrupted'); else error('MATLAB:ginput:FigureDeletionPause', 'Interrupted by figure deletion'); end end ptr_fig = get(0,'CurrentFigure'); if(ptr_fig == fig) if keydown char = get(fig, 'CurrentCharacter'); button = abs(get(fig, 'CurrentCharacter')); scrn_pt = get(0, 'PointerLocation'); set(fig,'units','pixels') loc = get(fig, 'Position'); % We need to compensate for an off-by-one error: pt = [scrn_pt(1) - loc(1) + 1, scrn_pt(2) - loc(2) + 1]; set(fig,'CurrentPoint',pt); else button = get(fig, 'SelectionType'); if strcmp(button,'open') button = 1; elseif strcmp(button,'normal') button = 1; elseif strcmp(button,'extend') button = 2; elseif strcmp(button,'alt') button = 3; else error('MATLAB:ginput:InvalidSelection', 'Invalid mouse selection.') end end pt = get(gca, 'CurrentPoint'); how_many = how_many - 1; if(char == 13) % & how_many ~= 0) % if the return key was pressed, char will == 13, % and that's our signal to break out of here whether % or not we have collected all the requested data % points. % If this was an early breakout, don't include % the <Return> key info in the return arrays. % We will no longer count it if it's the last input. break; end out1 = [out1;pt(1,1)]; y = [y;pt(1,2)]; b = [b;button]; end end uirestore(state); if ~isempty(toolbar) && ~isempty(ptButtons) set (ptButtons(1),'Enable',ptState{1}); set (ptButtons(2),'Enable',ptState{2}); end set(fig,'units',fig_units); if nargout > 1 out2 = y; if nargout > 2 out3 = b; end else out1 = [out1 y]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = wfbp %WFBP Replacement for WAITFORBUTTONPRESS that has no side effects. fig = gcf; current_char = []; % Now wait for that buttonpress, and check for error conditions waserr = 0; try h=findall(fig,'type','uimenu','accel','C'); % Disabling ^C for edit menu so the only ^C is for set(h,'accel',''); % interrupting the function. keydown = waitforbuttonpress; current_char = double(get(fig,'CurrentCharacter')); % Capturing the character. if~isempty(current_char) && (keydown == 1) % If the character was generated by the if(current_char == 3) % current keypress AND is ^C, set 'waserr'to 1 waserr = 1; % so that it errors out. end end set(h,'accel','C'); % Set back the accelerator for edit menu. catch waserr = 1; end drawnow; if(waserr == 1) set(h,'accel','C'); % Set back the accelerator if it errored out. error('MATLAB:ginput:Interrupted', 'Interrupted'); end if nargout>0, key = keydown; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
jacksky64/imageProcessing-master
loadinr.m
.m
imageProcessing-master/cameraCalibration/loadinr.m
1,029
utf_8
ac39329cc5acba186f4c5ef4c62f3a33
%LOADINR Load an INRIMAGE format file % % LOADINR(filename, im) % % Load an INRIA image format file and return it as a matrix % % SEE ALSO: saveinr % % Copyright (c) Peter Corke, 1999 Machine Vision Toolbox for Matlab % Peter Corke 1996 function im = loadinr(fname, im) fid = fopen(fname, 'r'); s = fgets(fid); if strcmp(s(1:12), '#INRIMAGE-4#') == 0, error('not INRIMAGE format'); end % not very complete, only looks for the X/YDIM keys while 1, s = fgets(fid); n = length(s) - 1; if s(1) == '#', break end if strcmp(s(1:5), 'XDIM='), cols = str2num(s(6:n)); end if strcmp(s(1:5), 'YDIM='), rows = str2num(s(6:n)); end if strcmp(s(1:4), 'CPU='), if strcmp(s(5:n), 'sun') == 0, error('not sun data ordering'); end end end disp(['INRIMAGE format file ' num2str(rows) ' x ' num2str(cols)]) % now the binary data fseek(fid, 256, 'bof'); [im count] = fread(fid, [cols rows], 'float32'); im = im'; if count ~= (rows*cols), error('file too short'); end fclose(fid);
github
jacksky64/imageProcessing-master
saveppm.m
.m
imageProcessing-master/cameraCalibration/saveppm.m
722
utf_8
9904ad3d075a120ca32bd9c10e019512
%SAVEPPM Write a PPM format file % % SAVEPPM(filename, I) % % Saves the specified red, green and blue planes in a binary (P6) % format PPM image file. % % SEE ALSO: loadppm % % Copyright (c) Peter Corke, 1999 Machine Vision Toolbox for Matlab % Peter Corke 1994 function saveppm(fname, I) I = double(I); if size(I,3) == 1, R = I; G = I; B = I; else R = I(:,:,1); G = I(:,:,2); B = I(:,:,3); end; %keyboard; fid = fopen(fname, 'w'); [r,c] = size(R'); fprintf(fid, 'P6\n'); fprintf(fid, '%d %d\n', r, c); fprintf(fid, '255\n'); R = R'; G = G'; B = B'; im = [R(:) G(:) B(:)]; %im = reshape(im,r,c*3); im = im'; %im = im(:); fwrite(fid, im, 'uchar'); fclose(fid);
github
jacksky64/imageProcessing-master
ginput3.m
.m
imageProcessing-master/cameraCalibration/ginput3.m
6,344
utf_8
1cc27af57f9872f05bbf0d9b8a0fdbc9
function [out1,out2,out3] = ginput2(arg1) %GINPUT Graphical input from mouse. % [X,Y] = GINPUT(N) gets N points from the current axes and returns % the X- and Y-coordinates in length N vectors X and Y. The cursor % can be positioned using a mouse (or by using the Arrow Keys on some % systems). Data points are entered by pressing a mouse button % or any key on the keyboard except carriage return, which terminates % the input before N points are entered. % % [X,Y] = GINPUT gathers an unlimited number of points until the % return key is pressed. % % [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that % contains a vector of integers specifying which mouse button was % used (1,2,3 from left) or ASCII numbers if a key on the keyboard % was used. % Copyright (c) 1984-96 by The MathWorks, Inc. % $Revision: 5.18 $ $Date: 1996/11/10 17:48:08 $ % Fixed version by Jean-Yves Bouguet to have a cross instead of 2 lines % More visible for images P = NaN*ones(16,16); P(1:15,1:15) = 2*ones(15,15); P(2:14,2:14) = ones(13,13); P(3:13,3:13) = NaN*ones(11,11); P(6:10,6:10) = 2*ones(5,5); P(7:9,7:9) = 1*ones(3,3); out1 = []; out2 = []; out3 = []; y = []; c = computer; if ~strcmp(c(1:2),'PC') & ~strcmp(c(1:2),'MA') tp = get(0,'TerminalProtocol'); else tp = 'micro'; end if ~strcmp(tp,'none') & ~strcmp(tp,'x') & ~strcmp(tp,'micro'), if nargout == 1, if nargin == 1, eval('out1 = trmginput(arg1);'); else eval('out1 = trmginput;'); end elseif nargout == 2 | nargout == 0, if nargin == 1, eval('[out1,out2] = trmginput(arg1);'); else eval('[out1,out2] = trmginput;'); end if nargout == 0 out1 = [ out1 out2 ]; end elseif nargout == 3, if nargin == 1, eval('[out1,out2,out3] = trmginput(arg1);'); else eval('[out1,out2,out3] = trmginput;'); end end else fig = gcf; figure(gcf); if nargin == 0 how_many = -1; b = []; else how_many = arg1; b = []; if isstr(how_many) ... | size(how_many,1) ~= 1 | size(how_many,2) ~= 1 ... | ~(fix(how_many) == how_many) ... | how_many < 0 error('Requires a positive integer.') end if how_many == 0 ptr_fig = 0; while(ptr_fig ~= fig) ptr_fig = get(0,'PointerWindow'); end scrn_pt = get(0,'PointerLocation'); loc = get(fig,'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; out1 = pt(1); y = pt(2); elseif how_many < 0 error('Argument must be a positive integer.') end end pointer = get(gcf,'pointer'); set(gcf,'Pointer','custom','PointerShapeCData',P,'PointerShapeHotSpot',[8,8]); %set(gcf,'pointer','crosshair'); fig_units = get(fig,'units'); char = 0; while how_many ~= 0 % Use no-side effect WAITFORBUTTONPRESS waserr = 0; eval('keydown = wfbp;', 'waserr = 1;'); if(waserr == 1) if(ishandle(fig)) set(fig,'pointer',pointer,'units',fig_units); error('Interrupted'); else error('Interrupted by figure deletion'); end end ptr_fig = get(0,'CurrentFigure'); if(ptr_fig == fig) if keydown char = get(fig, 'CurrentCharacter'); button = abs(get(fig, 'CurrentCharacter')); scrn_pt = get(0, 'PointerLocation'); set(fig,'units','pixels') loc = get(fig, 'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; set(fig,'CurrentPoint',pt); else button = get(fig, 'SelectionType'); if strcmp(button,'open') button = 1; %b(length(b)); elseif strcmp(button,'normal') button = 1; elseif strcmp(button,'extend') button = 2; elseif strcmp(button,'alt') button = 3; else error('Invalid mouse selection.') end end pt = get(gca, 'CurrentPoint'); how_many = how_many - 1; if(char == 13) % & how_many ~= 0) % if the return key was pressed, char will == 13, % and that's our signal to break out of here whether % or not we have collected all the requested data % points. % If this was an early breakout, don't include % the <Return> key info in the return arrays. % We will no longer count it if it's the last input. break; end out1 = [out1;pt(1,1)]; y = [y;pt(1,2)]; b = [b;button]; end end set(fig,'pointer',pointer,'units',fig_units); if nargout > 1 out2 = y; if nargout > 2 out3 = b; end else out1 = [out1 y]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = wfbp %WFBP Replacement for WAITFORBUTTONPRESS that has no side effects. % Remove figure button functions fprops = {'windowbuttonupfcn','buttondownfcn', ... 'windowbuttondownfcn','windowbuttonmotionfcn'}; fig = gcf; fvals = get(fig,fprops); set(fig,fprops,{'','','',''}) % Remove all other buttondown functions ax = findobj(fig,'type','axes'); if isempty(ax) ch = {}; else ch = get(ax,{'Children'}); end for i=1:length(ch), ch{i} = ch{i}(:)'; end h = [ax(:)',ch{:}]; vals = get(h,{'buttondownfcn'}); mt = repmat({''},size(vals)); set(h,{'buttondownfcn'},mt); % Now wait for that buttonpress, and check for error conditions waserr = 0; eval(['if nargout==0,', ... ' waitforbuttonpress,', ... 'else,', ... ' keydown = waitforbuttonpress;',... 'end' ], 'waserr = 1;'); % Put everything back if(ishandle(fig)) set(fig,fprops,fvals) set(h,{'buttondownfcn'},vals) end if(waserr == 1) error('Interrupted'); end if nargout>0, key = keydown; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
jacksky64/imageProcessing-master
ginput2.m
.m
imageProcessing-master/cameraCalibration/ginput2.m
6,105
utf_8
983a72db9a079ba54ab084149ced6ae9
function [out1,out2,out3] = ginput2(arg1) %GINPUT Graphical input from mouse. % [X,Y] = GINPUT(N) gets N points from the current axes and returns % the X- and Y-coordinates in length N vectors X and Y. The cursor % can be positioned using a mouse (or by using the Arrow Keys on some % systems). Data points are entered by pressing a mouse button % or any key on the keyboard except carriage return, which terminates % the input before N points are entered. % % [X,Y] = GINPUT gathers an unlimited number of points until the % return key is pressed. % % [X,Y,BUTTON] = GINPUT(N) returns a third result, BUTTON, that % contains a vector of integers specifying which mouse button was % used (1,2,3 from left) or ASCII numbers if a key on the keyboard % was used. % Copyright (c) 1984-96 by The MathWorks, Inc. % $Revision: 5.18 $ $Date: 1996/11/10 17:48:08 $ % Fixed version by Jean-Yves Bouguet to have a cross instead of 2 lines % More visible for images out1 = []; out2 = []; out3 = []; y = []; c = computer; if ~strcmp(c(1:2),'PC') & ~strcmp(c(1:2),'MA') tp = get(0,'TerminalProtocol'); else tp = 'micro'; end if ~strcmp(tp,'none') & ~strcmp(tp,'x') & ~strcmp(tp,'micro'), if nargout == 1, if nargin == 1, eval('out1 = trmginput(arg1);'); else eval('out1 = trmginput;'); end elseif nargout == 2 | nargout == 0, if nargin == 1, eval('[out1,out2] = trmginput(arg1);'); else eval('[out1,out2] = trmginput;'); end if nargout == 0 out1 = [ out1 out2 ]; end elseif nargout == 3, if nargin == 1, eval('[out1,out2,out3] = trmginput(arg1);'); else eval('[out1,out2,out3] = trmginput;'); end end else fig = gcf; figure(gcf); if nargin == 0 how_many = -1; b = []; else how_many = arg1; b = []; if isstr(how_many) ... | size(how_many,1) ~= 1 | size(how_many,2) ~= 1 ... | ~(fix(how_many) == how_many) ... | how_many < 0 error('Requires a positive integer.') end if how_many == 0 ptr_fig = 0; while(ptr_fig ~= fig) ptr_fig = get(0,'PointerWindow'); end scrn_pt = get(0,'PointerLocation'); loc = get(fig,'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; out1 = pt(1); y = pt(2); elseif how_many < 0 error('Argument must be a positive integer.') end end pointer = get(gcf,'pointer'); set(gcf,'pointer','crosshair'); fig_units = get(fig,'units'); char = 0; while how_many ~= 0 % Use no-side effect WAITFORBUTTONPRESS waserr = 0; eval('keydown = wfbp;', 'waserr = 1;'); if(waserr == 1) if(ishandle(fig)) set(fig,'pointer',pointer,'units',fig_units); error('Interrupted'); else error('Interrupted by figure deletion'); end end ptr_fig = get(0,'CurrentFigure'); if(ptr_fig == fig) if keydown char = get(fig, 'CurrentCharacter'); button = abs(get(fig, 'CurrentCharacter')); scrn_pt = get(0, 'PointerLocation'); set(fig,'units','pixels') loc = get(fig, 'Position'); pt = [scrn_pt(1) - loc(1), scrn_pt(2) - loc(2)]; set(fig,'CurrentPoint',pt); else button = get(fig, 'SelectionType'); if strcmp(button,'open') button = 1; %b(length(b)); elseif strcmp(button,'normal') button = 1; elseif strcmp(button,'extend') button = 2; elseif strcmp(button,'alt') button = 3; else error('Invalid mouse selection.') end end pt = get(gca, 'CurrentPoint'); how_many = how_many - 1; if(char == 13) % & how_many ~= 0) % if the return key was pressed, char will == 13, % and that's our signal to break out of here whether % or not we have collected all the requested data % points. % If this was an early breakout, don't include % the <Return> key info in the return arrays. % We will no longer count it if it's the last input. break; end out1 = [out1;pt(1,1)]; y = [y;pt(1,2)]; b = [b;button]; end end set(fig,'pointer',pointer,'units',fig_units); if nargout > 1 out2 = y; if nargout > 2 out3 = b; end else out1 = [out1 y]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function key = wfbp %WFBP Replacement for WAITFORBUTTONPRESS that has no side effects. % Remove figure button functions fprops = {'windowbuttonupfcn','buttondownfcn', ... 'windowbuttondownfcn','windowbuttonmotionfcn'}; fig = gcf; fvals = get(fig,fprops); set(fig,fprops,{'','','',''}) % Remove all other buttondown functions ax = findobj(fig,'type','axes'); if isempty(ax) ch = {}; else ch = get(ax,{'Children'}); end for i=1:length(ch), ch{i} = ch{i}(:)'; end h = [ax(:)',ch{:}]; vals = get(h,{'buttondownfcn'}); mt = repmat({''},size(vals)); set(h,{'buttondownfcn'},mt); % Now wait for that buttonpress, and check for error conditions waserr = 0; eval(['if nargout==0,', ... ' waitforbuttonpress,', ... 'else,', ... ' keydown = waitforbuttonpress;',... 'end' ], 'waserr = 1;'); % Put everything back if(ishandle(fig)) set(fig,fprops,fvals) set(h,{'buttondownfcn'},vals) end if(waserr == 1) error('Interrupted'); end if nargout>0, key = keydown; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
github
jacksky64/imageProcessing-master
loadppm.m
.m
imageProcessing-master/cameraCalibration/loadppm.m
2,355
utf_8
c8d750733c522f56f3aa17a4ca9f9df1
%LOADPPM Load a PPM image % % I = loadppm(filename) % % Returns a matrix containing the image loaded from the PPM format % file filename. Handles ASCII (P3) and binary (P6) PPM file formats. % % If the filename has no extension, and open fails, a '.ppm' and % '.pnm' extension will be tried. % % SEE ALSO: saveppm loadpgm % % Copyright (c) Peter Corke, 1999 Machine Vision Toolbox for Matlab % Peter Corke 1994 function I = loadppm(file) white = [' ' 9 10 13]; % space, tab, lf, cr white = setstr(white); fid = fopen(file, 'r'); if fid < 0, fid = fopen([file '.ppm'], 'r'); end if fid < 0, fid = fopen([file '.pnm'], 'r'); end if fid < 0, error('Couldn''t open file'); end magic = fread(fid, 2, 'char'); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end cols = fscanf(fid, '%d', 1); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end rows = fscanf(fid, '%d', 1); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end maxval = fscanf(fid, '%d', 1); % assume a carriage return only: c = fread(fid,1,'char'); % bug: because the image might be starting with special characters! %while 1 % c = fread(fid,1,'char'); % if c == '#', % fgetl(fid); % elseif ~any(c == white) % fseek(fid, -1, 'cof'); % unputc() % break; % end %end if magic(1) == 'P', if magic(2) == '3', %disp(['ASCII PPM file ' num2str(rows) ' x ' num2str(cols)]) I = fscanf(fid, '%d', [cols*3 rows]); elseif magic(2) == '6', %disp(['Binary PPM file ' num2str(rows) ' x ' num2str(cols)]) if maxval == 1, fmt = 'unint1'; elseif maxval == 15, fmt = 'uint4'; elseif maxval == 255, fmt = 'uint8'; elseif maxval == 2^32-1, fmt = 'uint32'; end I = fread(fid, [cols*3 rows], fmt); else disp('Not a PPM file'); end end % % now the matrix has interleaved columns of R, G, B % I = I'; size(I); R = I(:,1:3:(cols*3)); G = I(:,2:3:(cols*3)); B = I(:,3:3:(cols*3)); fclose(fid); I = zeros(rows,cols,3); I(:,:,1) = R; I(:,:,2) = G; I(:,:,3) = B; I = uint8(I);
github
jacksky64/imageProcessing-master
saveinr.m
.m
imageProcessing-master/cameraCalibration/saveinr.m
949
utf_8
a18df4fba021be006842fbc35166bc23
%SAVEINR Write an INRIMAGE format file % % SAVEINR(filename, im) % % Saves the specified image array in a INRIA image format file. % % SEE ALSO: loadinr % % Copyright (c) Peter Corke, 1999 Machine Vision Toolbox for Matlab % Peter Corke 1996 function saveinr(fname, im) fid = fopen(fname, 'w'); [r,c] = size(im'); % build the header hdr = []; s = sprintf('#INRIMAGE-4#{\n'); hdr = [hdr s]; s = sprintf('XDIM=%d\n',c); hdr = [hdr s]; s = sprintf('YDIM=%d\n',r); hdr = [hdr s]; s = sprintf('ZDIM=1\n'); hdr = [hdr s]; s = sprintf('VDIM=1\n'); hdr = [hdr s]; s = sprintf('TYPE=float\n'); hdr = [hdr s]; s = sprintf('PIXSIZE=32\n'); hdr = [hdr s]; s = sprintf('SCALE=2**0\n'); hdr = [hdr s]; s = sprintf('CPU=sun\n#'); hdr = [hdr s]; % make it 256 bytes long and write it hdr256 = zeros(1,256); hdr256(1:length(hdr)) = hdr; fwrite(fid, hdr256, 'uchar'); % now the binary data fwrite(fid, im', 'float32'); fclose(fid)
github
jacksky64/imageProcessing-master
stereo_gui.m
.m
imageProcessing-master/cameraCalibration/stereo_gui.m
6,208
utf_8
6cc48675fdf9c8c36bc147da7d046d06
% stereo_gui % Stereo Camera Calibration Toolbox (two cameras, internal and external calibration): % % It is assumed that the two cameras (left and right) have been calibrated with the pattern at the same 3D locations, and the same points % on the pattern (select the same grid points). Therefore, in particular, the same number of images were used to calibrate both cameras. % The two calibration result files must have been saved under two seperate data files (Calib_Results_left.mat and Calib_Results_right.mat) % prior to running this toolbox. To generate the two files, run the classic Camera Calibration toolbox calib.m. % % INPUT: Calib_Results_left.mat, Calib_Results_right.mat -> Generated by the standard calibration toolbox on the two cameras individually % OUTPUT: Calib_Results_stereo.mat -> The saved result after global stereo calibration (after running stereo calibration, and hitting Save stereo calib results) % % Main result variables stored in Calib_Results_stereo.mat: % om, R, T: relative rotation and translation of the right camera wrt the left camera % fc_left, cc_left, kc_left, alpha_c_left, KK_left: New intrinsic parameters of the left camera % fc_right, cc_right, kc_right, alpha_c_right, KK_right: New intrinsic parameters of the right camera % % Both sets of intrinsic parameters are equivalent to the classical {fc,cc,kc,alpha_c,KK} described online at: % http://www.vision.caltech.edu/bouguetj/calib_doc/parameters.html % % Note: If you do not want to recompute the intinsic parameters, through stereo calibration you may want to set % recompute_intrinsic_right and recompute_intrinsic_left to zero, prior to running stereo calibration. Default: 1 % % Definition of the extrinsic parameters: R and om are related through the rodrigues formula (R=rodrigues(om)). % Consider a point P of coordinates XL and XR in the left and right camera reference frames respectively. % XL and XR are related to each other through the following rigid motion transformation: % XR = R * XL + T % R and T (or equivalently om and T) fully describe the relative displacement of the two cameras. % % % If the Warning message "Disabling view kk - Reason: the left and right images are found inconsistent" is encountered during stereo calibration, % that probably means that for the kkth pair of images, the left and right images are found to have captured the calibration pattern at two % different locations in space. That means that the two views are not consistent, and therefore cannot be used for stereo calibration. % When capturing your images, make sure that you do not move the calibration pattern between capturing the left and the right images. % The pattwern can (and should) be moved in space only between two sets of (left,right) images. % Another reason for inconsistency is that you selected a different set of points on the pattern when running the separate calibrations % (leading to the two files Calib_Results_left.mat and Calib_Results_left.mat). Make sure that the same points are selected in the % two separate calibration. In other words, the points need to correspond. % (c) Jean-Yves Bouguet - Intel Corporation % October 25, 2001 -- Last updated June 14, 2004 function stereo_gui, cell_list = {}; %-------- Begin editable region -------------% %-------- Begin editable region -------------% fig_number = 1; title_figure = 'Stereo Camera Calibration Toolbox'; cell_list{1,1} = {'Load left and right calibration files','load_stereo_calib_files;'}; cell_list{1,2} = {'Run stereo calibration','go_calib_stereo;'}; cell_list{2,1} = {'Show Extrinsics of stereo rig','ext_calib_stereo;'}; cell_list{2,2} = {'Show Intrinsic parameters','show_stereo_calib_results;'}; cell_list{3,1} = {'Save stereo calib results','saving_stereo_calib;'}; cell_list{3,2} = {'Load stereo calib results','loading_stereo_calib;'}; cell_list{4,1} = {'Rectify the calibration images','rectify_stereo_pair;'}; cell_list{4,2} = {'Exit',['disp(''Bye. To run again, type stereo_gui.''); close(' num2str(fig_number) ');']}; %{'Exit','calib_gui;'}; show_window(cell_list,fig_number,title_figure,150,14); %-------- End editable region -------------% %-------- End editable region -------------% %------- DO NOT EDIT ANYTHING BELOW THIS LINE -----------% function show_window(cell_list,fig_number,title_figure,x_size,y_size,gap_x,font_name,font_size) if ~exist('cell_list'), error('No description of the functions'); end; if ~exist('fig_number'), fig_number = 1; end; if ~exist('title_figure'), title_figure = ''; end; if ~exist('x_size'), x_size = 85; end; if ~exist('y_size'), y_size = 14; end; if ~exist('gap_x'), gap_x = 0; end; if ~exist('font_name'), font_name = 'clean'; end; if ~exist('font_size'), font_size = 8; end; figure(fig_number); clf; pos = get(fig_number,'Position'); [n_row,n_col] = size(cell_list); fig_size_x = x_size*n_col+(n_col+1)*gap_x; fig_size_y = y_size*n_row+(n_row+1)*gap_x; set(fig_number,'Units','points', ... 'BackingStore','off', ... 'Color',[0.8 0.8 0.8], ... 'MenuBar','none', ... 'Resize','off', ... 'Name',title_figure, ... 'Position',[pos(1) pos(2) fig_size_x fig_size_y], ... 'NumberTitle','off'); %,'WindowButtonMotionFcn',['figure(' num2str(fig_number) ');']); h_mat = zeros(n_row,n_col); posx = zeros(n_row,n_col); posy = zeros(n_row,n_col); for i=n_row:-1:1, for j = n_col:-1:1, posx(i,j) = gap_x+(j-1)*(x_size+gap_x); posy(i,j) = fig_size_y - i*(gap_x+y_size); end; end; for i=n_row:-1:1, for j = n_col:-1:1, if ~isempty(cell_list{i,j}), if ~isempty(cell_list{i,j}{1}) & ~isempty(cell_list{i,j}{2}), h_mat(i,j) = uicontrol('Parent',fig_number, ... 'Units','points', ... 'Callback',cell_list{i,j}{2}, ... 'ListboxTop',0, ... 'Position',[posx(i,j) posy(i,j) x_size y_size], ... 'String',cell_list{i,j}{1}, ... 'fontsize',font_size,... 'fontname',font_name,... 'Tag','Pushbutton1'); end; end; end; end; %------ END PROTECTED REGION ----------------%
github
jacksky64/imageProcessing-master
loadpgm.m
.m
imageProcessing-master/cameraCalibration/loadpgm.m
1,838
utf_8
6ec18330c2633d5519c72eb2e6fe963b
%LOADPGM Load a PGM image % % I = loadpgm(filename) % % Returns a matrix containing the image loaded from the PGM format % file filename. Handles ASCII (P2) and binary (P5) PGM file formats. % % If the filename has no extension, and open fails, a '.pgm' will % be appended. % % % Copyright (c) Peter Corke, 1999 Machine Vision Toolbox for Matlab % Peter Corke 1994 function I = loadpgm(file) white = [' ' 9 10 13]; % space, tab, lf, cr white = setstr(white); fid = fopen(file, 'r'); if fid < 0, fid = fopen([file '.pgm'], 'r'); end if fid < 0, error('Couldn''t open file'); end magic = fread(fid, 2, 'char'); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end cols = fscanf(fid, '%d', 1); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end rows = fscanf(fid, '%d', 1); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end maxval = fscanf(fid, '%d', 1); while 1 c = fread(fid,1,'char'); if c == '#', fgetl(fid); elseif ~any(c == white) fseek(fid, -1, 'cof'); % unputc() break; end end if magic(1) == 'P', if magic(2) == '2', %disp(['ASCII PGM file ' num2str(rows) ' x ' num2str(cols)]) I = fscanf(fid, '%d', [cols rows])'; elseif magic(2) == '5', %disp(['Binary PGM file ' num2str(rows) ' x ' num2str(cols)]) if maxval == 1, fmt = 'unint1'; elseif maxval == 15, fmt = 'uint4'; elseif maxval == 255, fmt = 'uint8'; elseif maxval == 2^32-1, fmt = 'uint32'; end I = fread(fid, [cols rows], fmt)'; else disp('Not a PGM file'); end end fclose(fid);
github
jacksky64/imageProcessing-master
pcamat.m
.m
imageProcessing-master/FastICA_2.5/pcamat.m
12,075
utf_8
bcb1117d4132558d0d54d8b7b616a902
function [E, D] = pcamat(vectors, firstEig, lastEig, s_interactive, ... s_verbose); %PCAMAT - Calculates the pca for data % % [E, D] = pcamat(vectors, firstEig, lastEig, ... % interactive, verbose); % % Calculates the PCA matrices for given data (row) vectors. Returns % the eigenvector (E) and diagonal eigenvalue (D) matrices containing the % selected subspaces. Dimensionality reduction is controlled with % the parameters 'firstEig' and 'lastEig' - but it can also be done % interactively by setting parameter 'interactive' to 'on' or 'gui'. % % ARGUMENTS % % vectors Data in row vectors. % firstEig Index of the largest eigenvalue to keep. % Default is 1. % lastEig Index of the smallest eigenvalue to keep. % Default is equal to dimension of vectors. % interactive Specify eigenvalues to keep interactively. Note that if % you set 'interactive' to 'on' or 'gui' then the values % for 'firstEig' and 'lastEig' will be ignored, but they % still have to be entered. If the value is 'gui' then the % same graphical user interface as in FASTICAG will be % used. Default is 'off'. % verbose Default is 'on'. % % % EXAMPLE % [E, D] = pcamat(vectors); % % Note % The eigenvalues and eigenvectors returned by PCAMAT are not sorted. % % This function is needed by FASTICA and FASTICAG % For historical reasons this version does not sort the eigenvalues or % the eigen vectors in any ways. Therefore neither does the FASTICA or % FASTICAG. Generally it seams that the components returned from % whitening is almost in reversed order. (That means, they usually are, % but sometime they are not - depends on the EIG-command of matlab.) % @(#)$Id: pcamat.m,v 1.5 2003/12/15 18:24:32 jarmo Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Default values: if nargin < 5, s_verbose = 'on'; end if nargin < 4, s_interactive = 'off'; end if nargin < 3, lastEig = size(vectors, 1); end if nargin < 2, firstEig = 1; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Check the optional parameters; switch lower(s_verbose) case 'on' b_verbose = 1; case 'off' b_verbose = 0; otherwise error(sprintf('Illegal value [ %s ] for parameter: ''verbose''\n', s_verbose)); end switch lower(s_interactive) case 'on' b_interactive = 1; case 'off' b_interactive = 0; case 'gui' b_interactive = 2; otherwise error(sprintf('Illegal value [ %s ] for parameter: ''interactive''\n', ... s_interactive)); end oldDimension = size (vectors, 1); if ~(b_interactive) if lastEig < 1 | lastEig > oldDimension error(sprintf('Illegal value [ %d ] for parameter: ''lastEig''\n', lastEig)); end if firstEig < 1 | firstEig > lastEig error(sprintf('Illegal value [ %d ] for parameter: ''firstEig''\n', firstEig)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Calculate PCA % Calculate the covariance matrix. if b_verbose, fprintf ('Calculating covariance...\n'); end covarianceMatrix = cov(vectors', 1); % Calculate the eigenvalues and eigenvectors of covariance % matrix. [E, D] = eig (covarianceMatrix); % The rank is determined from the eigenvalues - and not directly by % using the function rank - because function rank uses svd, which % in some cases gives a higher dimensionality than what can be used % with eig later on (eig then gives negative eigenvalues). rankTolerance = 1e-7; maxLastEig = sum (diag (D) > rankTolerance); if maxLastEig == 0, fprintf (['Eigenvalues of the covariance matrix are' ... ' all smaller than tolerance [ %g ].\n' ... 'Please make sure that your data matrix contains' ... ' nonzero values.\nIf the values are very small,' ... ' try rescaling the data matrix.\n'], rankTolerance); error ('Unable to continue, aborting.'); end % Sort the eigenvalues - decending. eigenvalues = flipud(sort(diag(D))); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Interactive part - command-line if b_interactive == 1 % Show the eigenvalues to the user hndl_win=figure; bar(eigenvalues); title('Eigenvalues'); % ask the range from the user... % ... and keep on asking until the range is valid :-) areValuesOK=0; while areValuesOK == 0 firstEig = input('The index of the largest eigenvalue to keep? (1) '); lastEig = input(['The index of the smallest eigenvalue to keep? (' ... int2str(oldDimension) ') ']); % Check the new values... % if they are empty then use default values if isempty(firstEig), firstEig = 1;end if isempty(lastEig), lastEig = oldDimension;end % Check that the entered values are within the range areValuesOK = 1; if lastEig < 1 | lastEig > oldDimension fprintf('Illegal number for the last eigenvalue.\n'); areValuesOK = 0; end if firstEig < 1 | firstEig > lastEig fprintf('Illegal number for the first eigenvalue.\n'); areValuesOK = 0; end end % close the window close(hndl_win); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Interactive part - GUI if b_interactive == 2 % Show the eigenvalues to the user hndl_win = figure('Color',[0.8 0.8 0.8], ... 'PaperType','a4letter', ... 'Units', 'normalized', ... 'Name', 'FastICA: Reduce dimension', ... 'NumberTitle','off', ... 'Tag', 'f_eig'); h_frame = uicontrol('Parent', hndl_win, ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'Units', 'normalized', ... 'Position',[0.13 0.05 0.775 0.17], ... 'Style','frame', ... 'Tag','f_frame'); b = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'HorizontalAlignment','left', ... 'Position',[0.142415 0.0949436 0.712077 0.108507], ... 'String','Give the indices of the largest and smallest eigenvalues of the covariance matrix to be included in the reduced data.', ... 'Style','text', ... 'Tag','StaticText1'); e_first = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'Callback',[ ... 'f=round(str2num(get(gcbo, ''String'')));' ... 'if (f < 1), f=1; end;' ... 'l=str2num(get(findobj(''Tag'',''e_last''), ''String''));' ... 'if (f > l), f=l; end;' ... 'set(gcbo, ''String'', int2str(f));' ... ], ... 'BackgroundColor',[1 1 1], ... 'HorizontalAlignment','right', ... 'Position',[0.284831 0.0678168 0.12207 0.0542535], ... 'Style','edit', ... 'String', '1', ... 'Tag','e_first'); b = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'HorizontalAlignment','left', ... 'Position',[0.142415 0.0678168 0.12207 0.0542535], ... 'String','Range from', ... 'Style','text', ... 'Tag','StaticText2'); e_last = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'Callback',[ ... 'l=round(str2num(get(gcbo, ''String'')));' ... 'lmax = get(gcbo, ''UserData'');' ... 'if (l > lmax), l=lmax; fprintf([''The selected value was too large, or the selected eigenvalues were close to zero\n'']); end;' ... 'f=str2num(get(findobj(''Tag'',''e_first''), ''String''));' ... 'if (l < f), l=f; end;' ... 'set(gcbo, ''String'', int2str(l));' ... ], ... 'BackgroundColor',[1 1 1], ... 'HorizontalAlignment','right', ... 'Position',[0.467936 0.0678168 0.12207 0.0542535], ... 'Style','edit', ... 'String', int2str(maxLastEig), ... 'UserData', maxLastEig, ... 'Tag','e_last'); % in the first version oldDimension was used instead of % maxLastEig, but since the program would automatically % drop the eigenvalues afte maxLastEig... b = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'BackgroundColor',[0.701961 0.701961 0.701961], ... 'HorizontalAlignment','left', ... 'Position',[0.427246 0.0678168 0.0406901 0.0542535], ... 'String','to', ... 'Style','text', ... 'Tag','StaticText3'); b = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'Callback','uiresume(gcbf)', ... 'Position',[0.630697 0.0678168 0.12207 0.0542535], ... 'String','OK', ... 'Tag','Pushbutton1'); b = uicontrol('Parent',hndl_win, ... 'Units','normalized', ... 'Callback',[ ... 'gui_help(''pcamat'');' ... ], ... 'Position',[0.767008 0.0678168 0.12207 0.0542535], ... 'String','Help', ... 'Tag','Pushbutton2'); h_axes = axes('Position' ,[0.13 0.3 0.775 0.6]); set(hndl_win, 'currentaxes',h_axes); bar(eigenvalues); title('Eigenvalues'); uiwait(hndl_win); firstEig = str2num(get(e_first, 'String')); lastEig = str2num(get(e_last, 'String')); % close the window close(hndl_win); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % See if the user has reduced the dimension enought if lastEig > maxLastEig lastEig = maxLastEig; if b_verbose fprintf('Dimension reduced to %d due to the singularity of covariance matrix\n',... lastEig-firstEig+1); end else % Reduce the dimensionality of the problem. if b_verbose if oldDimension == (lastEig - firstEig + 1) fprintf ('Dimension not reduced.\n'); else fprintf ('Reducing dimension...\n'); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Drop the smaller eigenvalues if lastEig < oldDimension lowerLimitValue = (eigenvalues(lastEig) + eigenvalues(lastEig + 1)) / 2; else lowerLimitValue = eigenvalues(oldDimension) - 1; end lowerColumns = diag(D) > lowerLimitValue; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Drop the larger eigenvalues if firstEig > 1 higherLimitValue = (eigenvalues(firstEig - 1) + eigenvalues(firstEig)) / 2; else higherLimitValue = eigenvalues(1) + 1; end higherColumns = diag(D) < higherLimitValue; % Combine the results from above selectedColumns = lowerColumns & higherColumns; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % print some info for the user if b_verbose fprintf ('Selected [ %d ] dimensions.\n', sum (selectedColumns)); end if sum (selectedColumns) ~= (lastEig - firstEig + 1), error ('Selected a wrong number of dimensions.'); end if b_verbose fprintf ('Smallest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(lastEig)); fprintf ('Largest remaining (non-zero) eigenvalue [ %g ]\n', eigenvalues(firstEig)); fprintf ('Sum of removed eigenvalues [ %g ]\n', sum(diag(D) .* ... (~selectedColumns))); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Select the colums which correspond to the desired range % of eigenvalues. E = selcol(E, selectedColumns); D = selcol(selcol(D, selectedColumns)', selectedColumns); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Some more information if b_verbose sumAll=sum(eigenvalues); sumUsed=sum(diag(D)); retained = (sumUsed / sumAll) * 100; fprintf('[ %g ] %% of (non-zero) eigenvalues retained.\n', retained); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function newMatrix = selcol(oldMatrix, maskVector); % newMatrix = selcol(oldMatrix, maskVector); % % Selects the columns of the matrix that marked by one in the given vector. % The maskVector is a column vector. % 15.3.1998 if size(maskVector, 1) ~= size(oldMatrix, 2), error ('The mask vector and matrix are of uncompatible size.'); end numTaken = 0; for i = 1 : size (maskVector, 1), if maskVector(i, 1) == 1, takingMask(1, numTaken + 1) = i; numTaken = numTaken + 1; end end newMatrix = oldMatrix(:, takingMask);
github
jacksky64/imageProcessing-master
icaplot.m
.m
imageProcessing-master/FastICA_2.5/icaplot.m
13,259
utf_8
dde3e6d852f657a3c1eaacbd03f5dcc7
function icaplot(mode, varargin); %ICAPLOT - plot signals in various ways % % ICAPLOT is mainly for plottinf and comparing the mixed signals and % separated ica-signals. % % ICAPLOT has many different modes. The first parameter of the function % defines the mode. Other parameters and their order depends on the % mode. The explanation for the more common parameters is in the end. % % Classic % icaplot('classic', s1, n1, range, xrange, titlestr) % % Plots the signals in the same manner as the FASTICA and FASTICAG % programs do. All the signals are plotted in their own axis. % % Complot % icaplot('complot', s1, n1, range, xrange, titlestr) % % The signals are plotted on the same axis. This is good for % visualization of the shape of the signals. The scale of the signals % has been altered so that they all fit nicely. % % Histogram % icaplot('histogram', s1, n1, range, bins, style) % % The histogram of the signals is plotted. The number of bins can be % specified with 'bins'-parameter. The style for the histograms can % be either 'bar' (default) of 'line'. % % Scatter % icaplot('scatter', s1, n1, s2, n2, range, titlestr, s1label, % s2label, markerstr) % % A scatterplot is plotted so that the signal 1 is the 'X'-variable % and the signal 2 is the 'Y'-variable. The 'markerstr' can be used % to specify the maker used in the plot. The format for 'markerstr' % is the same as for Matlab's PLOT. % % Compare % icaplot('compare', s1, n1, s2, n2, range, xrange, titlestr, % s1label, s2label) % % This for for comparing two signals. The main used in this context % would probably be to see how well the separated ICA-signals explain % the observed mixed signals. The s2 signals are first scaled with % REGRESS function. % % Compare - Sum % icaplot('sum', s1, n1, s2, n2, range, xrange, titlestr, s1label, % s2label) % % The same as Compare, but this time the signals in s2 (specified by % n2) are summed together. % % Compare - Sumerror % icaplot('sumerror', s1, n1, s2, n2, range, xrange, titlestr, % s1label, s2label) % % The same as Compare - Sum, but also the 'error' between the signal % 1 and the summed IC's is plotted. % % % More common parameters % The signals to be plotted are in matrices s1 and s2. The n1 and n2 % are used to tell the index of the signal or signals to be plotted % from s1 or s2. If n1 or n2 has a value of 0, then all the signals % from corresponding matrix will be plotted. The values for n1 and n2 % can also be vectors (like: [1 3 4]) In some casee if there are more % than 1 signal to be plotted from s1 or s2 then the plot will % contain as many subplots as are needed. % % The range of the signals to be plotted can be limited with % 'range'-parameter. It's value is a vector ( 10000:15000 ). If range % is 0, then the whole range will be plotted. % % The 'xrange' is used to specify only the labels used on the % x-axis. The value of 'xrange' is a vector containing the x-values % for the plots or [start end] for begin and end of the range % ( 10000:15000 or [10 15] ). If xrange is 0, then value of range % will be used for x-labels. % % You can give a title for the plot with 'titlestr'. Also the % 's1label' and 's2label' are used to give more meaningfull label for % the signals. % % Lastly, you can omit some of the arguments from the and. You will % have to give values for the signal matrices (s1, s2) and the % indexes (n1, n2) % @(#)$Id: icaplot.m,v 1.2 2003/04/05 14:23:58 jarmo Exp $ switch mode %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % 'dispsig' is to replace the old DISPSIG % '' & 'classic' are just another names - '' quite short one :-) case {'', 'classic', 'dispsig'} % icaplot(mode, s1, n1, range, xrange, titlestr) if length(varargin) < 1, error('Not enough arguments.'); end if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end if length(varargin) < 3, range = 0;else range = varargin{3}; end if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end s1 = varargin{1}; range=chkrange(range, s1); xrange=chkxrange(xrange, range); n1=chkn(n1, s1); clf; numSignals = size(n1, 2); for i = 1:numSignals, subplot(numSignals, 1, i); plot(xrange, s1(n1(i), range)); end subplot(numSignals,1, 1); if (~isempty(titlestr)) title(titlestr); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'complot' % icaplot(mode, s1, n1, range, xrange, titlestr) if length(varargin) < 1, error('Not enough arguments.'); end if length(varargin) < 5, titlestr = '';else titlestr = varargin{5}; end if length(varargin) < 4, xrange = 0;else xrange = varargin{4}; end if length(varargin) < 3, range = 0;else range = varargin{3}; end if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end s1 = remmean(varargin{1}); range=chkrange(range, s1); xrange=chkxrange(xrange, range); n1=chkn(n1, s1); for i = 1:size(n1, 2) S1(i, :) = s1(n1(i), range); end alpha = mean(max(S1')-min(S1')); for i = 1:size(n1,2) S2(i,:) = S1(i,:) - alpha*(i-1)*ones(size(S1(1,:))); end plot(xrange, S2'); axis([min(xrange) max(xrange) min(min(S2)) max(max(S2)) ]); set(gca,'YTick',(-size(S1,1)+1)*alpha:alpha:0); set(gca,'YTicklabel',fliplr(n1)); if (~isempty(titlestr)) title(titlestr); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'histogram' % icaplot(mode, s1, n1, range, bins, style) if length(varargin) < 1, error('Not enough arguments.'); end if length(varargin) < 5, style = 'bar';else style = varargin{5}; end if length(varargin) < 4, bins = 10;else bins = varargin{4}; end if length(varargin) < 3, range = 0;else range = varargin{3}; end if length(varargin) < 2, n1 = 0;else n1 = varargin{2}; end s1 = varargin{1}; range = chkrange(range, s1); n1 = chkn(n1, s1); numSignals = size(n1, 2); rows = floor(sqrt(numSignals)); columns = ceil(sqrt(numSignals)); while (rows * columns < numSignals) columns = columns + 1; end switch style case {'', 'bar'} for i = 1:numSignals, subplot(rows, columns, i); hist(s1(n1(i), range), bins); title(int2str(n1(i))); drawnow; end case 'line' for i = 1:numSignals, subplot(rows, columns, i); [Y, X]=hist(s1(n1(i), range), bins); plot(X, Y); title(int2str(n1(i))); drawnow; end otherwise fprintf('Unknown style.\n') end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case 'scatter' % icaplot(mode, s1, n1, s2, n2, range, titlestr, xlabelstr, ylabelstr, markerstr) if length(varargin) < 4, error('Not enough arguments.'); end if length(varargin) < 9, markerstr = '.';else markerstr = varargin{9}; end if length(varargin) < 8, ylabelstr = 'Signal 2';else ylabelstr = varargin{8}; end if length(varargin) < 7, xlabelstr = 'Signal 1';else xlabelstr = varargin{7}; end if length(varargin) < 6, titlestr = '';else titlestr = varargin{6}; end if length(varargin) < 5, range = 0;else range = varargin{5}; end n2 = varargin{4}; s2 = varargin{3}; n1 = varargin{2}; s1 = varargin{1}; range = chkrange(range, s1); n1 = chkn(n1, s1); n2 = chkn(n2, s2); rows = size(n1, 2); columns = size(n2, 2); for r = 1:rows for c = 1:columns subplot(rows, columns, (r-1)*columns + c); plot(s1(n1(r), range),s2(n2(c), range),markerstr); if (~isempty(titlestr)) title(titlestr); end if (rows*columns == 1) xlabel(xlabelstr); ylabel(ylabelstr); else xlabel([xlabelstr ' (' int2str(n1(r)) ')']); ylabel([ylabelstr ' (' int2str(n2(c)) ')']); end drawnow; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% case {'compare', 'sum', 'sumerror'} % icaplot(mode, s1, n1, s2, n2, range, xrange, titlestr, s1label, s2label) if length(varargin) < 4, error('Not enough arguments.'); end if length(varargin) < 9, s2label = 'IC';else s2label = varargin{9}; end if length(varargin) < 8, s1label = 'Mix';else s1label = varargin{8}; end if length(varargin) < 7, titlestr = '';else titlestr = varargin{7}; end if length(varargin) < 6, xrange = 0;else xrange = varargin{6}; end if length(varargin) < 5, range = 0;else range = varargin{5}; end s1 = varargin{1}; n1 = varargin{2}; s2 = varargin{3}; n2 = varargin{4}; range = chkrange(range, s1); xrange = chkxrange(xrange, range); n1 = chkn(n1, s1); n2 = chkn(n2, s2); numSignals = size(n1, 2); if (numSignals > 1) externalLegend = 1; else externalLegend = 0; end rows = floor(sqrt(numSignals+externalLegend)); columns = ceil(sqrt(numSignals+externalLegend)); while (rows * columns < (numSignals+externalLegend)) columns = columns + 1; end clf; for j = 1:numSignals subplot(rows, columns, j); switch mode case 'compare' plotcompare(s1, n1(j), s2,n2, range, xrange); [legendtext,legendstyle]=legendcompare(n1(j),n2,s1label,s2label,externalLegend); case 'sum' plotsum(s1, n1(j), s2,n2, range, xrange); [legendtext,legendstyle]=legendsum(n1(j),n2,s1label,s2label,externalLegend); case 'sumerror' plotsumerror(s1, n1(j), s2,n2, range, xrange); [legendtext,legendstyle]=legendsumerror(n1(j),n2,s1label,s2label,externalLegend); end if externalLegend title([titlestr ' (' s1label ' ' int2str(n1(j)) ')']); else legend(char(legendtext)); if (~isempty(titlestr)) title(titlestr); end end end if (externalLegend) subplot(rows, columns, numSignals+1); legendsize = size(legendtext, 2); hold on; for i=1:legendsize plot([0 1],[legendsize-i legendsize-i], char(legendstyle(i))); text(1.5, legendsize-i, char(legendtext(i))); end hold off; axis([0 6 -1 legendsize]); axis off; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotcompare(s1, n1, s2, n2, range, xrange); style=getStyles; K = regress(s1(n1,:)',s2'); plot(xrange, s1(n1,range), char(style(1))); hold on for i=1:size(n2,2) plotstyle=char(style(i+1)); plot(xrange, K(n2(i))*s2(n2(i),range), plotstyle); end hold off function [legendText, legendStyle]=legendcompare(n1, n2, s1l, s2l, externalLegend); style=getStyles; if (externalLegend) legendText(1)={[s1l ' (see the titles)']}; else legendText(1)={[s1l ' ', int2str(n1)]}; end legendStyle(1)=style(1); for i=1:size(n2, 2) legendText(i+1) = {[s2l ' ' int2str(n2(i))]}; legendStyle(i+1) = style(i+1); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotsum(s1, n1, s2, n2, range, xrange); K = diag(regress(s1(n1,:)',s2')); sigsum = sum(K(:,n2)*s2(n2,:)); plot(xrange, s1(n1, range),'k-', ... xrange, sigsum(range), 'b-'); function [legendText, legendStyle]=legendsum(n1, n2, s1l, s2l, externalLegend); if (externalLegend) legendText(1)={[s1l ' (see the titles)']}; else legendText(1)={[s1l ' ', int2str(n1)]}; end legendText(2)={['Sum of ' s2l ': ', int2str(n2)]}; legendStyle={'k-';'b-'}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function plotsumerror(s1, n1, s2, n2, range, xrange); K = diag(regress(s1(n1,:)',s2')); sigsum = sum(K(:,n2)*s2(n2,:)); plot(xrange, s1(n1, range),'k-', ... xrange, sigsum(range), 'b-', ... xrange, s1(n1, range)-sigsum(range), 'r-'); function [legendText, legendStyle]=legendsumerror(n1, n2, s1l, s2l, externalLegend); if (externalLegend) legendText(1)={[s1l ' (see the titles)']}; else legendText(1)={[s1l ' ', int2str(n1)]}; end legendText(2)={['Sum of ' s2l ': ', int2str(n2)]}; legendText(3)={'"Error"'}; legendStyle={'k-';'b-';'r-'}; %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function style=getStyles; color = {'k','r','g','b','m','c','y'}; line = {'-',':','-.','--'}; for i = 0:size(line,2)-1 for j = 1:size(color, 2) style(j + i*size(color, 2)) = strcat(color(j), line(i+1)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function range=chkrange(r, s) if r == 0 range = 1:size(s, 2); else range = r; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function xrange=chkxrange(xr,r); if xr == 0 xrange = r; elseif size(xr, 2) == 2 xrange = xr(1):(xr(2)-xr(1))/(size(r,2)-1):xr(2); elseif size(xr, 2)~=size(r, 2) error('Xrange and range have different sizes.'); else xrange = xr; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function n=chkn(n,s) if n == 0 n = 1:size(s, 1); end
github
jacksky64/imageProcessing-master
PhaseResidues_r1.m
.m
imageProcessing-master/PhaseUnwrap2DGoldsteinAlgorithm/PhaseResidues_r1.m
2,399
utf_8
eb7ce76ac23d23d3a221874a6e9e7305
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PhaseResidues.m calculates the phase residues for a given wrapped phase % image. Note that by convention the positions of the phase residues are % marked on the top left corner of the 2 by 2 regions. % % active---res4---right % | | % res1 res3 % | | % below---res2---belowright % Phase residues with integer multiples of 2*pi are not accounted for, but % these rarely occur. % Created by B.S. Spottiswoode on 07/10/2004 % Last modified on 08/10/2004 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function residue_charge=PhaseResidues(IM_phase, IM_mask); [rows, cols]=size(IM_phase); %The code below is simply a vectorised representation of operations on 2 by 2 %blocks in the matrix IM_active = IM_phase; IM_below =zeros(rows,cols); IM_below(1:rows-1,:) = IM_phase(2:rows,:); % Shift up 1 pixel IM_right =zeros(rows,cols); IM_right(:,1:cols-1) = IM_phase(:,2:cols); % Shift left 1 pixel IM_belowright =zeros(rows,cols); IM_belowright(1:rows-1,1:cols-1) = IM_phase(2:rows,2:cols); % Shift up 1 pixel & left 1 pixel % Wrap the phase differences as we loop around the 2 by 2 blocks res1=mod(IM_active - IM_below + pi, 2*pi) - pi; % Up - Down (bottom row is unreliable) res2=mod(IM_below - IM_belowright + pi, 2*pi) - pi; % Left- Right, shifted up (bottom row & far-right column are unreliable) res3=mod(IM_belowright - IM_right + pi, 2*pi) - pi; % Down - Up, shifted left (bottom row & far-right column are unreliable) res4=mod(IM_right - IM_active + pi, 2*pi) - pi; % Right - Left, (far-right column is unreliable) temp_residues=res1+res2+res3+res4; %Sum the phase differences. Positive residues appear as 2*pi, negative as -2*pi. % Far-right column and bottom row are unreliable in temp_residues residues=(temp_residues>=6); %Assign 1 to positive residue (which should equal 2*pi) residues=residues - (temp_residues<=-6); %Assign -1 to negative residues (which should equal -2*pi) residues(:,cols)=0; residues(rows,:)=0; %Zero pad the border residues %residues(:,1)=0; residues(1,:)=0; % Not needed. Left column and top row are accurate residue_charge=residues; %residue_sum=sum(sum(abs(residues))) % DEBUG
github
jacksky64/imageProcessing-master
BranchCuts_r1.m
.m
imageProcessing-master/PhaseUnwrap2DGoldsteinAlgorithm/BranchCuts_r1.m
11,409
utf_8
3bf75332b143ddd255309404c5a6678e
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % BranchCuts.m generates branch cuts based on the phase residues. This is % done using the Goldstein method, as described in "Two-dimensional phase % unwrapping: theory, algorithms and software" by Dennis Ghiglia and % Mark Pritt. % "residue_charge" is a matrix wherein positive residues are 1 and % negative residues are 0. % "max_box_radius" defines the maximum search radius for the balancing of % residues. If this is too large, areas will be isolated by the branch % cuts. % "IM_mask" is a binary matrix. This serves as an artificial border for the % branch cuts to connect to. % Created by B.S. Spottiswoode on 15/10/2004 % Last modified on 18/10/2004 % 07/19/2010 Modified by Carey Smith % Corrected a NaN divide by zero problem % Return immediately, if no residues % Eliminated code Analyzer warnings about && vs. &, || vs. | % 2010/09/15 Match with residues of opposite sign. % Change the order of the loops: Put the radius loop on the outside, % to let each residue try to find its closest neighbor of opposite % sign. This generally finds closer pairs. % Use residue_charge_masked in place of residue_charge in some places. % Modified "for n" loop to just use the needed indices. % When making a branch cut to the edge, go straight, rather than diagonally. % Eliminated unnecessary sections of code & resulting unused variables. % Sped-up internal function "branch_cuts". % Added some error checks. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function branch_cuts=BranchCuts(residue_charge, max_box_radius, IM_mask) branch_cuts = ~IM_mask; %Define initial branch cuts borders as the mask. residue_charge_masked=residue_charge; residue_charge_masked(logical(~IM_mask))=0; %Remove all residues except those in the mask [rowres,colres] = find(residue_charge_masked~=0); %Find the coordinates of the residues if(isempty(rowres)); disp(['BranchCuts: No residues, length(rowres)=',int2str(length(rowres)),... '; sum(abs(residue_charge))=',int2str(sum(abs(residue_charge(:)))),... '; sum(abs(residue_charge_masked))=',int2str(sum(abs(residue_charge_masked(:))))]) return; end % no residues % Allocate spcae [rowdim, coldim] =size(residue_charge); residue_balanced =zeros(rowdim, coldim); %Initially designate all residues as unbalanced %disp('Calculating branch cuts ...'); %tic; n_residues = length(rowres); max_box_radius = min(max_box_radius,floor(length(residue_charge)/2)); for(radius=1:max_box_radius) % Loop thru box sizes %disp(['BranchCuts.m: radius=',num2str(radius)]) for i=1:n_residues; %Loop through the residues r_active=rowres(i); %Coordinates of the active residue c_active=colres(i); if(residue_balanced(r_active, c_active) > 0) % Already balanced, possibly by a preceeding residue? %disp(['i=',int2str(i),'; r_active=',int2str(r_active),'; c_active=',int2str(c_active),... % '; residue_charge=',int2str(residue_charge(r_active, c_active)),... % '; residue_charge_masked=',int2str(residue_charge_masked(r_active, c_active)),'; Already balanced or not in the mask']) continue; end if r_active<=1 || r_active>=rowdim || c_active<=1 || c_active>=coldim %Is this residue on the image border? branch_cuts(r_active, c_active)=1; % Make this point a branchcut to the edge residue_balanced(r_active, c_active) = 1; %Mark this residue as balanced %disp(['i=',int2str(i),'; r_active=',int2str(r_active),'; c_active=',int2str(c_active),'; residue_charge=',int2str(residue_charge(r_active, c_active)),'; edge residue, so balanced']) residue_charge_masked(r_active, c_active) = 0; % Remove from the set of unmatched residues continue; end charge_counter = residue_charge_masked(r_active, c_active); %Store the initial residue charge %disp(['i=',int2str(i),'; r_active=',int2str(r_active),'; c_active=',int2str(c_active),... % '; residue_charge=',int2str(residue_charge(r_active, c_active)),'; radius=',num2str(radius)]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %This portion of code serves to search the box perimeter, %place branch cuts, and keep track of the summed residue charge %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% m1 = max(r_active-radius,1); m2 = min(r_active+radius,rowdim); n1 = max(c_active-radius,1); n2 = min(c_active+radius,coldim); for m = m1:m2 %Coordinates of the box border pixels if(m==m1 || m==m2) %Ensure that only the border pixels are being tested ndel = 1; %Use all pixels in top & bottom rows else % Avoid re-testing pixels that have already been tested ndel = n2-n1; %Use only the end pixels in middle rows end for n = n1:ndel:n2 % Coordinates of only the box border pixels %disp([' m=',int2str(m),'; n=',int2str(n),... %'; residue_charge(m,n)=',int2str(residue_charge(m,n)),... %'; residue_charge_masked(m,n)=',int2str(residue_charge_masked(m,n)),... %'; IM_mask=',num2str(IM_mask(m,n),2),... %'; res_balanced=',int2str(residue_balanced(m,n))]) if (charge_counter~=0) % Not yet resolved if m<=1 || m>=rowdim %Is the current pixel on the image border? branch_cuts = PlaceBranchCutInternal(branch_cuts, r_active, c_active, m, c_active); %Place a branch cut between the active point and the mask border residue_balanced(r_active, c_active)=1; %Mark the centre residue as balanced %disp([' Balanced to a row edge, branch_cuts(',int2str(r_active),',',int2str(n),')=',int2str(branch_cuts(r_active, n))]) charge_counter=0; %Label the charge as balanced residue_charge_masked(r_active, c_active) = 0; % Remove from the set of unmatched residues residue_charge_masked(r_active, n) = 0; % Remove from the set of unmatched residues break; elseif n<=1 || n>=coldim %Is the current pixel on the image border? branch_cuts = PlaceBranchCutInternal(branch_cuts, r_active, c_active, r_active, n); %Place a branch cut between the active point and the nearest mask border residue_balanced(r_active, c_active)=1; %Mark the centre residue as balanced %disp([' Balanced to a col edge']) charge_counter=0; %Label the charge as balanced residue_charge_masked(r_active, c_active) = 0; % Remove from the set of unmatched residues residue_charge_masked(m, c_active) = 0; % Remove from the set of unmatched residues break; % Logic to connect positive residues to negative residues. elseif(residue_charge_masked(r_active, c_active) * residue_charge_masked(m,n) == -1) % Is the current pixel a residue of opposite sign? branch_cuts = PlaceBranchCutInternal(branch_cuts, r_active, c_active, m, n); %Place a branch cut regardless of the charge_counter value %disp([' m=',int2str(m),'; n=',int2str(n),'; residue_charge_masked(m,n)=',int2str(residue_charge_masked(m,n)),'charge_counter=',int2str(charge_counter),', so balanced']) charge_counter=0; %Label the charge as balanced residue_balanced(r_active, c_active)=1; %Mark the centre (active) residue as balanced residue_balanced(m, n) =1; %Mark the end-pt. residue as balanced residue_charge_masked(r_active, c_active) = 0; % Remove from the set of unmatched residues residue_charge_masked(m, n) = 0; % Remove from the set of unmatched residues break; %else % disp([' m=',int2str(m),'; n=',int2str(n),'; residue_charge=',int2str(residue_charge(m,n)),... % '; residue_charge_masked(m,n)=',int2str(residue_charge_masked(m,n)),'; charge_counter=',int2str(charge_counter),';not yet balanced']) end % if [m<=1 || m>=rowdim || n<=1 || n>=coldim]; elseif(residue_charge_masked(r_active, c_active) * residue_charge_masked(m,n) == -1) end % if charge_counter~=0 if(charge_counter==0); break; end; end % for n if(charge_counter==0); break; end; end % for m end % for i=1:n_residues %disp([' sum(residue_balanced(:))=',int2str(sum(residue_balanced(:)))]) if(sum(residue_balanced(:)) >= n_residues) % are all of the residues balanced? break; end end % for(radius=1:floor(length(residue_charge)/2)) %t=toc; %disp(['Branch cut operation completed in ',int2str(t),' seconds.']); %disp(['Residues: total= ',int2str(n_residues),', accounted= ',int2str(sum(residue_balanced(:))),', unaccounted= ',int2str(n_residues-sum(residue_balanced(:)))]) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % PlaceBranchCutInternal.m places a branch cut between the points [r1, c1] and % [r2, c2]. The matrix branch_cuts is binary, with 1's depicting a % branch cut. % % 2010/09/15 Carey Smith Changed atan() to atan2() & reduced to one "for loop" % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% function branch_cuts = PlaceBranchCutInternal(branch_cuts, r1, c1, r2, c2) branch_cuts(r1,c1)=1; %Fill the starting points branch_cuts(r2,c2)=1; %Fill the ending points radius=sqrt((r2-r1)^2 + (c2-c1)^2); %Distance between points warning off MATLAB:divideByZero; %This warning has been removed from MATLAB 2010 %theta=atan2((c2-c1),(r2-r1)); % CS: atan2() gives the full line angle (=/-pi), % % so, we need just one "for" loop %cos_theta = cos(theta) % CS: Compute once, outside the for loop %sin_theta = sin(theta) % CS: Compute once, outside the for loop % Compute cos & sin by trig, w/out computing the angle dist = sqrt((c2-c1)^2 + (r2-r1)^2); cos_theta = (r2-r1)/dist; % CS: Compute once, outside the for loop sin_theta = (c2-c1)/dist; % CS: Compute once, outside the for loop for i=1:radius %Number of points to fill in r_fill=r1 + round(i*cos_theta); c_fill=c1 + round(i*sin_theta); if(c_fill==0) error(['PlaceBranchCutInternal:invalid_c',' c_fill==0',... '; r1=',int2str(r1),'; r2=',int2str(r2),'; c1=',int2str(c1),'; c2=',int2str(c2),... '; i=',int2str(i),'; cos_theta=',num2str(cos_theta,4),'; sin_theta=',num2str(sin_theta,4)]) end if(r_fill==0) error(['PlaceBranchCutInternal:invalid_r',' r_fill==0',... '; r1=',int2str(r1),'; r2=',int2str(r2),'; c1=',int2str(c1),'; c2=',int2str(c2),... '; i=',int2str(i),'; cos_theta=',num2str(cos_theta,4),'; sin_theta=',num2str(sin_theta,4)]) end branch_cuts(r_fill, c_fill) = 1; end return;
github
jacksky64/imageProcessing-master
phasesym.m
.m
imageProcessing-master/GaborImageFeatures/phasesym.m
22,009
utf_8
c73a0499c75e8bb7cf10646e82e2a928
% PHASESYM - Function for computing gabor features of a gray-scale image % % This function calculates gabor features. Mean-squared energy & meanAmplitude % for each scale % and orientation is returned. % % There are potentially many arguments, here is the full usage: % % [gaborSquareEnergy, gaborMeanAmplitude] = ... % phasesym(im, nscale, norient ) %NOTE: nscale & norient are optional arguments % % However, apart from the image, all parameters have defaults and the % usage can be as simple as: % % [gaborSquareEnergy, gaborMeanAmplitude ]= phasesym(im); % % Arguments: % Default values Description % % nscale 5 - Number of wavelet scales, try values 3-6 % norient 6 - Number of filter orientations. % % Return values: % msEnergy - Mean square energy % orientation - Mean amplitude % % The convolutions are done via the FFT. Many of the parameters relate to the % specification of the filters in the frequency plane. The values do not seem % to be very critical and the defaults are usually fine. You may want to % experiment with the values of 'nscales' and 'k', the noise compensation factor. % % % For maximum speed the input image should have dimensions that correspond to % powers of 2, but the code will operate on images of arbitrary size. % % See Also: PHASECONG, PHASECONG2, GABORCONVOLVE, PLOTGABORFILTERS % References: % Peter Kovesi, "Symmetry and Asymmetry From Local Phase" AI'97, Tenth % Australian Joint Conference on Artificial Intelligence. 2 - 4 December % 1997. http://www.cs.uwa.edu.au/pub/robvis/papers/pk/ai97.ps.gz. % % Peter Kovesi, "Image Features From Phase Congruency". Videre: A % Journal of Computer Vision Research. MIT Press. Volume 1, Number 3, % Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html % % Kuse, Manohar, Yi-Fang Wang, Vinay Kalasannavar, Michael Khan, and Nasir Rajpoot. % "Local isotropic phase symmetry measure for detection of beta cells and lymphocytes." % Journal of Pathology Informatics 2 (2011). % % Naik, S., et al. Automated gland and nuclei segmentation for grading of prostate and breast % cancer histopathology. in IEEE International Symposium on Biomedical Imaging (ISBI). 2008. % IEEE. % % April 1996 Original Version written % August 1998 Noise compensation corrected. % October 1998 Noise compensation corrected. - Again!!! % September 1999 Modified to operate on non-square images of arbitrary size. % February 2001 Specialised from phasecong.m to calculate phase symmetry % July 2005 Better argument handling + general cleanup and speed improvements % August 2005 Made Octave compatible. % January 2007 Small correction and cleanup of radius calculation for odd % image sizes. % May 2011 Modified by manohar kuse to for compuation of Isotropic Phase Symmetry % Oct 2012 Modified by manohar kuse to for computation of sqare energy and mean amplitude gabor features % Copyright (c) 2011-2012 Manohar Kuse % European Center for Nuclear Reseach % CERN, Geneva, Switzerland % http://cern.ch/mkuse % Copyright (c) 1996-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % The software is provided "as is", without warranty of any kind. function[gaborSquareEnergy, gaborMeanAmplitude] = phasesym(varargin) % Get arguments and/or default values [im, nscale, norient, minWaveLength, mult, sigmaOnf, dThetaOnSigma,k, ... polarity] = checkargs(varargin(:)); v = version; Octave = v(1)<'5'; % Crude Octave test epsilon = .0001; % Used to prevent division by zero. % Calculate the standard deviation of the angular Gaussian function % used to construct filters in the frequency plane. thetaSigma = pi/norient/dThetaOnSigma; [rows,cols] = size(im); imagefft = fft2(im); % Fourier transform of image zero = zeros(rows,cols); totalEnergy = zero; % Matrix for accumulating weighted phase % congruency values (energy). totalSumAn = zero; % Matrix for accumulating filter response % amplitude values. orientation = zero; % Matrix storing orientation with greatest % energy for each pixel. estMeanE2n = []; EO = cell(nscale, norient); % Cell array of convolution results ifftFilterArray = cell(1, nscale); % Cell array of inverse FFTs of filters % Pre-compute some stuff to speed up filter construction % Set up X and Y matrices with ranges normalised to +/- 0.5 % The following code adjusts things appropriately for odd and even values % of rows and columns. if mod(cols,2) xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1); else xrange = [-cols/2:(cols/2-1)]/cols; end if mod(rows,2) yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1); else yrange = [-rows/2:(rows/2-1)]/rows; end [x,y] = meshgrid(xrange, yrange); radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre. theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) radius = ifftshift(radius); % Quadrant shift radius and theta so that filters theta = ifftshift(theta); % are constructed with 0 frequency at the corners. radius(1,1) = 1; % Get rid of the 0 radius value at the 0 % frequency point (now at top-left corner) % so that taking the log of the radius will % not cause trouble. sintheta = sin(theta); costheta = cos(theta); clear x; clear y; clear theta; % save a little memory % Filters are constructed in terms of two components. % 1) The radial component, which controls the frequency band that the filter % responds to % 2) The angular component, which controls the orientation that the filter % responds to. % The two components are multiplied together to construct the overall filter. % Construct the radial filter components... % First construct a low-pass filter that is as large as possible, yet falls % away to zero at the boundaries. All log Gabor filters are multiplied by % this to ensure no extra frequencies at the 'corners' of the FFT are % incorporated as this seems to upset the normalisation process when % calculating phase congrunecy. lp = lowpassfilter([rows,cols],.4,10); % Radius .4, 'sharpness' 10 logGabor = cell(1,nscale); for s = 1:nscale wavelength = minWaveLength*mult^(s-1); fo = 1.0/wavelength; % Centre frequency of filter. logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter % back to zero (undo the radius fudge). end % Then construct the angular filter components... spread = cell(1,norient); for o = 1:norient angl = (o-1)*pi/norient; % Filter angle. % For each point in the filter matrix calculate the angular distance from % the specified filter orientation. To overcome the angular wrap-around % problem sine difference and cosine difference values are first computed % and then the atan2 function is used to determine angular distance. ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine. dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread{o} = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the % angular filter component. end count=1; gaborSquareEnergy=[]; gaborMeanAmplitude=[]; % The main loop... for o = 1:norient, % For each orientation. fprintf('Processing orientation %d \r', o); if Octave fflush(1); end sumAn_ThisOrient = zero; Energy_ThisOrient = zero; for s = 1:nscale, % For each scale. filter = logGabor{s} .* spread{o}; % Multiply radial and angular % components to get filter. ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power ifftFilterArray{s} = ifftFilt; % record ifft2 of filter % Convolve image with even and odd filters returning the result in EO EO{s,o} = ifft2(imagefft .* filter); An = abs(EO{s,o}); % Amplitude of even & odd filter response. sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses. % % % %%% Code by Manohar Kuse % % Display of individual components % if o == 6 % figure, imagesc( An ), colormap(gray), title( sprintf( 'orient : %d, scale : %d', o,s) ); % imwrite( An, sprintf( 'orient/%d/%d.png', o,s ) ); % new changes on 20th oct 2012. [email protected] for computation of Gabor features gaborSquareEnergy(count) = sum(sum( An.^2 ) ); gaborMeanAmplitude(count) = mean2( An ); count = count + 1; %end of changes by [email protected] % end % % % %%% End of code by manohar % % if s==1 EM_n = sum(sum(filter.^2)); % Record mean squared filter value at smallest end % scale. This is used for noise estimation. end % ... and process the next scale % code by manohar kuse to calculate the phase symmetry measure. if polarity == 0 % look for 'white' and 'black' spots for s = 1:nscale, Energy_ThisOrient = Energy_ThisOrient ... + abs(real(EO{s,o})) - abs(imag(EO{s,o})); end elseif polarity == 1 % Just look for 'white' spots for s = 1:nscale, Energy_ThisOrient = Energy_ThisOrient ... + real(EO{s,o}) - abs(imag(EO{s,o})); end elseif polarity == -1 % Just look for 'black' spots for s = 1:nscale, Energy_ThisOrient = Energy_ThisOrient ... - real(EO{s,o}) - abs(imag(EO{s,o})); end end % Compensate for noise % We estimate the noise power from the energy squared response at the % smallest scale. If the noise is Gaussian the energy squared will % have a Chi-squared 2DOF pdf. We calculate the median energy squared % response as this is a robust statistic. From this we estimate the % mean. The estimate of noise power is obtained by dividing the mean % squared energy value by the mean squared filter value medianE2n = median(reshape(abs(EO{1,o}).^2,1,rows*cols)); meanE2n = -medianE2n/log(0.5); estMeanE2n = [estMeanE2n meanE2n]; noisePower = meanE2n/EM_n; % Estimate of noise power. % Now estimate the total energy^2 due to noise % Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj)) EstSumAn2 = zero; for s = 1:nscale EstSumAn2 = EstSumAn2+ifftFilterArray{s}.^2; end EstSumAiAj = zero; for si = 1:(nscale-1) for sj = (si+1):nscale EstSumAiAj = EstSumAiAj + ifftFilterArray{si}.*ifftFilterArray{sj}; end end EstNoiseEnergy2 = 2*noisePower*sum(sum(EstSumAn2)) + 4*noisePower*sum(sum(EstSumAiAj)); tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 ); T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold % The estimated noise effect calculated above is only valid for the PC_1 % measure. The PC_2 measure does not lend itself readily to the same % analysis. However empirically it seems that the noise effect is % overestimated roughly by a factor of 1.7 for the filter parameters % used here. T = T/1.7; % Apply noise threshold Energy_ThisOrient = max(Energy_ThisOrient - T, zero); % Update accumulator matrix for sumAn and totalEnergy totalSumAn = totalSumAn + sumAn_ThisOrient; totalEnergy = totalEnergy + Energy_ThisOrient; % Update orientation matrix by finding image points where the energy in % this orientation is greater than in any previous orientation (the % change matrix) and then replacing these elements in the orientation % matrix with the current orientation number. if(o == 1), maxEnergy = Energy_ThisOrient; else change = Energy_ThisOrient > maxEnergy; orientation = (o - 1).*change + orientation.*(~change); maxEnergy = max(maxEnergy, Energy_ThisOrient); end end % For each orientation fprintf(' \r'); display( 'Code By Manohar for <Variation in Phase Symetry> Starts' ); % % Code By Manohar Kuse % Desc: % We are trying out a variant of phase symetry. Our measure of symetry % is average across all orientations and scales, instead of normal % addition. This was done so that, maximas in particular direction only % could be eliminated. Also, the obervation was that a cell-center % point would be symetric in all direction and a high value in all % direction. averageDirectionalEnergy = zero; % for s=1:nscale % for o=1:norient % averageDirectionalEnergy = averageDirectionalEnergy + abs(EO{s,o}); % end % end % averageDirectionalEnergy = averageDirectionalEnergy / (nscale * norient ); % % % Computing median image % median is computed over orientations. which means for a % particular scale orientation is varied to take the median for sc = 1:nscale clear XA; clear XE; display( sprintf( 'Taking Median for scale %d/%d', sc, nscale ) ); scale_current = sc; % for a fixed scale, iterate thru each orientation for ori=1:norient XA(:,:,ori) = abs( EO{scale_current,ori} ); XE(:,:,ori) = abs( real(EO{scale_current,ori}) ) - abs( imag(EO{scale_current,ori}) ); end % % % Basic Approach %mA(:,:,scale_current) = median( XA, 3 ); %mE(:,:,scale_current) = median( XE, 3 ); % % % Approach for optimization. 3d array reshaped to 2d appr_r_XA = reshape( XA, [ size(XA,1)*size(XA,2) norient ] ); appr_r_median_XA = median( appr_r_XA, 2 ); mA = reshape( appr_r_median_XA, [size(XA,1) size(XA,2) ] ); appr_r_XE = reshape( XE, [ size(XE,1)*size(XE,2) norient ] ); appr_r_median_XE = median( appr_r_XE, 2 ); mE = reshape( appr_r_median_XE, [size(XE,1) size(XE,2) ] ); % figure,imagesc( tmp ) % colormap(gray), title( sprintf( 'scale : %d', sc ) ); end A = sum( mA, 3 ); E = sum( mE, 3 ); averageDirectionalEnergy = E ./ (A + epsilon); % for ori=1:norient % clear XP; % % for a fixed scale, iterate thru each orientation % for sc = 1:nscale % scale_current = sc; % XP(:,:,sc) = abs( EO{scale_current,ori} ); % end % % tmp= median( XP, 3 ); % %rel(:,:,scale_current) % % figure,imagesc( tmp ) % colormap(gray), title( sprintf( 'orientation : %d', ori ) ); % end display( 'Code End by Manohar' ); % % End of code by Manohar Kuse % % disp('Mean Energy squared values recorded with smallest scale filter at each orientation'); % disp(estMeanE2n); % Normalize totalEnergy by the totalSumAn to obtain phase symmetry phaseSym = totalEnergy ./ (totalSumAn + epsilon); % Convert orientation matrix values to degrees orientation = orientation * (180 / norient); %------------------------------------------------------------------ % CHECKARGS % % Function to process the arguments that have been supplied, assign % default values as needed and perform basic checks. function [im, nscale, norient, minWaveLength, mult, sigmaOnf, ... dThetaOnSigma,k, polarity] = checkargs(arg); nargs = length(arg); if nargs < 1 error('No image supplied as an argument'); end % Set up default values for all arguments and then overwrite them % with with any new values that may be supplied im = []; nscale = 5; % Number of wavelet scales. norient = 6; % Number of filter orientations. minWaveLength = 3; % Wavelength of smallest scale filter. mult = 2.1; % Scaling factor between successive filters. sigmaOnf = 0.55; % Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's % transfer function in the frequency domain % to the filter center frequency. dThetaOnSigma = 1.2; % Ratio of angular interval between filter orientations % and the standard deviation of the angular Gaussian % function used to construct filters in the % freq. plane. k = 2.0; % No of standard deviations of the noise % energy beyond the mean at which we set the % noise threshold point. polarity = 0; % Look for both black and white spots of symmetrry % Allowed argument reading states allnumeric = 1; % Numeric argument values in predefined order keywordvalue = 2; % Arguments in the form of string keyword % followed by numeric value readstate = allnumeric; % Start in the allnumeric state if readstate == allnumeric for n = 1:nargs if isa(arg{n},'char') readstate = keywordvalue; break; else if n == 1, im = arg{n}; elseif n == 2, nscale = arg{n}; elseif n == 3, norient = arg{n}; elseif n == 4, minWaveLength = arg{n}; elseif n == 5, mult = arg{n}; elseif n == 6, sigmaOnf = arg{n}; elseif n == 7, dThetaOnSigma = arg{n}; elseif n == 8, k = arg{n}; elseif n == 9, polarity = arg{n}; end end end end % Code to handle parameter name - value pairs if readstate == keywordvalue while n < nargs if ~isa(arg{n},'char') | ~isa(arg{n+1}, 'double') error('There should be a parameter name - value pair'); end if strncmpi(arg{n},'im' ,2), im = arg{n+1}; elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1}; elseif strncmpi(arg{n},'norient' ,2), norient = arg{n+1}; elseif strncmpi(arg{n},'minWaveLength',2), minWavelength = arg{n+1}; elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1}; elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1}; elseif strncmpi(arg{n},'dthetaOnSigma',2), dThetaOnSigma = arg{n+1}; elseif strncmpi(arg{n},'k' ,1), k = arg{n+1}; elseif strncmpi(arg{n},'polarity',2), polarity = arg{n+1}; else error('Unrecognised parameter name'); end n = n+2; if n == nargs error('Unmatched parameter name - value pair'); end end end if isempty(im) error('No image argument supplied'); end if ~isa(im, 'double') im = double(im); end if nscale < 1 error('nscale must be an integer >= 1'); end if norient < 1 error('norient must be an integer >= 1'); end if minWaveLength < 2 error('It makes little sense to have a wavelength < 2'); end if polarity ~= -1 & polarity ~= 0 & polarity ~= 1 error('Allowed polarity values are -1, 0 and 1') end
github
jacksky64/imageProcessing-master
phasecong2.m
.m
imageProcessing-master/GaborImageFeatures/phasecong2.m
23,023
utf_8
62cee80b9df326d89f0ffb2008658303
% PHASECONG2 - Computes edge and corner phase congruency in an image. % % This function calculates the PC_2 measure of phase congruency. % This function supersedes PHASECONG % % There are potentially many arguments, here is the full usage: % % [M m or ft pc EO] = phasecong2(im, nscale, norient, minWaveLength, ... % mult, sigmaOnf, dThetaOnSigma, k, cutOff, g) % % However, apart from the image, all parameters have defaults and the % usage can be as simple as: % % M = phasecong2(im); % % Arguments: % Default values Description % % nscale 4 - Number of wavelet scales, try values 3-6 % norient 6 - Number of filter orientations. % minWaveLength 3 - Wavelength of smallest scale filter. % mult 2.1 - Scaling factor between successive filters. % sigmaOnf 0.55 - Ratio of the standard deviation of the Gaussian % describing the log Gabor filter's transfer function % in the frequency domain to the filter center frequency. % dThetaOnSigma 1.2 - Ratio of angular interval between filter orientations % and the standard deviation of the angular Gaussian % function used to construct filters in the % freq. plane. % k 2.0 - No of standard deviations of the noise energy beyond % the mean at which we set the noise threshold point. % You may want to vary this up to a value of 10 or % 20 for noisy images % cutOff 0.5 - The fractional measure of frequency spread % below which phase congruency values get penalized. % g 10 - Controls the sharpness of the transition in % the sigmoid function used to weight phase % congruency for frequency spread. % % Returned values: % M - Maximum moment of phase congruency covariance. % This is used as a indicator of edge strength. % m - Minimum moment of phase congruency covariance. % This is used as a indicator of corner strength. % or - Orientation image in integer degrees 0-180, % positive anticlockwise. % 0 corresponds to a vertical edge, 90 is horizontal. % ft - *Not correctly implemented at this stage* % A complex valued image giving the weighted mean % phase angle at every point in the image for each % orientation. % pc - Cell array of phase congruency images (values between 0 and 1) % for each orientation % EO - A 2D cell array of complex valued convolution results % % EO{s,o} = convolution result for scale s and orientation o. The real part % is the result of convolving with the even symmetric filter, the imaginary % part is the result from convolution with the odd symmetric filter. % % Hence: % abs(EO{s,o}) returns the magnitude of the convolution over the % image at scale s and orientation o. % angle(EO{s,o}) returns the phase angles. % % Notes on specifying parameters: % % The parameters can be specified as a full list eg. % >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3, 2.5, 0.55, 1.2, 2.0, 0.4, 10); % % or as a partial list with unspecified parameters taking on default values % >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3); % % or as a partial list of parameters followed by some parameters specified via a % keyword-value pair, remaining parameters are set to defaults, for example: % >> [M m or ft pc EO] = phasecong2(im, 5, 6, 3, 'cutOff', 0.3, 'k', 2.5); % % The convolutions are done via the FFT. Many of the parameters relate to the % specification of the filters in the frequency plane. The values do not seem % to be very critical and the defaults are usually fine. You may want to % experiment with the values of 'nscales' and 'k', the noise compensation factor. % % Notes on filter settings to obtain even coverage of the spectrum % dthetaOnSigma 1.2 norient 6 % sigmaOnf .85 mult 1.3 % sigmaOnf .75 mult 1.6 (filter bandwidth ~1 octave) % sigmaOnf .65 mult 2.1 % sigmaOnf .55 mult 3 (filter bandwidth ~2 octaves) % % For maximum speed the input image should have dimensions that correspond to % powers of 2, but the code will operate on images of arbitrary size. % % See Also: PHASECONG, PHASESYM, GABORCONVOLVE, PLOTGABORFILTERS % References: % % Peter Kovesi, "Image Features From Phase Congruency". Videre: A % Journal of Computer Vision Research. MIT Press. Volume 1, Number 3, % Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html % % Peter Kovesi, "Phase Congruency Detects Corners and % Edges". Proceedings DICTA 2003, Sydney Dec 10-12 % April 1996 Original Version written % August 1998 Noise compensation corrected. % October 1998 Noise compensation corrected. - Again!!! % September 1999 Modified to operate on non-square images of arbitrary size. % May 2001 Modified to return feature type image. % July 2003 Altered to calculate 'corner' points. % October 2003 Speed improvements and refinements. % July 2005 Better argument handling, changed order of return values % August 2005 Made Octave compatible % May 2006 Bug in checkargs fixed % Jan 2007 Bug in setting radius to 0 for odd sized images fixed. % Copyright (c) 1996-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in all % copies or substantial portions of the Software. % % The software is provided "as is", without warranty of any kind. function [M, m, or, featType, PC, EO]=phasecong2(varargin) % Get arguments and/or default values [im, nscale, norient, minWaveLength, mult, sigmaOnf, ... dThetaOnSigma,k, cutOff, g] = checkargs(varargin(:)); v = version; Octave = v(1)<'5'; % Crude Octave test epsilon = .0001; % Used to prevent division by zero. thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the % angular Gaussian function used to % construct filters in the freq. plane. [rows,cols] = size(im); imagefft = fft2(im); % Fourier transform of image zero = zeros(rows,cols); totalEnergy = zero; % Total weighted phase congruency values (energy). totalSumAn = zero; % Total filter response amplitude values. orientation = zero; % Matrix storing orientation with greatest % energy for each pixel. EO = cell(nscale, norient); % Array of convolution results. covx2 = zero; % Matrices for covariance data covy2 = zero; covxy = zero; estMeanE2n = []; ifftFilterArray = cell(1,nscale); % Array of inverse FFTs of filters % Pre-compute some stuff to speed up filter construction % Set up X and Y matrices with ranges normalised to +/- 0.5 % The following code adjusts things appropriately for odd and even values % of rows and columns. if mod(cols,2) xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1); else xrange = [-cols/2:(cols/2-1)]/cols; end if mod(rows,2) yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1); else yrange = [-rows/2:(rows/2-1)]/rows; end [x,y] = meshgrid(xrange, yrange); radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre. theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) radius = ifftshift(radius); % Quadrant shift radius and theta so that filters theta = ifftshift(theta); % are constructed with 0 frequency at the corners. radius(1,1) = 1; % Get rid of the 0 radius value at the 0 % frequency point (now at top-left corner) % so that taking the log of the radius will % not cause trouble. sintheta = sin(theta); costheta = cos(theta); clear x; clear y; clear theta; % save a little memory % Filters are constructed in terms of two components. % 1) The radial component, which controls the frequency band that the filter % responds to % 2) The angular component, which controls the orientation that the filter % responds to. % The two components are multiplied together to construct the overall filter. % Construct the radial filter components... % First construct a low-pass filter that is as large as possible, yet falls % away to zero at the boundaries. All log Gabor filters are multiplied by % this to ensure no extra frequencies at the 'corners' of the FFT are % incorporated as this seems to upset the normalisation process when % calculating phase congrunecy. lp = lowpassfilter([rows,cols],.45,15); % Radius .45, 'sharpness' 15 logGabor = cell(1,nscale); for s = 1:nscale wavelength = minWaveLength*mult^(s-1); fo = 1.0/wavelength; % Centre frequency of filter. logGabor{s} = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); logGabor{s} = logGabor{s}.*lp; % Apply low-pass filter logGabor{s}(1,1) = 0; % Set the value at the 0 frequency point of the filter % back to zero (undo the radius fudge). end % Then construct the angular filter components... spread = cell(1,norient); for o = 1:norient angl = (o-1)*pi/norient; % Filter angle. % For each point in the filter matrix calculate the angular distance from % the specified filter orientation. To overcome the angular wrap-around % problem sine difference and cosine difference values are first computed % and then the atan2 function is used to determine angular distance. ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine. dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread{o} = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the % angular filter component. end % The main loop... for o = 1:norient % For each orientation. fprintf('Processing orientation %d\r',o); if Octave fflush(1); end angl = (o-1)*pi/norient; % Filter angle. sumE_ThisOrient = zero; % Initialize accumulator matrices. sumO_ThisOrient = zero; sumAn_ThisOrient = zero; Energy = zero; for s = 1:nscale, % For each scale. filter = logGabor{s} .* spread{o}; % Multiply radial and angular % components to get the filter. % if o == 1 % accumulate filter info for noise compensation (nominally the same % for all orientations, hence it is only done once) ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power ifftFilterArray{s} = ifftFilt; % record ifft2 of filter % end % Convolve image with even and odd filters returning the result in EO EO{s,o} = ifft2(imagefft .* filter); An = abs(EO{s,o}); % Amplitude of even & odd filter response. sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses. sumE_ThisOrient = sumE_ThisOrient + real(EO{s,o}); % Sum of even filter convolution results. sumO_ThisOrient = sumO_ThisOrient + imag(EO{s,o}); % Sum of odd filter convolution results. if s==1 % Record mean squared filter value at smallest EM_n = sum(sum(filter.^2)); % scale. This is used for noise estimation. maxAn = An; % Record the maximum An over all scales. else maxAn = max(maxAn, An); end end % ... and process the next scale % Get weighted mean filter response vector, this gives the weighted mean % phase angle. XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon; MeanE = sumE_ThisOrient ./ XEnergy; MeanO = sumO_ThisOrient ./ XEnergy; % Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by % using dot and cross products between the weighted mean filter response % vector and the individual filter response vectors at each scale. This % quantity is phase congruency multiplied by An, which we call energy. for s = 1:nscale, E = real(EO{s,o}); O = imag(EO{s,o}); % Extract even and odd % convolution results. Energy = Energy + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE); end % Compensate for noise % We estimate the noise power from the energy squared response at the % smallest scale. If the noise is Gaussian the energy squared will have a % Chi-squared 2DOF pdf. We calculate the median energy squared response % as this is a robust statistic. From this we estimate the mean. % The estimate of noise power is obtained by dividing the mean squared % energy value by the mean squared filter value medianE2n = median(reshape(abs(EO{1,o}).^2,1,rows*cols)); meanE2n = -medianE2n/log(0.5); estMeanE2n(o) = meanE2n; noisePower = meanE2n/EM_n; % Estimate of noise power. % if o == 1 % Now estimate the total energy^2 due to noise % Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj)) EstSumAn2 = zero; for s = 1:nscale EstSumAn2 = EstSumAn2 + ifftFilterArray{s}.^2; end EstSumAiAj = zero; for si = 1:(nscale-1) for sj = (si+1):nscale EstSumAiAj = EstSumAiAj + ifftFilterArray{si}.*ifftFilterArray{sj}; end end sumEstSumAn2 = sum(sum(EstSumAn2)); sumEstSumAiAj = sum(sum(EstSumAiAj)); % end % if o == 1 EstNoiseEnergy2 = 2*noisePower*sumEstSumAn2 + 4*noisePower*sumEstSumAiAj; tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 ); T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold % The estimated noise effect calculated above is only valid for the PC_1 measure. % The PC_2 measure does not lend itself readily to the same analysis. However % empirically it seems that the noise effect is overestimated roughly by a factor % of 1.7 for the filter parameters used here. T = T/1.7; % Empirical rescaling of the estimated noise effect to % suit the PC_2 phase congruency measure Energy = max(Energy - T, zero); % Apply noise threshold % Form weighting that penalizes frequency distributions that are % particularly narrow. Calculate fractional 'width' of the frequencies % present by taking the sum of the filter response amplitudes and dividing % by the maximum amplitude at each point on the image. width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale; % Now calculate the sigmoidal weighting function for this orientation. weight = 1.0 ./ (1 + exp( (cutOff - width)*g)); % Apply weighting to energy and then calculate phase congruency PC{o} = weight.*Energy./sumAn_ThisOrient; % Phase congruency for this orientation featType{o} = E+i*O; % Build up covariance data for every point covx = PC{o}*cos(angl); covy = PC{o}*sin(angl); covx2 = covx2 + covx.^2; covy2 = covy2 + covy.^2; covxy = covxy + covx.*covy; end % For each orientation fprintf(' \r'); % Edge and Corner calculations % The following is optimised code to calculate principal vector % of the phase congruency covariance data and to calculate % the minimumum and maximum moments - these correspond to % the singular values. % First normalise covariance values by the number of orientations/2 covx2 = covx2/(norient/2); covy2 = covy2/(norient/2); covxy = covxy/norient; % This gives us 2*covxy/(norient/2) denom = sqrt(covxy.^2 + (covx2-covy2).^2)+epsilon; sin2theta = covxy./denom; cos2theta = (covx2-covy2)./denom; or = atan2(sin2theta,cos2theta)/2; % Orientation perpendicular to edge. or = round(or*180/pi); % Return result rounded to integer % degrees. neg = or < 0; or = ~neg.*or + neg.*(or+180); % Adjust range from -90 to 90 % to 0 to 180. M = (covy2+covx2 + denom)/2; % Maximum moment m = (covy2+covx2 - denom)/2; % ... and minimum moment %------------------------------------------------------------------ % CHECKARGS % % Function to process the arguments that have been supplied, assign % default values as needed and perform basic checks. function [im, nscale, norient, minWaveLength, mult, sigmaOnf, ... dThetaOnSigma,k, cutOff, g] = checkargs(arg); nargs = length(arg); if nargs < 1 error('No image supplied as an argument'); end % Set up default values for all arguments and then overwrite them % with with any new values that may be supplied im = []; nscale = 4; % Number of wavelet scales. norient = 6; % Number of filter orientations. minWaveLength = 3; % Wavelength of smallest scale filter. mult = 2.1; % Scaling factor between successive filters. sigmaOnf = 0.55; % Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's % transfer function in the frequency domain % to the filter center frequency. dThetaOnSigma = 1.2; % Ratio of angular interval between filter orientations % and the standard deviation of the angular Gaussian % function used to construct filters in the % freq. plane. k = 2.0; % No of standard deviations of the noise % energy beyond the mean at which we set the % noise threshold point. cutOff = 0.5; % The fractional measure of frequency spread % below which phase congruency values get penalized. g = 10; % Controls the sharpness of the transition in % the sigmoid function used to weight phase % congruency for frequency spread. % Allowed argument reading states allnumeric = 1; % Numeric argument values in predefined order keywordvalue = 2; % Arguments in the form of string keyword % followed by numeric value readstate = allnumeric; % Start in the allnumeric state if readstate == allnumeric for n = 1:nargs if isa(arg{n},'char') readstate = keywordvalue; break; else if n == 1, im = arg{n}; elseif n == 2, nscale = arg{n}; elseif n == 3, norient = arg{n}; elseif n == 4, minWaveLength = arg{n}; elseif n == 5, mult = arg{n}; elseif n == 6, sigmaOnf = arg{n}; elseif n == 7, dThetaOnSigma = arg{n}; elseif n == 8, k = arg{n}; elseif n == 9, cutOff = arg{n}; elseif n == 10,g = arg{n}; end end end end % Code to handle parameter name - value pairs if readstate == keywordvalue while n < nargs if ~isa(arg{n},'char') | ~isa(arg{n+1}, 'double') error('There should be a parameter name - value pair'); end if strncmpi(arg{n},'im' ,2), im = arg{n+1}; elseif strncmpi(arg{n},'nscale' ,2), nscale = arg{n+1}; elseif strncmpi(arg{n},'norient' ,2), norient = arg{n+1}; elseif strncmpi(arg{n},'minWaveLength',2), minWaveLength = arg{n+1}; elseif strncmpi(arg{n},'mult' ,2), mult = arg{n+1}; elseif strncmpi(arg{n},'sigmaOnf',2), sigmaOnf = arg{n+1}; elseif strncmpi(arg{n},'dThetaOnSigma',2), dThetaOnSigma = arg{n+1}; elseif strncmpi(arg{n},'k' ,1), k = arg{n+1}; elseif strncmpi(arg{n},'cutOff' ,2), cutOff = arg{n+1}; elseif strncmpi(arg{n},'g' ,1), g = arg{n+1}; else error('Unrecognised parameter name'); end n = n+2; if n == nargs error('Unmatched parameter name - value pair'); end end end if isempty(im) error('No image argument supplied'); end if ~isa(im, 'double') im = double(im); end if nscale < 1 error('nscale must be an integer >= 1'); end if norient < 1 error('norient must be an integer >= 1'); end if minWaveLength < 2 error('It makes little sense to have a wavelength < 2'); end if cutOff < 0 | cutOff > 1 error('Cut off value must be between 0 and 1'); end
github
jacksky64/imageProcessing-master
noisecomp.m
.m
imageProcessing-master/GaborImageFeatures/noisecomp.m
7,750
utf_8
9676f0608db5db81178e20d70f317783
% NOISECOMP - Function for denoising an image % % function cleanimage = noisecomp(image, k, nscale, mult, norient, softness) % % Parameters: % k - No of standard deviations of noise to reject 2-3 % nscale - No of filter scales to use (5-7) - the more scales used % the more low frequencies are covered % mult - multiplying factor between scales (2.5-3) % norient - No of orientations to use (6) % softness - degree of soft thresholding (0-hard 1-soft) % % For maximum processing speed the input image should have a size that % is a power of 2. % % The convolutions are done via the FFT. Many of the parameters relate % to the specification of the filters in the frequency plane. % The parameters are set within the file rather than being specified as % arguments because they rarely need to be changed - nor are they very % critical. % % Reference: % Peter Kovesi, "Phase Preserving Denoising of Images". % The Australian Pattern Recognition Society Conference: DICTA'99. % December 1999. Perth WA. pp 212-217 % http://www.cs.uwa.edu.au/pub/robvis/papers/pk/denoise.ps.gz. % % Copyright (c) 1998-2000 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % September 1998 - original version % May 1999 - % May 2000 - modified to allow arbitrary size images function cleanimage = noisecomp(image, k, nscale, mult, norient, softness) %nscale = 6; % Number of wavelet scales. %norient = 6; % Number of filter orientations. minWaveLength = 2; % Wavelength of smallest scale filter. %mult = 2; % Scaling factor between successive filters. sigmaOnf = 0.55; % Ratio of the standard deviation of the Gaussian % describing the log Gabor filter's transfer function % in the frequency domain to the filter center frequency. dThetaOnSigma = 1.; % Ratio of angular interval between filter orientations % and the standard deviation of the angular Gaussian % function used to construct filters in the freq. plane. epsilon = .00001;% Used to prevent division by zero. thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the % angular Gaussian function used to % construct filters in the freq. plane. imagefft = fft2(image); % Fourier transform of image [rows,cols] = size(imagefft); % Create two matrices, x and y. All elements of x have a value equal to its % x coordinate relative to the centre, elements of y have values equal to % their y coordinate relative to the centre. x = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2); y = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2); radius = sqrt(x.^2 + y.^2); % Matrix values contain normalised radius from centre. radius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle so that % taking the log of the radius will not cause trouble. theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve anti-clockwise angles) clear x; clear y; % save a little memory sig = []; estMeanEn = []; aMean = []; aSig = []; totalEnergy = zeros(rows,cols); % response at each orientation. for o = 1:norient, % For each orientation. disp(['Processing orientation ' num2str(o)]); angl = (o-1)*pi/norient; % Calculate filter angle. wavelength = minWaveLength; % Initialize filter wavelength. % Pre-compute filter data specific to this orientation % For each point in the filter matrix calculate the angular distance from the % specified filter orientation. To overcome the angular wrap-around problem % sine difference and cosine difference values are first computed and then % the atan2 function is used to determine angular distance. ds = sin(theta) * cos(angl) - cos(theta) * sin(angl); % Difference in sine. dc = cos(theta) * cos(angl) + sin(theta) * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component. for s = 1:nscale, % For each scale. % Construct the filter - first calculate the radial filter component. fo = 1.0/wavelength; % Centre frequency of filter. rfo = fo/0.5; % Normalised radius from centre of frequency plane % corresponding to fo. logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter % back to zero (undo the radius fudge). filter = logGabor .* spread; % Multiply by the angular spread to get the filter. filter = fftshift(filter); % Swap quadrants to move zero frequency % to the corners. % Convolve image with even an odd filters returning the result in EO EOfft = imagefft .* filter; % Do the convolution. EO = ifft2(EOfft); % Back transform. aEO = abs(EO); if s == 1 % Estimate the mean and variance in the amplitude response of the smallest scale % filter pair at this orientation. % If the noise is Gaussian the amplitude response will have a Rayleigh distribution. % We calculate the median amplitude response as this is a robust statistic. % From this we estimate the mean and variance of the Rayleigh distribution medianEn = median(reshape(aEO,1,rows*cols)); meanEn = medianEn*.5*sqrt(-pi/log(0.5)); RayVar = (4-pi)*(meanEn.^2)/pi; RayMean = meanEn; estMeanEn = [estMeanEn meanEn]; sig = [sig sqrt(RayVar)]; %% May want to look at actual distribution on special images % hist(reshape(aEO,1,rows*cols),100); % pause(1); end % Now apply soft thresholding T = (RayMean + k*sqrt(RayVar))/(mult^(s-1)); % Noise effect inversely proportional to % bandwidth/centre frequency. validEO = aEO > T; % Find where magnitude of energy exceeds noise. V = softness*T*EO./(aEO + epsilon); % Calculate array of noise vectors to subtract. V = ~validEO.*EO + validEO.*V; % Adjust noise vectors so that EO values will % not be negated EO = EO-V; % Subtract noise vector. totalEnergy = totalEnergy + EO; wavelength = wavelength * mult; % Wavelength of next filter end end % For each orientation disp('Estimated mean noise in each orientation') disp(estMeanEn); cleanimage = real(totalEnergy); %imagesc(cleanimage), title('denoised image'), axis image;
github
jacksky64/imageProcessing-master
loggabor.m
.m
imageProcessing-master/GaborImageFeatures/loggabor.m
1,707
utf_8
c15d2b1f67996d38d0003a5309d2f76f
% LOGGABOR % % Plots 1D log-Gabor functions % % Author: Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk @ csse uwa edu au http://www.csse.uwa.edu.au/~pk function loggabor(nscale, wmin, mult, konwo) Npts = 2048; Nwaves = 1; wmax = 0.5; dw = wmax/(Npts-1); w = [0: dw: wmax]; wo = wmin/2; for s = 1:nscale w(1) = 1; % fudge Gw{s} = exp( (-(log(w/wo)).^2) ./ (2*(log(konwo)).^2) ); Gw{s}(1) = 0; % undo fudge Wave{s} = fftshift(ifft(Gw{s})); wavelength = 1/wo; p = max(round(Npts/2 - Nwaves*wavelength),1); q = min(round(Npts/2 + Nwaves*wavelength),Npts); Wave{s} = Wave{s}(p:q); wo = wo*mult; end w(1) = 0; % undo fudge lw = 2; % linewidth fs = 14; % font size figure(1), clf for s = 1:nscale subplot(2,1,1), plot(w, Gw{s},'LineWidth',lw), axis([0 0.5 0 1.1]), hold on subplot(2,1,2), semilogx(w, Gw{s},'LineWidth',lw), axis([0 0.5 0 1.1]), hold on end subplot(2,1,1), title('Log-Gabor Transfer Functions','FontSize',fs); xlabel('frequency','FontSize',fs) subplot(2,1,2), xlabel('log frequency','FontSize',fs) ymax = 1.05*max(abs(Wave{nscale})); figure(2), clf for s = 1:nscale subplot(2,nscale,s), plot(real(Wave{s}),'LineWidth',lw), axis([0 length(Wave{s}) -ymax ymax]), axis off subplot(2,nscale,s+nscale), plot(imag(Wave{s}),'LineWidth',lw), axis([0 length(Wave{s}) -ymax ymax]), axis off end subplot(2,nscale,1), title('even symmetric wavelets','FontSize',fs); subplot(2,nscale,nscale+1), title('odd symmetric wavelets','FontSize',fs);
github
jacksky64/imageProcessing-master
lowpassfilter.m
.m
imageProcessing-master/GaborImageFeatures/lowpassfilter.m
2,446
utf_8
d8cb687e785e698617852ce86f35a064
% LOWPASSFILTER - Constructs a low-pass butterworth filter. % % usage: f = lowpassfilter(sze, cutoff, n) % % where: sze is a two element vector specifying the size of filter % to construct [rows cols]. % cutoff is the cutoff frequency of the filter 0 - 0.5 % n is the order of the filter, the higher n is the sharper % the transition is. (n must be an integer >= 1). % Note that n is doubled so that it is always an even integer. % % 1 % f = -------------------- % 2n % 1.0 + (w/cutoff) % % The frequency origin of the returned filter is at the corners. % % See also: HIGHPASSFILTER, HIGHBOOSTFILTER, BANDPASSFILTER % % Copyright (c) 1999 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 1999 % August 2005 - Fixed up frequency ranges for odd and even sized filters % (previous code was a bit approximate) function f = lowpassfilter(sze, cutoff, n) if cutoff < 0 | cutoff > 0.5 error('cutoff frequency must be between 0 and 0.5'); end if rem(n,1) ~= 0 | n < 1 error('n must be an integer >= 1'); end if length(sze) == 1 rows = sze; cols = sze; else rows = sze(1); cols = sze(2); end % Set up X and Y matrices with ranges normalised to +/- 0.5 % The following code adjusts things appropriately for odd and even values % of rows and columns. if mod(cols,2) xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1); else xrange = [-cols/2:(cols/2-1)]/cols; end if mod(rows,2) yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1); else yrange = [-rows/2:(rows/2-1)]/rows; end [x,y] = meshgrid(xrange, yrange); radius = sqrt(x.^2 + y.^2); % A matrix with every pixel = radius relative to centre. f = ifftshift( 1 ./ (1.0 + (radius ./ cutoff).^(2*n)) ); % The filter
github
jacksky64/imageProcessing-master
odot.m
.m
imageProcessing-master/GaborImageFeatures/odot.m
3,720
utf_8
336255093ed76b067368d764f3d823d5
% ODOT - Demonstrates odot and oslash operators on 1D signal % % Usage: [smooth, energy] = odot(f, K) % % Arguments: f - a 1D signal % K - optional 'Weiner' type factor to condition the results % where division by 0 occurs in the 'oslash' operation. % K defaults to 'eps', If oscillations appear in the % plots try increasing the value of K % % Returns: energy - the Local Energy of the signal. % smooth - the smooth component of the signal obtained by % performing the 'oslash' operator between the % signal and its Local Energy. % Plots: % Signal Hilbert Transform of Signal % Local Energy Hilbert Transform of Energy % Smooth Component Reconstruction % % Smooth = signal 'oslash' energy % Reconstruction = energy 'odot' smooth % % Glitches in the results will be seen at points where the Local Energy % peaks - these points cause numerical grief. These problems can be % alleviated by smoothing the signal slightly and/or increasing the % parameter K. % % This code only works for 1D signals - I am not sure how you would % implement it for 2D images... % Reference: Robyn Owens. "Feature-Free Images", Pattern Recognition % Letters. Vol 15. pp 35-44, 1994. % Copyright (c) 2004 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % March 2004 function [smooth, energy] = odot(f, K) if nargin == 1 K = eps; end N = length(f); if rem(N,2) > 0 % odd No of elements - trim the last one off to make the % number of elements even for simplicity. N = N - 1; f = f(1:N); end F = fft(f); F(1) = 0; % Kill DC component f = real(ifft(F)); % Reconstruct signal minus DC component % Perform 90 degree phase shift on the signal by multiplying +ve % frequencies of the fft by i and the -ve frequencies by -i, and then % inverting. phaseshift = [ ones(1,N/2)*i ones(1,N/2)*(-i) ]; % Hilbert Transform of signal h = real(ifft(F.*phaseshift)); energy = sqrt(f.^2 + h.^2); % Energy % Hilbert Transform of Energy energyh = real(ifft(fft(energy).*phaseshift)); % smooth = signal 'oslash' energy divisor = energy.^2 + energyh.^2; % Where divisor << K, weinercorrector -> 0/K % Where divisor >> K, weinercorrector -> 1 weinercorrector = divisor.^2 ./ ((divisor.^2)+K); smooth = (f.*energy + energyh.*h)./divisor .* weinercorrector; % Hilbert transform of smooth component smoothh=real(ifft(fft(smooth).*phaseshift)); % Reconstruction = energy odot smooth recon = (smooth.*energy - smoothh.*energyh); subplot(3,2,1), plot(f),title('Signal'); subplot(3,2,2), plot(h),title('Hilbert Transform of Signal'); subplot(3,2,3), plot(energy),title('Local Energy'); subplot(3,2,4), plot(energyh),title('Hilbert Transform of Energy'); subplot(3,2,5), plot(smooth),title('Smooth Component'); subplot(3,2,6), plot(recon),title('Reconstruction');
github
jacksky64/imageProcessing-master
dispfeat.m
.m
imageProcessing-master/GaborImageFeatures/dispfeat.m
5,648
utf_8
b84431635f0865ba6f5383b095221c41
% DISPFEAT - Displays feature types as detected by PHASECONG. % % This function provides a visualisation of the feature types as detected % by PHASECONG. % % Usage: im = dispfeat(ft, edgeim, 'l') % % Arguments: ft - A complex valued image giving the weighted mean % phase angle at every point in the image for the % orientation having maximum energy. % edgeim - A binary edge image (typically obtained via % non-maxima suppression and thresholding). % This is used as a `mask' to specify which bits of % the phase data should be displayed. % Alternatively you can supply a phase congruency % image in which case it is used to control the % saturation of the colour coding % l - An optional parameter indicating that a line plot % encoded by line style should also be produced. If % this is the case then `edgeim' really should be an % edge image. % % Returns: im - An edge image with edges colour coded according to % feature type. % % Two or three plots are generated: % 1. An edge image with edges colour coded according to feature type. % 2. A histogram of the frequencies at which the different feature types % occur. % 3. Optionally a black/white edge image with edges coded by different line % styles. Not as pretty as the first plot, but it is something that can % be put in a paper and reproduced in black and white. % Copyright (c) 2001 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % June 2001 function im = dispfeat(ft, edgeim) % Construct the colour coded image maxhue = 0.7; % Hues vary from 0 (red) indicating line feature to % 0.7 (blue) indicating a step feature. nhues = 50; phaseang = angle(ft); % Extract phase angles. % Map -ve phase angles to 0-pi negphase = phaseang<0; phaseang = negphase.*(-phaseang) + ~negphase.*phaseang; % Then map angles > pi/2 to 0-pi/2 x = phaseang>(pi/2); phaseang = x.*(pi-phaseang) + ~x.*phaseang; % Now set up a HSV image and convert to RGB hsvim(:,:,1) = (pi/2-phaseang)/(pi/2)*maxhue; hsvim(:,:,2) = edgeim; % saturation hsvim(:,:,3) = 1; hsvim(1,:,3) = 0; hsvim(end,:,3) = 0; hsvim(:,1,3) = 0; hsvim(:,end,3) = 0; im = hsv2rgb(hsvim); % Set up the colour key bar keybar(:,:,1) = [maxhue:-maxhue/nhues:0]'; keybar(:,:,2) = 1; keybar(:,:,3) = 1; keybar = hsv2rgb(keybar); % Plot the results figure(1), clf subplot('position',[.05 .1 .75 .8]), imshow(im) subplot('position',[.8 .1 .1 .8]), imshow(keybar) text(3,2,'step feature'); text(3,nhues/2,'step/line'); text(3,nhues,'line feature'); % Construct the histogram of feature types figure(2),clf data = phaseang(find(edgeim)); % find phase angles just at edge points Nbins = 32; bincentres = [0:pi/2/Nbins:pi/2]; hdata = histc(data(:), bincentres); bar(bincentres+pi/4/Nbins, hdata) % plot histogram ymax = max(hdata); xlabel('phase angle'); ylabel('frequency'); ypos = -.12*ymax; axis([0 pi/2 0 1.05*ymax]) if nargin == 3 % Construct the feature type image coded using different line styles % Generate a phase angle image with non-zero values only at edge % points. An offset of eps is added to differentiate points having 0 % phase from non edge points. featedge = (phaseang+eps).*double(edgeim); % Now construct feature images over specified phase ranges f1 = featedge >= eps & featedge < pi/6; f2 = featedge >= pi/6 & featedge < pi/3; f3 = featedge >= pi/3 & featedge <= pi/2; fprintf('Linking edges for plots...\n'); [f1edgelst dum] = edgelink(f1,2); [f2edgelst dum] = edgelink(f2,2); [f3edgelst dum] = edgelink(f3,2); figno = 3; figure(figno), clf % Construct a legend by first drawing some dummy, zero length, lines % with the appropriate linestyles in the right order line([0 0],[0 0],'LineStyle','-'); line([0 0],[0 0],'LineStyle','--'); line([0 0],[0 0],'LineStyle',':'); legend('step', 'step/line', 'line',3); % Now do the real plots plotedgelist(f1edgelst, figno, '-'); plotedgelist(f2edgelst, figno, '--'); plotedgelist(f3edgelst, figno, ':'); % Draw a border around the whole image [r c] = size(edgeim); line([0 c c 0 0],[0 0 r r 0]); axis([0 c 0 r]) axis equal axis ij axis off end %------------------------------------------------------------------------ % Internal function to plot an edgelist as generated by edgelink using a % specified linestyle function plotedgelist(elist, figno, linestyle) figure(figno); for e = 1:length(elist) line(elist{e}(:,2), elist{e}(:,1), 'LineStyle', linestyle, ... 'LineWidth',1); end
github
jacksky64/imageProcessing-master
gaborconvolve.m
.m
imageProcessing-master/GaborImageFeatures/gaborconvolve.m
7,461
utf_8
e5eafdc94ab27e11c00dc229fa39b9fb
% GABORCONVOLVE - function for convolving image with log-Gabor filters % % Usage: EO = gaborconvolve(im, nscale, norient, minWaveLength, mult, ... % sigmaOnf, dThetaOnSigma, feedback) % % Arguments: % The convolutions are done via the FFT. Many of the parameters relate % to the specification of the filters in the frequency plane. % % Variable Suggested Description % name value % ---------------------------------------------------------- % im Image to be convolved. % nscale = 4; Number of wavelet scales. % norient = 6; Number of filter orientations. % minWaveLength = 3; Wavelength of smallest scale filter. % mult = 2; Scaling factor between successive filters. % sigmaOnf = 0.65; Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's % transfer function in the frequency domain % to the filter center frequency. % dThetaOnSigma = 1.5; Ratio of angular interval between filter % orientations and the standard deviation of % the angular Gaussian function used to % construct filters in the freq. plane. % feedback 0/1 Optional parameter. If set to 1 a message % indicating which orientation is being % processed is printed on the screen. % % Returns: % % EO a 2D cell array of complex valued convolution results % % EO{s,o} = convolution result for scale s and orientation o. % The real part is the result of convolving with the even % symmetric filter, the imaginary part is the result from % convolution with the odd symmetric filter. % % Hence: % abs(EO{s,o}) returns the magnitude of the convolution over the % image at scale s and orientation o. % angle(EO{s,o}) returns the phase angles. % % % Notes on filter settings to obtain even coverage of the spectrum % dthetaOnSigma 1.5 % sigmaOnf .85 mult 1.3 % sigmaOnf .75 mult 1.6 (bandwidth ~1 octave) % sigmaOnf .65 mult 2.1 % sigmaOnf .55 mult 3 (bandwidth ~2 octaves) % % For maximum speed the input image should be square and have a % size that is a power of 2, but the code will operate on images % of arbitrary size. % % % The determination of mult given sigmaOnf is entirely empirical % What I do is plot out the sum of the filters in the frequency domain % and see how even the coverage of the spectrum is. % If there are concentric 'gaps' in the spectrum one needs to % reduce mult and/or reduce sigmaOnf (which increases filter bandwidth) % % If there are 'gaps' radiating outwards then one needs to reduce % dthetaOnSigma (increasing angular bandwidth of the filters) % % For details of log-Gabor filters see: % D. J. Field, "Relations Between the Statistics of Natural Images and the % Response Properties of Cortical Cells", Journal of The Optical Society of % America A, Vol 4, No. 12, December 1987. pp 2379-2394 % Copyright (c) 2001-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % May 2001 function EO = gaborconvolve(im, nscale, norient, minWaveLength, mult, ... sigmaOnf, dThetaOnSigma, feedback) if nargin == 7 feedback = 0; end if ~isa(im,'double') im = double(im); end [rows cols] = size(im); imagefft = fft2(im); % Fourier transform of image EO = cell(nscale, norient); % Pre-allocate cell array % Pre-compute some stuff to speed up filter construction [x,y] = meshgrid( [-cols/2:(cols/2-1)]/cols,... [-rows/2:(rows/2-1)]/rows); radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre. radius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle % so that taking the log of the radius will % not cause trouble. % Precompute sine and cosine of the polar angle of all pixels about the % centre point theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) sintheta = sin(theta); costheta = cos(theta); clear x; clear y; clear theta; % save a little memory thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the % angular Gaussian function used to % construct filters in the freq. plane. % The main loop... for o = 1:norient, % For each orientation. if feedback fprintf('Processing orientation %d \r', o); end angl = (o-1)*pi/norient; % Calculate filter angle. wavelength = minWaveLength; % Initialize filter wavelength. % Pre-compute filter data specific to this orientation % For each point in the filter matrix calculate the angular distance from the % specified filter orientation. To overcome the angular wrap-around problem % sine difference and cosine difference values are first computed and then % the atan2 function is used to determine angular distance. ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine. dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component. for s = 1:nscale, % For each scale. % Construct the filter - first calculate the radial filter component. fo = 1.0/wavelength; % Centre frequency of filter. logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter % back to zero (undo the radius fudge). filter = fftshift(logGabor .* spread); % Multiply by the angular spread to get the filter % and swap quadrants to move zero frequency % to the corners. % Do the convolution, back transform, and save the result in EO EO{s,o} = ifft2(imagefft .* filter); wavelength = wavelength * mult; % Finally calculate Wavelength of next filter end % ... and process the next scale end % For each orientation if feedback, fprintf(' \r'); end
github
jacksky64/imageProcessing-master
monofilt.m
.m
imageProcessing-master/GaborImageFeatures/monofilt.m
6,435
utf_8
adac38e6a3a0ad2423e6f10b769dc1fd
% MONOFILT - Apply monogenic filters to an image to obtain 2D analytic signal % % Implementation of Felsberg's monogenic filters % % Usage: [f, h1f, h2f, A, theta, psi] = ... % monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap) % 3 4 2 0.65 1/0 % Arguments: % The convolutions are done via the FFT. Many of the parameters relate % to the specification of the filters in the frequency plane. % % Variable Suggested Description % name value % ---------------------------------------------------------- % im Image to be convolved. % nscale = 3; Number of filter scales. % minWaveLength = 4; Wavelength of smallest scale filter. % mult = 2; Scaling factor between successive filters. % sigmaOnf = 0.65; Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's % transfer function in the frequency domain % to the filter center frequency. % orientWrap 1/0 Optional flag 1/0 to turn on/off % 'wrapping' of orientation data from a % range of -pi .. pi to the range 0 .. pi. % This affects the interpretation of the % phase angle - see note below. Defaults to 0. % Returns: % % f - cell array of bandpass filter responses with respect to scale. % h1f - cell array of bandpass h1 filter responses wrt scale. % h2f - cell array of bandpass h2 filter responses. % A - cell array of monogenic energy responses. % theta - cell array of phase orientation responses. % psi - cell array of phase angle responses. % % If orientWrap is 1 (on) theta will be returned in the range 0 .. pi and % psi (the phase angle) will be returned in the range -pi .. pi. If % orientWrap is 0 theta will be returned in the range -pi .. pi and psi will % be returned in the range -pi/2 .. pi/2. Try both options on an image of a % circle to see what this means! % % Experimentation with sigmaOnf can be useful depending on your application. % I have found values as low as 0.2 (a filter with a *very* large bandwidth) % to be useful on some occasions. % % See also: GABORCONVOLVE % References: % Michael Felsberg and Gerald Sommer. "A New Extension of Linear Signal % Processing for Estimating Local Properties and Detecting Features" % DAGM Symposium 2000, Kiel % % Michael Felsberg and Gerald Sommer. "The monogenic signal" IEEE % Transactions on Signal Processing, 49(12):3136-3144, December 2001 % Copyright (c) 2004-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % October 2004 - Original version. % May 2005 - Orientation wrapping and code cleaned up. % August 2005 - Phase calculation improved. function [f, h1f, h2f, A, theta, psi] = ... monofilt(im, nscale, minWaveLength, mult, sigmaOnf, orientWrap) if nargin == 5 orientWrap = 0; % Default is no orientation wrapping end if nargout > 4 thetaPhase = 1; % Calculate orientation and phase else thetaPhase = 0; % Only return filter outputs end [rows,cols] = size(im); IM = fft2(double(im)); % Generate horizontal and vertical frequency grids that vary from % -0.5 to 0.5 [u1, u2] = meshgrid(([1:cols]-(fix(cols/2)+1))/(cols-mod(cols,2)), ... ([1:rows]-(fix(rows/2)+1))/(rows-mod(rows,2))); u1 = ifftshift(u1); % Quadrant shift to put 0 frequency at the corners u2 = ifftshift(u2); radius = sqrt(u1.^2 + u2.^2); % Matrix values contain frequency % values as a radius from centre % (but quadrant shifted) % Get rid of the 0 radius value in the middle (at top left corner after % fftshifting) so that taking the log of the radius, or dividing by the % radius, will not cause trouble. radius(1,1) = 1; H1 = i*u1./radius; % The two monogenic filters in the frequency domain H2 = i*u2./radius; % The two monogenic filters H1 and H2 are oriented in frequency space % but are not selective in terms of the magnitudes of the % frequencies. The code below generates bandpass log-Gabor filters % which are point-wise multiplied by H1 and H2 to produce different % bandpass versions of H1 and H2 for s = 1:nscale wavelength = minWaveLength*mult^(s-1); fo = 1.0/wavelength; % Centre frequency of filter. logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(1,1) = 0; % undo the radius fudge. % Generate bandpass versions of H1 and H2 at this scale H1s = H1.*logGabor; H2s = H2.*logGabor; % Apply filters to image in the frequency domain and get spatial % results f{s} = real(ifft2(IM.*logGabor)); h1f{s} = real(ifft2(IM.*H1s)); h2f{s} = real(ifft2(IM.*H2s)); A{s} = sqrt(f{s}.^2 + h1f{s}.^2 + h2f{s}.^2); % Magnitude of Energy. % If requested calculate the orientation and phase angles if thetaPhase theta{s} = atan2(h2f{s}, h1f{s}); % Orientation. % Here phase is measured relative to the h1f-h2f plane as an % 'elevation' angle that ranges over +- pi/2 psi{s} = atan2(f{s}, sqrt(h1f{s}.^2 + h2f{s}.^2)); if orientWrap % Wrap orientation values back into the range 0-pi negind = find(theta{s}<0); theta{s}(negind) = theta{s}(negind) + pi; % Where orientation values have been wrapped we should % adjust phase accordingly **check** psi{s}(negind) = pi-psi{s}(negind); morethanpi = find(psi{s}>pi); psi{s}(morethanpi) = psi{s}(morethanpi)-2*pi; end end end
github
jacksky64/imageProcessing-master
plotgaborfilters.m
.m
imageProcessing-master/GaborImageFeatures/plotgaborfilters.m
8,558
utf_8
88279510c3ad351b70b45076aa576792
% PLOTGABORFILTERS - Plots log-Gabor filters % % The purpose of this code is to see what effect the various parameter % settings have on the formation of a log-Gabor filter bank. % % Usage: [Ffilter, Efilter, Ofilter] = plotgaborfilters(sze, nscale, norient,... % minWaveLength, mult, sigmaOnf, dThetaOnSigma) % % Arguments: % Many of the parameters relate to the specification of the filters in the frequency plane. % % Variable Suggested Description % name value % ---------------------------------------------------------- % sze = 200 Size of image grid on which the filters % are calculated. Note that the actual size % of the filter is really specified by its % wavelength. % nscale = 4; Number of wavelet scales. % norient = 6; Number of filter orientations. % minWaveLength = 3; Wavelength of smallest scale filter. % mult = 2; Scaling factor between successive filters. % sigmaOnf = 0.65; Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's % transfer function in the frequency domain % to the filter center frequency. % dThetaOnSigma = 1.5; Ratio of angular interval between filter % orientations and the standard deviation of % the angular Gaussian function used to % construct filters in the freq. plane. % % Returns: % Ffilter - a 2D cell array of filters defined in the frequency domain. % Efilter - a 2D cell array of even filters defined in the spatial domain. % Ofilter - a 2D cell array of odd filters defined in the spatial domain. % % Ffilter{s,o} = filter for scale s and orientation o. % The even and odd filters in the spatial domain for scale s, % orientation o, are obtained using. % % Efilter = ifftshift(real(ifft2(fftshift(filter{s,o})))); % Ofilter = ifftshift(imag(ifft2(fftshift(filter{s,o})))); % % Plots: % Figure 1 - Sum of the filters in the frequency domain % Figure 2 - Cross sections of Figure 1 % Figures 3 and 4 - Surface and intensity plots of filters in the % spatial domain at the smallest and largest % scales respectively. % % See also: GABORCONVOLVE, PHASECONG % Copyright (c) 2001-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % May 2001 - Original version. % February 2005 - Cleaned up. % August 2005 - Ffilter,Efilter and Ofilter corrected to return with scale % varying as the first index in the cell arrays. function [Ffilter, Efilter, Ofilter] = ... plotgaborfilters(sze, nscale, norient, minWaveLength, mult, ... sigmaOnf, dThetaOnSigma) rows = sze; cols = sze; thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the % angular Gaussian function used to % construct filters in the freq. plane. % Pre-compute some stuff to speed up filter construction % Set up X and Y matrices with ranges normalised to +/- 0.5 % The following code adjusts things appropriately for odd and even values % of rows and columns. if mod(cols,2) xrange = [-(cols-1)/2:(cols-1)/2]/(cols-1); else xrange = [-cols/2:(cols/2-1)]/cols; end if mod(rows,2) yrange = [-(rows-1)/2:(rows-1)/2]/(rows-1); else yrange = [-rows/2:(rows/2-1)]/rows; end [x,y] = meshgrid(xrange, yrange); radius = sqrt(x.^2 + y.^2); % Normalised radius (frequency) values 0.0 - 0.5 % Get rid of the 0 radius value in the middle so that taking the log of % the radius will not cause trouble. radius(fix(rows/2+1),fix(cols/2+1)) = 1; theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) sintheta = sin(theta); costheta = cos(theta); clear x; clear y; clear theta; % save a little memory % Define a low-pass filter that is as large as possible, yet falls away to zero % at the boundaries. All log Gabor filters are multiplied by this to ensure % that filters are as similar as possible across orientations (Eliminate the % extra frequencies at the 'corners' of the FFT) lp = fftshift(lowpassfilter([rows,cols],.45,15)); % Radius .4, 'sharpness' 10 % The main loop... filtersum = zeros(rows,cols); for o = 1:2*norient, % For each orientation. angl = (o-1)*pi/norient; % Calculate filter angle. wavelength = minWaveLength; % Initialize filter wavelength. % Compute filter data specific to this orientation % For each point in the filter matrix calculate the angular distance from the % specified filter orientation. To overcome the angular wrap-around problem % sine difference and cosine difference values are first computed and then % the atan2 function is used to determine angular distance. ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine. dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % The angular filter component. for s = 1:nscale, % For each scale. % Construct the filter - first calculate the radial filter component. fo = 1.0/wavelength; % Centre frequency of filter. logGabor = exp((-(log(radius/fo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set value at center of the filter % back to zero (undo the radius fudge). logGabor = logGabor.*lp; % Apply low-pass filter Ffilter{s,o} = logGabor .* spread; % Multiply by the angular % spread to get the filter. filtersum = filtersum + Ffilter{s,o}; Efilter{s,o} = ifftshift(real(ifft2(fftshift(Ffilter{s,o})))); Ofilter{s,o} = ifftshift(imag(ifft2(fftshift(Ffilter{s,o})))); wavelength = wavelength*mult; end end % Plot sum of filters and slices radially and tangentially figure(1), clf, show(filtersum,1), title('sum of filters'); figure(2), clf subplot(2,1,1), plot(filtersum(round(rows/2+1),:)) title('radial slice through sum of filters'); ang = [0:pi/32:2*pi]; r = rows/4; tslice = improfile(filtersum,r*cos(ang)+cols/2,r*sin(ang)+rows/2); subplot(2,1,2), plot(tslice), axis([0 length(tslice) 0 1.1*max(tslice)]); title('tangential slice through sum of filters at f = 0.25'); % Plot Even and Odd filters at the largest and smallest scales h = figure(3); clf set(h,'name',sprintf('Filters: Wavelenth = %.2f',minWaveLength)); subplot(3,2,1), surfl(Efilter{1,1}), shading interp, colormap(gray), title('Even Filter'); subplot(3,2,2), surfl(Ofilter{1,1}), shading interp, colormap(gray) title('Odd Filter'); subplot(3,2,3),imagesc(Efilter{1,1}), axis image, colormap(gray) subplot(3,2,4),imagesc(Ofilter{1,1}), axis image, colormap(gray) subplot(3,2,5),imagesc(Ffilter{1,1}), axis image, colormap(gray) title('Frequency Domain'); h = figure(4); clf set(h,'name',sprintf('Filters: Wavelenth = %.2f',minWaveLength*mult^(nscale-1))); subplot(3,2,1), surfl(Efilter{nscale,1}), shading interp, colormap(gray) title('Even Filter'); subplot(3,2,2), surfl(Ofilter{nscale,1}), shading interp, colormap(gray) title('Odd Filter'); subplot(3,2,3),imagesc(Efilter{nscale,1}), axis image, colormap(gray) subplot(3,2,4),imagesc(Ofilter{nscale,1}), axis image, colormap(gray) subplot(3,2,5),imagesc(Ffilter{nscale,1}), axis image, colormap(gray) title('Frequency Domain');
github
jacksky64/imageProcessing-master
spatialgabor.m
.m
imageProcessing-master/GaborImageFeatures/spatialgabor.m
2,644
utf_8
0d56aa13789e5563961e97238d519790
% SPATIALGABOR - applies single oriented gabor filter to an image % % Usage: % [Eim, Oim, Aim] = spatialgabor(im, wavelength, angle, kx, ky, showfilter) % % Arguments: % im - Image to be processed. % wavelength - Wavelength in pixels of Gabor filter to construct % angle - Angle of filter in degrees. An angle of 0 gives a % filter that responds to vertical features. % kx, ky - Scale factors specifying the filter sigma relative % to the wavelength of the filter. This is done so % that the shapes of the filters are invariant to the % scale. kx controls the sigma in the x direction % which is along the filter, and hence controls the % bandwidth of the filter. ky controls the sigma % across the filter and hence controls the % orientational selectivity of the filter. A value of % 0.5 for both kx and ky is a good starting point. % showfilter - An optional flag 0/1. When set an image of the % even filter is displayed for inspection. % % Returns: % Eim - Result from filtering with the even (cosine) Gabor filter % Oim - Result from filtering with the odd (sine) Gabor filter % Aim - Amplitude image = sqrt(Eim.^2 + Oim.^2) % % Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % pk at csse uwa edu au % http://www.csse.uwa.edu.au/~pk % % October 2006 function [Eim, Oim, Aim] = spatialgabor(im, wavelength, angle, kx, ky, showfilter) if nargin == 5 showfilter = 0; end im = double(im); [rows, cols] = size(im); newim = zeros(rows,cols); % Construct even and odd Gabor filters sigmax = wavelength*kx; sigmay = wavelength*ky; sze = round(3*max(sigmax,sigmay)); [x,y] = meshgrid(-sze:sze); evenFilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)... .*cos(2*pi*(1/wavelength)*x); oddFilter = exp(-(x.^2/sigmax^2 + y.^2/sigmay^2)/2)... .*sin(2*pi*(1/wavelength)*x); evenFilter = imrotate(evenFilter, angle, 'bilinear'); oddFilter = imrotate(oddFilter, angle, 'bilinear'); % Do the filtering Eim = filter2(evenFilter,im); % Even filter result Oim = filter2(oddFilter,im); % Odd filter result Aim = sqrt(Eim.^2 + Oim.^2); % Amplitude if showfilter % Display filter for inspection figure(1), imshow(evenFilter,[]); title('filter'); end
github
jacksky64/imageProcessing-master
phasecong.m
.m
imageProcessing-master/GaborImageFeatures/phasecong.m
16,644
utf_8
693c5ec683ef5ce8c816379185261bf7
% PHASECONG - Computes phase congruency on an image. % % Usage: [pc or ft] = phasecong(im) % % This function calculates the PC_2 measure of phase congruency. % For maximum speed the input image should be square and have a % size that is a power of 2, but the code will operate on images % of arbitrary size. % % % Returned values: % pc - Phase congruency image (values between 0 and 1) % or - Orientation image. Provides orientation in which % local energy is a maximum in in degrees (0-180), % angles positive anti-clockwise. % ft - A complex valued image giving the weighted mean % phase angle at every point in the image for the % orientation having maximum energy. Use the % function DISPFEAT to display this data. % % Parameters: % im - A greyscale image to be processed. % % You can also specify numerous optional parameters. See the code to find % out what they are. The convolutions are done via the FFT. Many of the % parameters relate to the specification of the filters in the frequency % plane. Default values for parameters are set within the file rather than % being required as arguments because they rarely need to be changed - nor % are they very critical. However, you may want to experiment with % specifying/editing the values of `nscales' and `noiseCompFactor'. % % Note this phase congruency code is very computationally expensive and uses % *lots* of memory. % % % Example MATLAB session: % % >> im = imread('picci.tif'); % >> image(im); % Display the image % >> [pc or ft] = phasecong(im); % >> imagesc(pc), colormap(gray); % Display the phase congruency image % % % To convert the phase congruency image to an edge map (with my usual parameters): % % >> nm = nonmaxsup(pc, or, 1.5); % Non-maxima suppression. % The parameter 1.5 can result in edges more than 1 pixel wide but helps % in picking up `broad' maxima. % >> edgim = hysthresh(nm, 0.4, 0.2); % Hysteresis thresholding. % >> edgeim = bwmorph(edgim,'skel',Inf); % Skeletonize the edgemap to fix % % the non-maximal suppression. % >> imagesc(edgeim), colormap(gray); % % % To display the different feature types present in your image use: % % >> dispfeat(ft,edgim); % % With a small amount of editing the code can be modified to calculate % a dimensionless measure of local symmetry in the image. The basis % of this is that one looks for points in the image where the local % phase is 90 or 270 degrees (the symmetric points in the cycle). % Editing instructions are within the code. % % Notes on filter settings to obtain even coverage of the spectrum % dthetaOnSigma 1.5 % sigmaOnf .85 mult 1.3 % sigmaOnf .75 mult 1.6 (bandwidth ~1 octave) % sigmaOnf .65 mult 2.1 % sigmaOnf .55 mult 3 (bandwidth ~2 octaves) % % References: % % Peter Kovesi, "Image Features From Phase Congruency". Videre: A % Journal of Computer Vision Research. MIT Press. Volume 1, Number 3, % Summer 1999 http://mitpress.mit.edu/e-journals/Videre/001/v13.html % Copyright (c) 1996-2005 Peter Kovesi % School of Computer Science & Software Engineering % The University of Western Australia % http://www.csse.uwa.edu.au/ % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, subject to the following conditions: % % The above copyright notice and this permission notice shall be included in % all copies or substantial portions of the Software. % % The Software is provided "as is", without warranty of any kind. % Original Version written April 1996 % Noise compensation corrected. August 1998 % Noise compensation corrected. October 1998 - Again!!! % Modified to operate on non-square images of arbitrary size. September 1999 % Modified to return feature type image. May 2001 function[phaseCongruency,orientation, featType]=phasecong(im, nscale, norient, ... minWaveLength, mult, ... sigmaOnf, dThetaOnSigma, ... k, cutOff) sze = size(im); if nargin < 2 nscale = 3; % Number of wavelet scales. end if nargin < 3 norient = 6; % Number of filter orientations. end if nargin < 4 minWaveLength = 3; % Wavelength of smallest scale filter. end if nargin < 5 mult = 2; % Scaling factor between successive filters. end if nargin < 6 sigmaOnf = 0.55; % Ratio of the standard deviation of the % Gaussian describing the log Gabor filter's transfer function % in the frequency domain to the filter center frequency. end if nargin < 7 dThetaOnSigma = 1.7; % Ratio of angular interval between filter orientations % and the standard deviation of the angular Gaussian % function used to construct filters in the % freq. plane. end if nargin < 8 k = 3.0; % No of standard deviations of the noise energy beyond the % mean at which we set the noise threshold point. % standard deviation to its maximum effect % on Energy. end if nargin < 9 cutOff = 0.4; % The fractional measure of frequency spread % below which phase congruency values get penalized. end g = 10; % Controls the sharpness of the transition in the sigmoid % function used to weight phase congruency for frequency % spread. epsilon = .0001; % Used to prevent division by zero. thetaSigma = pi/norient/dThetaOnSigma; % Calculate the standard deviation of the % angular Gaussian function used to % construct filters in the freq. plane. imagefft = fft2(im); % Fourier transform of image sze = size(imagefft); rows = sze(1); cols = sze(2); zero = zeros(sze); totalEnergy = zero; % Matrix for accumulating weighted phase % congruency values (energy). totalSumAn = zero; % Matrix for accumulating filter response % amplitude values. orientation = zero; % Matrix storing orientation with greatest % energy for each pixel. estMeanE2n = []; % Pre-compute some stuff to speed up filter construction x = ones(rows,1) * (-cols/2 : (cols/2 - 1))/(cols/2); y = (-rows/2 : (rows/2 - 1))' * ones(1,cols)/(rows/2); radius = sqrt(x.^2 + y.^2); % Matrix values contain *normalised* radius from centre. radius(round(rows/2+1),round(cols/2+1)) = 1; % Get rid of the 0 radius value in the middle % so that taking the log of the radius will % not cause trouble. theta = atan2(-y,x); % Matrix values contain polar angle. % (note -ve y is used to give +ve % anti-clockwise angles) sintheta = sin(theta); costheta = cos(theta); clear x; clear y; clear theta; % save a little memory % The main loop... for o = 1:norient, % For each orientation. disp(['Processing orientation ' num2str(o)]); angl = (o-1)*pi/norient; % Calculate filter angle. wavelength = minWaveLength; % Initialize filter wavelength. sumE_ThisOrient = zero; % Initialize accumulator matrices. sumO_ThisOrient = zero; sumAn_ThisOrient = zero; Energy_ThisOrient = zero; EOArray = []; % Array of complex convolution images - one for each scale. ifftFilterArray = []; % Array of inverse FFTs of filters % Pre-compute filter data specific to this orientation % For each point in the filter matrix calculate the angular distance from the % specified filter orientation. To overcome the angular wrap-around problem % sine difference and cosine difference values are first computed and then % the atan2 function is used to determine angular distance. ds = sintheta * cos(angl) - costheta * sin(angl); % Difference in sine. dc = costheta * cos(angl) + sintheta * sin(angl); % Difference in cosine. dtheta = abs(atan2(ds,dc)); % Absolute angular distance. spread = exp((-dtheta.^2) / (2 * thetaSigma^2)); % Calculate the angular filter component. for s = 1:nscale, % For each scale. % Construct the filter - first calculate the radial filter component. fo = 1.0/wavelength; % Centre frequency of filter. rfo = fo/0.5; % Normalised radius from centre of frequency plane % corresponding to fo. logGabor = exp((-(log(radius/rfo)).^2) / (2 * log(sigmaOnf)^2)); logGabor(round(rows/2+1),round(cols/2+1)) = 0; % Set the value at the center of the filter % back to zero (undo the radius fudge). filter = logGabor .* spread; % Multiply by the angular spread to get the filter. filter = fftshift(filter); % Swap quadrants to move zero frequency % to the corners. ifftFilt = real(ifft2(filter))*sqrt(rows*cols); % Note rescaling to match power ifftFilterArray = [ifftFilterArray ifftFilt]; % record ifft2 of filter % Convolve image with even and odd filters returning the result in EO EOfft = imagefft .* filter; % Do the convolution. EO = ifft2(EOfft); % Back transform. EOArray = [EOArray, EO]; % Record convolution result An = abs(EO); % Amplitude of even & odd filter response. sumAn_ThisOrient = sumAn_ThisOrient + An; % Sum of amplitude responses. sumE_ThisOrient = sumE_ThisOrient + real(EO); % Sum of even filter convolution results. sumO_ThisOrient = sumO_ThisOrient + imag(EO); % Sum of odd filter convolution results. if s == 1 % Record the maximum An over all scales maxAn = An; else maxAn = max(maxAn, An); end if s==1 EM_n = sum(sum(filter.^2)); % Record mean squared filter value at smallest end % scale. This is used for noise estimation. wavelength = wavelength * mult; % Finally calculate Wavelength of next filter end % ... and process the next scale % Get weighted mean filter response vector, this gives the weighted mean phase angle. XEnergy = sqrt(sumE_ThisOrient.^2 + sumO_ThisOrient.^2) + epsilon; MeanE = sumE_ThisOrient ./ XEnergy; MeanO = sumO_ThisOrient ./ XEnergy; % Now calculate An(cos(phase_deviation) - | sin(phase_deviation)) | by using % dot and cross products between the weighted mean filter response vector and % the individual filter response vectors at each scale. This quantity is % phase congruency multiplied by An, which we call energy. for s = 1:nscale, EO = submat(EOArray,s,cols); % Extract even and odd filter E = real(EO); O = imag(EO); Energy_ThisOrient = Energy_ThisOrient ... + E.*MeanE + O.*MeanO - abs(E.*MeanO - O.*MeanE); end % Note: To calculate the phase symmetry measure replace the for loop above % with the following loop. (The calculation of MeanE, MeanO, sumE_ThisOrient % and sumO_ThisOrient can also be omitted). It is suggested that the value % of nscale is increased (to say, 5 for a 256x256 image) and that cutOff is % set to 0 to eliminate weighting for frequency spread. % for s = 1:nscale, % Energy_ThisOrient = Energy_ThisOrient ... % + abs(real(submat(EOArray,s,cols))) - abs(imag(submat(EOArray,s,cols))); % end % Compensate for noise % We estimate the noise power from the energy squared response at the smallest scale. % If the noise is Gaussian the energy squared will have a Chi-squared 2DOF pdf. % We calculate the median energy squared response as this is a robust statistic. % From this we estimate the mean. % The estimate of noise power is obtained by dividing the mean squared energy value % by the mean squared filter value medianE2n = median(reshape(abs(submat(EOArray,1,cols)).^2,1,rows*cols)); meanE2n = -medianE2n/log(0.5); estMeanE2n = [estMeanE2n meanE2n]; noisePower = meanE2n/EM_n; % Estimate of noise power. % Now estimate the total energy^2 due to noise % Estimate for sum(An^2) + sum(Ai.*Aj.*(cphi.*cphj + sphi.*sphj)) EstSumAn2 = zero; for s = 1:nscale EstSumAn2 = EstSumAn2+submat(ifftFilterArray,s,cols).^2; end EstSumAiAj = zero; for si = 1:(nscale-1) for sj = (si+1):nscale EstSumAiAj = EstSumAiAj + submat(ifftFilterArray,si,cols).*submat(ifftFilterArray,sj,cols); end end EstNoiseEnergy2 = 2*noisePower*sum(sum(EstSumAn2)) + 4*noisePower*sum(sum(EstSumAiAj)); tau = sqrt(EstNoiseEnergy2/2); % Rayleigh parameter EstNoiseEnergy = tau*sqrt(pi/2); % Expected value of noise energy EstNoiseEnergySigma = sqrt( (2-pi/2)*tau^2 ); T = EstNoiseEnergy + k*EstNoiseEnergySigma; % Noise threshold % The estimated noise effect calculated above is only valid for the PC_1 measure. % The PC_2 measure does not lend itself readily to the same analysis. However % empirically it seems that the noise effect is overestimated roughly by a factor % of 1.7 for the filter parameters used here. T = T/1.7; % Empirical rescaling of the estimated noise effect to % suit the PC_2 phase congruency measure Energy_ThisOrient = max(Energy_ThisOrient - T, zero); % Apply noise threshold % Form weighting that penalizes frequency distributions that are particularly % narrow. % Calculate fractional 'width' of the frequencies present by taking % the sum of the filter response amplitudes and dividing by the maximum % amplitude at each point on the image. width = sumAn_ThisOrient ./ (maxAn + epsilon) / nscale; % Now calculate the sigmoidal weighting function for this orientation. weight = 1.0 ./ (1 + exp( (cutOff - width)*g)); % Apply weighting Energy_ThisOrient = weight.*Energy_ThisOrient; % Update accumulator matrix for sumAn and totalEnergy totalSumAn = totalSumAn + sumAn_ThisOrient; totalEnergy = totalEnergy + Energy_ThisOrient; % Update orientation matrix by finding image points where the energy in this % orientation is greater than in any previous orientation (the change matrix) % and then replacing these elements in the orientation matrix with the % current orientation number. if(o == 1), maxEnergy = Energy_ThisOrient; featType = E + i*O; else change = Energy_ThisOrient > maxEnergy; orientation = (o - 1).*change + orientation.*(~change); featType = (E+i*O).*change + featType.*(~change); maxEnergy = max(maxEnergy, Energy_ThisOrient); end end % For each orientation disp('Mean Energy squared values recorded with smallest scale filter at each orientation'); disp(estMeanE2n); % Display results %imagesc(totalEnergy), axis image, title('total energy'); %disp('Hit any key to continue '); pause %imagesc(totalSumAn), axis image, title('total sumAn'); %disp('Hit any key to continue '); pause % Normalize totalEnergy by the totalSumAn to obtain phase congruency phaseCongruency = totalEnergy ./ (totalSumAn + epsilon); %imagesc(phaseCongruency), axis image, title('phase congruency'); % Convert orientation matrix values to degrees orientation = orientation * (180 / norient); featType = featType*i; % Rotate feature phase angles by 90deg so that 0 % phase corresponds to a step edge (this is a % fudge I must have something the wrong way % around somewhere) % % SUBMAT % % Function to extract the i'th sub-matrix 'cols' wide from a large % matrix composed of several matricies. The large matrix is used in % lieu of an array of matricies function a = submat(big,i,cols) a = big(:,((i-1)*cols+1):(i*cols));
github
jacksky64/imageProcessing-master
xraymu.m
.m
imageProcessing-master/xraymu/xraymu.m
4,840
utf_8
4443d46a51b213105453a1a0c4ea46f5
function [mus,xray_energies,ztable] = xraymu(chem_spec,egys,varargin) % function [mus,xray_energies,ztable] = xraymu(chem_spec,egys,varargin) % X-ray attenuation coefficients for a specified compound from tabulated data % returns NaN's for energies beyond tabulated data range % inputs: % chem_spec: (case-sensitive string) chemical formula for the compound e.g. NaSO4 or H2O % or an n by 2 matrix, 1 row per element with columns [(atomic number of element), fraction by weight] % egys: a vector of x-ray energy (keV) % optional arguments % 'energy_absorption' if specified the function returns energy absorption coefficents (cm^2/gm) % 'weight_fraction' if specified expects the formula to specify weight fraction % e.g. for water H.111O.888 % outputs: % mus: a column vector of the attenuation coefficients at the specified energies (cm^2/gm) % xray_energies: the x-ray energies for the mus values (keV) % ztable: a 2 column matrix with atomic numbers in 1st column and fraction by weight in 2nd % % for more information see http://aprendtech.com/wordpress/?p=45 % % REA 5/28/07-2/10/09 from PhotonAttenuation.m by Jaroslaw Tuszynski % REA 7/31/10 add ztable output nreqargs = 2; assert(nargin>=nreqargs); mutype = 'att'; do_weight_fraction = false; if(nargin>nreqargs) i=1; while(i<=size(varargin,2)) switch lower(varargin{i}) case 'energy_absorption'; mutype = 'abs'; case 'weight_fraction'; do_weight_fraction = true; otherwise error('Unknown argument %s given',varargin{i}); end i=i+1; end end assert(~isempty(egys) ); assert(all(egys>0.0)); if ischar(chem_spec) [elems,ns] = ParseChemicalFormula_xraymu(chem_spec); [atomic_numbers,atomic_weights] = ChemicalSymbols2AtomicNumbers(elems); elseif isnumeric(chem_spec) && (size(chem_spec,2)==2) && (all(chem_spec(:,1)<92)) && (all(chem_spec(:,2)<=1)) do_weight_fraction = true; atomic_numbers = chem_spec(:,1); ns = chem_spec(:,2); % this var used for wgt fractions below if do_weight_fraction==true else error('chem_spec format not recognized'); end % get the attenuation coefficients for all the elements used musall = MusElementsLoc(atomic_numbers,egys,mutype); % prepare the weighting if do_weight_fraction % formula is weight fraction e.g. H.111O.888 atomic_weightsall = ns(:); else % formula is atomic fraction e.g. H2O atomic_weightsall = ns(:).*atomic_weights(:); atomic_weightsall = (1/sum(atomic_weightsall))*atomic_weightsall; end ztable = [atomic_numbers(:) (1/sum(atomic_weightsall))*atomic_weightsall]; mus = sum( musall.* repmat(atomic_weightsall',numel(egys),1), 2); % sum along rows xray_energies = egys(:); function musall = MusElementsLoc(atomic_numbers,egys,type) % function musall = MusElementsLoc(atomic_numbers,egys) % Returns a 2D array of the attenuation coefficients % of the elements with atomic numbers atomic_numbers at energies egys % inputs: % atomic_numbers: atomic numbers of the elements 1:93 % egys: the x-ray energies (keV) % type: (string) 'att' (mass attenuation coeffs), 'abs' energy absorption % outputs: % musall: a matrix with each column the mass attentuation coefficients for the % corresponding element in atomic_numbers at the specified energies % REA 5/28/07 % get the tables of data [weights,symbols,xdatas] = XrayData; % check inputs assert(all(floor(atomic_numbers(:)) == atomic_numbers(:))); % make sure they are integers mn = min(atomic_numbers(:)); mx = max(atomic_numbers(:)); % and in proper range assert( (mn>0) && (mn<=length(xdatas) ) ); assert( (mx>0) && (mx<=length(xdatas)) ); assert(all(egys>0)); egys = 0.001*egys; % convert to MeV % prep log-log interpolation from NIST data musall = zeros(numel(egys),numel(atomic_numbers)); for kz = 1:numel(atomic_numbers) z = atomic_numbers(kz); xdata = xdatas{z}; etable = log(xdata.PhotonEnergy); switch type case 'att' mus = log( xdata.MAC' ); case 'abs' mus = log( xdata.MEAC' ); otherwise error('MusElementsLoc: absorption type %s unknown',type) end % in NIST table, energies are duplicated at absorption edges % but this gives interp1 problems, so nudge them just below and above edge d = 5*eps; % offset energies this much at absorption edges (MeV) k = find(diff(etable)==0);% find edges etable(k) = etable(k)-d; % give them some width etable(k+1) = etable(k+1)+d; a = interp1(etable, mus, log(egys), 'cubic'); % cubic Hermite polynomial a(a>9.267) = 9.267; % extrapolated values can get high especially close to edges. Clip them. musall(:,kz) = exp(a(:)); end
github
jacksky64/imageProcessing-master
mergeimports.m
.m
imageProcessing-master/yamlmatlab/+yaml/mergeimports.m
2,907
utf_8
62fc3b86ba001de3e7986f200b433f7d
function result = mergeimports(data, verb) import yaml.*; if ~exist('verb','var') verb = 0; end; result = recurse(data, 0, [], verb); end function result = recurse(data, level, addit, verb) import yaml.*; indent = repmat(' | ',1,level); % for debugging if iscell(data) result = iter_cell(data, level, addit, verb); elseif isstruct(data) result = iter_struct(data, level, addit, verb); else if any(verb == 1) % for debugging fprintf([indent,'Some data: ']); disp(data); end; result = data; end; end function result = iter_cell(data, level, addit, verb) import yaml.*; indent = repmat(' | ',1,level); % for debugging result = {}; if any(verb == 1); fprintf([indent,'cell {\n']); end; % for debugging for i = 1:length(data) itemcontent = recurse(data{i}, level + 1, addit, verb); result{end + 1} = itemcontent; end; if any(verb == 1); fprintf([indent,'} cell\n']); end; % for debugging end function result = iter_struct(data, level, addit, verb) import yaml.*; indent = repmat(' | ',1,level); % for debugging result = struct(); collected_imports = {}; if any(verb == 1); fprintf([indent,'struct {\n']); end; % for debugging for i = fields(data)' fld = char(i); if any(verb == 1); fprintf([indent,' +-field ',fld,':\n']); end; % for debugging result.(fld) = recurse(data.(fld), level + 1, addit, verb); if isequal(fld, 'import') processed_import = process_import_field(result.(fld)); result = rmfield(result, 'import'); if isstruct(processed_import) collected_imports{end+1} = processed_import; else disp(processed_import); error('Expected struct, otherwise it cannot be merged with the rest.'); end; end; end; for i = 1:length(collected_imports) result = merge_struct(result, collected_imports{i}, {}, 'deep'); end; if any(verb == 1); fprintf([indent,'} struct\n']); end; % for debugging end function result = process_import_field(data) import yaml.*; if iscell(data) merged_structs = struct(); collected_nonstruct = {}; for i = 1:length(data) if isstruct(data{i}) merged_structs = merge_struct(merged_structs, data{i}, {}, 'deep'); else collected_nonstruct{end+1} = data{i}; end; end; if isempty(collected_nonstruct) result = merged_structs; elseif isempty(merged_structs) result = collected_nonstruct; else result = {merged_structs; collected_nonstruct}; end; else error('BUG: import field should always contain a cell.'); end; end
github
jacksky64/imageProcessing-master
DateTime.m
.m
imageProcessing-master/yamlmatlab/+yaml/DateTime.m
7,819
utf_8
1d32e576b384f88172041b154f0c60f4
classdef DateTime Copyright (c) 2011 This program is a result of a joined cooperation of Energocentrum PLUS, s.r.o. and Czech Technical University (CTU) in Prague. The program is maintained by Energocentrum PLUS, s.r.o. and licensed under the terms of MIT license. Full text of the license is included in the program release. Author(s): Jiri Cigler, Dept. of Control Engineering, CTU Prague & Automatic Control Laboratory, ETH Zurich Jan Siroky, Energocentrum PLUS s.r.o. Implementation and Revisions: Auth Date Description of change ---- --------- ------------------------------------------------- jc 01-Mar-11 First implementation jc 30-Sep-11 Added function colon jc 07-Jan-12 Added functions addtodate,datevec,weekday properties serialDate end methods import yaml.*; function this = DateTime(varargin) if numel(varargin)==1 && isa(varargin{1},'java.util.Date') sec = varargin{1}.getTime/1000; this.serialDate=datenum(1970,1,1,0,0,sec); else this.serialDate=datenum(varargin{:}); end end import yaml.*; function this = plus(this,val) o =@plus; this = doFun(this,o,val); end import yaml.*; function this = minus(this,val) o =@minus; this = doFun(this,o,val); end import yaml.*; function this = times(this,val) o =@times; this = doFun(this,o,val); end import yaml.*; function this = mtimes(this,val) o =@mtimes; this = doFun(this,o,val); end import yaml.*; function this = mrdivide(this,val) o =@mrdivide; this = doFun(this,o,val); end import yaml.*; function this = rdivide(this,val) o =@rdivide; this = doFun(this,o,val); end import yaml.*; function this = horzcat(this,varargin) for i=1:numel(varargin) this.serialDate = [this.serialDate, varargin{i}.serialDate]; end end import yaml.*; function out = colon(this,step,to) vect = [double(this):double(step):double(to)]'; out =DateTime(vect); end import yaml.*; function this = vertcat(this,varargin) for i=1:numel(varargin) this.serialDate = [this.serialDate; varargin{i}.serialDate]; end end import yaml.*; function this = ctranspose(this) this.serialDate = this.serialDate'; end import yaml.*; function this = transpose(this) this.serialDate = this.serialDate'; end import yaml.*; function disp(this) disp([this.serialDate]) end import yaml.*; function out = double(this) out = this.serialDate; end import yaml.*; function out = length(this) out = length(this.serialDate); end import yaml.*; function out = size(this,varargin) out = size(this.serialDate,varargin{:}); end import yaml.*; function out = numel(this) out = numel(this.serialDate); end import yaml.*; function out = isreal(this) out = isreal(this.serialDate); end import yaml.*; function out = isnan(this) out = isnan(this.serialDate); end import yaml.*; function out = isfinite(this) out = isfinite(this.serialDate); end import yaml.*; function out = le(this,B) if isa(B,'DateTime') out = le(this.serialDate,B.serialDate); else out = le(this.serialDate,B); end end import yaml.*; function out = lt(this,B) fun=@lt; if isa(B,'DateTime') out = fun(this.serialDate,B.serialDate); else out = fun(this.serialDate,B); end end import yaml.*; function out = gt(this,B) fun=@gt; if isa(B,'DateTime') out = fun(this.serialDate,B.serialDate); else out = fun(this.serialDate,B); end end import yaml.*; function out = eq(this,B) fun=@eq; if isa(B,'DateTime') out = fun(this.serialDate,B.serialDate); else out = fun(this.serialDate,B); end end import yaml.*; function out = diff(this) out = diff(this.serialDate); end import yaml.*; function out = norm(this,varargin) out = norm(this.serialDate,varargin{:}); end import yaml.*; function [this k] = sort(this,varargin) [this.serialDate k] = sort(this.serialDate,varargin{:}); end import yaml.*; function this = subsref(this,S) if isa(S.subs{1},'DateTime') S.subs{1}=double(S.subs{1}); end this.serialDate = subsref(this.serialDate,S); end import yaml.*; function idx = subsindex(this) idx = double(this)-1; end import yaml.*; function endidx = end(this,k,n) if size(this.serialDate,1)==1 || size(this.serialDate,2)==1 endidx=numel(this.serialDate); else endidx = size(this.serialDate,k); end end import yaml.*; function this = subsasgn(this, S, B) if not(isa(B,'DateTime')) B=DateTime(B); end this.serialDate =subsasgn(this.serialDate, S, B); end import yaml.*; function res = bsxfun(fun,A,B) res = fun(A,B); end import yaml.*; function out =superiorfloat (x,y,xi) if isa(x,'DateTime') && isa(xi,'DateTime') out = superiorfloat(x.serialDate,y,xi.serialDate); elseif isa(x,'DateTime') && not(isa(xi,'DateTime')) out = superiorfloat(x.serialDate,y,xi); elseif not(isa(x,'DateTime')) && isa(xi,'DateTime') out = superiorfloat(x,y,xi.serialDate); else out = superiorfloat(x,y,xi); end end import yaml.*; function this = floor(this) this.serialDate = floor(this.serialDate); end import yaml.*; function this = max(this,varargin) this.serialDate = max(this.serialDate,varargin{:}); end import yaml.*; function this = min(this,varargin) this.serialDate = min(this.serialDate,varargin{:}); end import yaml.*; function out = datestr(this,varargin) out = datestr(this.serialDate,varargin{:}); end import yaml.*; function out = addtodate(this,varargin) out = addtodate(this.serialDate,varargin{:}); end import yaml.*; function varargout= datevec(this,varargin) nout = nargout; if nout <=1 varargout{1} = datevec(this.serialDate,varargin{:}); elseif nout ==2 [varargout{1} varargout{2}] = datevec(this.serialDate,varargin{:}); elseif nout ==3 [varargout{1} varargout{2} varargout{3}] = datevec(this.serialDate,varargin{:}); elseif nout ==4 [varargout{1} varargout{2} varargout{3} varargout{4}] = datevec(this.serialDate,varargin{:}); elseif nout ==5 [varargout{1} varargout{2} varargout{3} varargout{4} varargout{5} ] = datevec(this.serialDate,varargin{:}); elseif nout ==6 [varargout{1} varargout{2} varargout{3} varargout{4} varargout{5} varargout{6} ] = datevec(this.serialDate,varargin{:}); else error('Unknown function call'); end end end methods (Access = private) import yaml.*; function this = doFun (this,o, val)
github
jacksky64/imageProcessing-master
ReadYamlRaw.m
.m
imageProcessing-master/yamlmatlab/+yaml/ReadYamlRaw.m
4,999
utf_8
348b70ee95f28e77a5059ca9b30517cd
function result = ReadYamlRaw(filename, verbose, nosuchfileaction, treatasdata) import yaml.*; if ~exist('verbose','var') verbose = 0; end; if ~exist('nosuchfileaction','var') nosuchfileaction = 0; end; if ~ismember(nosuchfileaction,[0,1]) error('nosuchfileexception parameter must be 0,1 or missing.'); end; if(~exist('treatasdata','var')) treatasdata = 0; end; if ~ismember(treatasdata,[0,1]) error('treatasdata parameter must be 0,1 or missing.'); end; [pth,~,~] = fileparts(mfilename('fullpath')); try import('org.yaml.snakeyaml.*'); javaObject('Yaml'); catch dp = [pth filesep 'external' filesep 'snakeyaml-1.9.jar']; if not(ismember(dp, javaclasspath ('-dynamic'))) javaaddpath(dp); % javaaddpath clears global variables!? end import('org.yaml.snakeyaml.*'); end; setverblevel(verbose); result = load_yaml(filename, nosuchfileaction, treatasdata); end function result = load_yaml(inputfilename, nosuchfileaction, treatasdata) import yaml.*; persistent nsfe; if exist('nosuchfileaction','var') %isempty(nsfe) && nsfe = nosuchfileaction; end; persistent tadf; if isempty(tadf) && exist('treatasdata','var') tadf = treatasdata; end; yaml = org.yaml.snakeyaml.Yaml(); % It appears that Java objects cannot be persistent!? if ~tadf [filepath, filename, fileext] = fileparts(inputfilename); if isempty(filepath) pathstore = cd(); else pathstore = cd(filepath); end; end; try if ~tadf result = scan(yaml.load(fileread([filename, fileext]))); else result = scan(yaml.load(inputfilename)); end; catch ex if ~tadf cd(pathstore); end; switch ex.identifier case 'MATLAB:fileread:cannotOpenFile' if nsfe == 1 error('MATLAB:MATYAML:FileNotFound', ['No such file to read: ',filename,fileext]); elseif nsfe == 0 warning('MATLAB:MATYAML:FileNotFound', ['No such file to read: ',filename,fileext]); result = struct(); return; end; end; rethrow(ex); end; if ~tadf cd(pathstore); end; end function result = scan(r) import yaml.*; if isa(r, 'char') result = scan_string(r); elseif isa(r, 'double') result = scan_numeric(r); elseif isa(r, 'logical') result = scan_logical(r); elseif isa(r, 'java.util.Date') result = scan_datetime(r); elseif isa(r, 'java.util.List') result = scan_list(r); elseif isa(r, 'java.util.Map') result = scan_map(r); else error(['Unknown data type: ' class(r)]); end; end function result = scan_string(r) import yaml.*; result = char(r); end function result = scan_numeric(r) import yaml.*; result = double(r); end function result = scan_logical(r) import yaml.*; result = logical(r); end function result = scan_datetime(r) import yaml.*; result = DateTime(r); end function result = scan_list(r) import yaml.*; result = cell(r.size(),1); it = r.iterator(); ii = 1; while it.hasNext() i = it.next(); result{ii} = scan(i); ii = ii + 1; end; end function result = scan_map(r) import yaml.*; it = r.keySet().iterator(); while it.hasNext() next = it.next(); i = next; ich = char(i); if iskw_import(ich) result.(ich) = perform_import(r.get(java.lang.String(ich))); else result.(genvarname(ich)) = scan(r.get(java.lang.String(ich))); end; end; if not(exist('result','var')) result={}; end end function result = iskw_import(r) import yaml.*; result = isequal(r, 'import'); end function result = perform_import(r) import yaml.*; r = scan(r); if iscell(r) && all(cellfun(@ischar, r)) result = cellfun(@load_yaml, r, 'UniformOutput', 0); elseif ischar(r) result = {load_yaml(r)}; else disp(r); error(['Importer does not unterstand given filename. ' 'Invalid node displayed above.']); end; end function setverblevel(level) import yaml.*; global verbose_readyaml; verbose_readyaml = 0; if exist('level','var') verbose_readyaml = level; end; end function result = getverblevel() import yaml.*; global verbose_readyaml; result = verbose_readyaml; end function info(level, text, value_to_display) import yaml.*; if getverblevel() >= level fprintf(text); if exist('value_to_display','var') disp(value_to_display); else fprintf('\n'); end; end; end
github
jacksky64/imageProcessing-master
makematrices.m
.m
imageProcessing-master/yamlmatlab/+yaml/makematrices.m
2,998
utf_8
b6ccf836e3e3a122d7868b15a1151df9
function result = makematrices(r, makeords) import yaml.*; result = recurse(r, 0, [], makeords); end function result = recurse(data, level, addit, makeords) import yaml.*; if iscell(data) result = iter_cell(data, level, addit, makeords); elseif isstruct(data) result = iter_struct(data, level, addit, makeords); else result = scan_data(data, level, addit); end; end function result = iter_cell(data, level, addit, makeords) import yaml.*; if isvector(data) && iscell_all(data) && isvector_all(data) && isaligned_all(data) && ismatrixrow_all(data) tmp = data; tmp = cellfun(@cell2mat, tmp, 'UniformOutput', 0); tmp = cellfun(@torow, tmp, 'UniformOutput', 0); tmp = tocolumn(tmp); tmp = cell2mat(tmp); if ~makeords tmp = num2cell(tmp); end; result = tmp; elseif isempty(data) result = []; else result = {}; for i = 1:length(data) result{i} = recurse(data{i}, level + 1, addit, makeords); end; end; end function result = iter_struct(data, level, addit, makeords) import yaml.*; result = struct(); for i = fields(data)' fld = char(i); result.(fld) = recurse(data.(fld), level + 1, addit, makeords); end; end function result = scan_data(data, level, addit) import yaml.*; result = data; end function result = iscell_all(cellvec) import yaml.*; result = all(cellfun(@iscell, cellvec)); end function result = isaligned_all(cellvec) import yaml.*; siz = numel(cellvec{1}); result = all(cellfun(@numel, cellvec) == siz); end function result = ismatrixrow_all(cellvec) import yaml.*; result = all(cellfun(@ismatrixrow, cellvec)); end function result = ismatrixrow(cellvec) import yaml.*; result = (isnumeric_all(cellvec) || islogical_all(cellvec) || isstruct_all(cellvec)) && issingle_all(cellvec) && iscompatible_all(cellvec); end function result = isnumeric_all(cellvec) import yaml.*; result = all(cellfun(@isnumeric, cellvec)); end function result = islogical_all(cellvec) import yaml.*; result = all(cellfun(@islogical, cellvec)); end function result = issingle_all(cellvec) import yaml.*; result = all(cellfun(@issingle, cellvec)); end function result = iscompatible_all(cellvec) import yaml.*; result = true; for i = 1:(length(cellvec) - 1) result = result && iscompatible(cellvec{i}, cellvec{i + 1}); end end function result = iscompatible(obj1, obj2) import yaml.*; result = isequal(class(obj1), class(obj2)); end function result = isvector_all(cellvec) import yaml.*; result = all(cellfun(@isvector, cellvec)); end function result = isstruct_all(cellvec) import yaml.*; result = all(cellfun(@isstruct, cellvec)); end function result = torow(vec) import yaml.*; result = tocolumn(vec).'; end function result = tocolumn(vec) import yaml.*; result = vec(:); end
github
jacksky64/imageProcessing-master
deflateimports.m
.m
imageProcessing-master/yamlmatlab/+yaml/deflateimports.m
1,597
utf_8
9b2a562969b1be978543af1bbc9340c7
function result = deflateimports(r) import yaml.*; result = recurse(r, 0, []); end function result = recurse(data, level, addit) import yaml.*; if iscell(data) && ~ismymatrix(data) result = iter_cell(data, level, addit); elseif isstruct(data) result = iter_struct(data, level, addit); else result = data; end; end function result = iter_cell(data, level, addit) import yaml.*; result = {}; icollect = {}; ii = 1; for i = 1:length(data) datai = data{i}; if issingleimport(datai) if ~iscell(datai.import) datai.import = {datai.import}; end; for j = 1:length(datai.import) icollect{end + 1} = datai.import{j}; end; else result{ii} = recurse(datai, level + 1, addit); ii = ii + 1; end; end; if ~isempty(icollect) result{end + 1} = struct('import',{icollect}); end; end function result = iter_struct(data, level, addit) import yaml.*; result = struct(); for i = fields(data)' fld = char(i); result.(fld) = recurse(data.(fld), level + 1, addit); end; end function result = issingleimport_all(r) import yaml.*; result = all(cellfun(@issingleimport, r)); end function result = issingleimport(r) import yaml.*; result = isstruct(r) && length(fields(r)) == 1 && isfield(r, 'import'); end function result = addall(list1, list2) import yaml.*; for i = 1:length(list2) list1{end + 1} = list2{i}; end; result = list1; end
github
jacksky64/imageProcessing-master
dosubstitution.m
.m
imageProcessing-master/yamlmatlab/+yaml/dosubstitution.m
963
utf_8
feed736691fdf3f1b56ad4f33f9b89f4
function result = dosubstitution(r, dictionary) import yaml.*; if ~exist('dictionary','var') dictionary = {}; end; result = recurse(r, 0, dictionary); end function result = recurse(data, level, dictionary) import yaml.*; if iscell(data) && ~ismymatrix(data) result = iter_cell(data, level, dictionary); elseif isstruct(data) result = iter_struct(data, level, dictionary); elseif ischar(data) && isfield(dictionary, data) result = dictionary.(data); else result = data; end; end function result = iter_cell(data, level, dictionary) import yaml.*; result = {}; for i = 1:length(data) result{i} = recurse(data{i}, level + 1, dictionary); end; end function result = iter_struct(data, level, dictionary) import yaml.*; result = data; for i = fields(data)' fld = char(i); result.(fld) = recurse(data.(fld), level + 1, dictionary); end; end
github
jacksky64/imageProcessing-master
datadump.m
.m
imageProcessing-master/yamlmatlab/+yaml/datadump.m
1,104
utf_8
38ebb873fefdc3b54d2b504c19a31a50
function datadump(data) import yaml.*; recurse(data, 0, []); end function result = recurse(data, level, addit) import yaml.*; indent = repmat(' | ',1,level); if iscell(data) && ~ismymatrix(data) result = iter_cell(data, level, addit); elseif isstruct(data) result = iter_struct(data, level, addit); else fprintf([indent,' +-Some data: ']); disp(data); result = data; end; end function result = iter_cell(data, level, addit) import yaml.*; indent = repmat(' | ',1,level); result = {}; fprintf([indent,'cell {\n']); for i = 1:length(data) result{i} = recurse(data{i}, level + 1, addit); end; fprintf([indent,'} cell\n']); end function result = iter_struct(data, level, addit) import yaml.*; indent = repmat(' | ',1,level); result = struct(); fprintf([indent,'struct {\n']); for i = fields(data)' fld = char(i); fprintf([indent,' +-field ',fld,':\n']); result.(fld) = recurse(data.(fld), level + 1, addit); end; fprintf([indent,'} struct\n']); end
github
jacksky64/imageProcessing-master
doinheritance.m
.m
imageProcessing-master/yamlmatlab/+yaml/doinheritance.m
2,631
utf_8
cc275395af98bd16ac7c446484686b8d
function result = doinheritance(r, tr) import yaml.*; if ~exist('tr','var') tr = r; end; result = recurse(r, 0, {tr}); end function result = recurse(data, level, addit) import yaml.*; if iscell(data) && ~ismymatrix(data) result = iter_cell(data, level, addit); elseif isstruct(data) result = iter_struct(data, level, addit); else result = data; end; end function result = iter_cell(data, level, addit) import yaml.*; result = {}; for i = 1:length(data) result{i} = recurse(data{i}, level + 1, addit); end; for i = 1:length(data) if isstruct(result{i}) && isfield(result{i}, kwd_parent()) result{i} = inherit(result{i}, result{i}.(kwd_parent()), [], addit{1}, {}); % !!! end; end; end function result = iter_struct(data, level, addit) import yaml.*; result = data; for i = fields(data)' fld = char(i); result.(fld) = recurse(data.(fld), level + 1, addit); end; for i = fields(result)' fld = char(i); if isstruct(result.(fld)) && isfield(result.(fld), kwd_parent()) result.(fld) = inherit(result.(fld), result.(fld).(kwd_parent()), [], addit{1}, {}); end; end; end function result = inherit(child, parent_chr, container, oaroot, loc_imported) import yaml.*; result = child; if ~iscell(parent_chr) parent_chr = {parent_chr}; end; for i = length(parent_chr):-1:1 if contains(loc_imported, parent_chr{i}) error('MATLAB:MATYAML:inheritedtwice',['Cyclic inheritance: ', parent_chr{i}]); end; try parentstruct = eval(['oaroot.',parent_chr{i}]); catch ex switch ex.identifier case {'MATLAB:nonExistentField', 'MATLAB:badsubscript'} error('MATLAB:MATYAML:NonExistentParent', ['Parent was not found: ',parent_chr{i}]); end; rethrow(ex); end; if isstruct(parentstruct) && isfield(parentstruct, kwd_parent()) next_loc_imported = loc_imported; next_loc_imported{end + 1} = parent_chr{i}; result = merge_struct(inherit(parentstruct, parentstruct.(kwd_parent()), [], oaroot, next_loc_imported), result, {'import'}); end; result = merge_struct(parentstruct, result, {'import'}); end; end function result = contains(list, chr) import yaml.*; for i = 1:length(list) if strcmp(list{i}, chr) result = true; return; end; end; result = false; end
github
jacksky64/imageProcessing-master
WriteYaml.m
.m
imageProcessing-master/yamlmatlab/+yaml/WriteYaml.m
5,246
utf_8
a8261807d51be1f0a8dc7a11661d379b
function result = WriteYaml(filename, data, flowstyle) import yaml.*; if ~exist('flowstyle','var') flowstyle = 0; end; if ~ismember(flowstyle, [0,1]) error('Flowstyle must be 0,1 or empty.'); end; result = []; [pth,~,~] = fileparts(mfilename('fullpath')); try import('org.yaml.snakeyaml.*'); javaObject('Yaml'); catch dp = [pth filesep 'external' filesep 'snakeyaml-1.9.jar']; if not(ismember(dp, javaclasspath ('-dynamic'))) javaaddpath(dp); % javaaddpath clears global variables!? end import('org.yaml.snakeyaml.*'); end; javastruct = scan(data); dumperopts = DumperOptions(); dumperopts.setLineBreak( javaMethod('getPlatformLineBreak', 'org.yaml.snakeyaml.DumperOptions$LineBreak')); if flowstyle classes = dumperopts.getClass.getClasses; flds = classes(3).getDeclaredFields(); fsfld = flds(1); if ~strcmp(char(fsfld.getName), 'FLOW') error(['Accessed another field instead of FLOW. Please correct', 'class/field indices (this error maybe caused by new snakeyaml version).']); end; dumperopts.setDefaultFlowStyle(fsfld.get([])); end; yaml = Yaml(dumperopts); output = yaml.dump(javastruct); if ~isempty(filename) fid = fopen(filename,'w'); fprintf(fid,'%s',char(output) ); fclose(fid); else result = output; end; end function result = scan(r) import yaml.*; if ischar(r) result = scan_char(r); elseif iscell(r) result = scan_cell(r); elseif isord(r) result = scan_ord(r); elseif isstruct(r) result = scan_struct(r); elseif isnumeric(r) result = scan_numeric(r); elseif islogical(r) result = scan_logical(r); elseif isa(r,'DateTime') result = scan_datetime(r); else error(['Cannot handle type: ' class(r)]); end end function result = scan_numeric(r) import yaml.*; if isempty(r) result = java.util.ArrayList(); elseif(isinteger(r)) result = java.lang.Integer(r); else result = java.lang.Double(r); end end function result = scan_logical(r) import yaml.*; if isempty(r) result = java.util.ArrayList(); else result = java.lang.Boolean(r); end end function result = scan_char(r) import yaml.*; if isempty(r) result = java.util.ArrayList(); else result = java.lang.String(r); end end function result = scan_datetime(r) import yaml.*; [Y, M, D, H, MN,S] = datevec(double(r)); result = java.util.GregorianCalendar(Y, M-1, D, H, MN,S); result.setTimeZone(java.util.TimeZone.getTimeZone('UTC')); end function result = scan_cell(r) import yaml.*; if(isrowvector(r)) result = scan_cell_row(r); elseif(iscolumnvector(r)) result = scan_cell_column(r); elseif(ismymatrix(r)) result = scan_cell_matrix(r); elseif(issingle(r)); result = scan_cell_single(r); elseif(isempty(r)) result = java.util.ArrayList(); else error('Unknown cell content.'); end; end function result = scan_ord(r) import yaml.*; if(isrowvector(r)) result = scan_ord_row(r); elseif(iscolumnvector(r)) result = scan_ord_column(r); elseif(ismymatrix(r)) result = scan_ord_matrix(r); elseif(issingle(r)) result = scan_ord_single(r); elseif(isempty(r)) result = java.util.ArrayList(); else error('Unknown ordinary array content.'); end; end function result = scan_cell_row(r) import yaml.*; result = java.util.ArrayList(); for ii = 1:size(r,2) result.add(scan(r{ii})); end; end function result = scan_cell_column(r) import yaml.*; result = java.util.ArrayList(); for ii = 1:size(r,1) tmp = r{ii}; if ~iscell(tmp) tmp = {tmp}; end; result.add(scan(tmp)); end; end function result = scan_cell_matrix(r) import yaml.*; result = java.util.ArrayList(); for ii = 1:size(r,1) i = r(ii,:); result.add(scan_cell_row(i)); end; end function result = scan_cell_single(r) import yaml.*; result = java.util.ArrayList(); result.add(scan(r{1})); end function result = scan_ord_row(r) import yaml.*; result = java.util.ArrayList(); for i = r result.add(scan(i)); end; end function result = scan_ord_column(r) import yaml.*; result = java.util.ArrayList(); for i = 1:size(r,1) result.add(scan_ord_row(r(i))); end; end function result = scan_ord_matrix(r) import yaml.*; result = java.util.ArrayList(); for i = r' result.add(scan_ord_row(i')); end; end function result = scan_ord_single(r) import yaml.*; result = java.util.ArrayList(); for i = r' result.add(r); end; end function result = scan_struct(r) import yaml.*; result = java.util.LinkedHashMap(); for i = fields(r)' key = i{1}; val = r.(key); result.put(key,scan(val)); end; end
github
jacksky64/imageProcessing-master
selftest_yamlmatlab.m
.m
imageProcessing-master/yamlmatlab/+yaml/Tests/selftest_yamlmatlab.m
2,954
utf_8
4b0ea27db95878c651e0c46855f39e18
function selftest_yamlmatlab(varargin) % This function tests consistency of YAMLMatlab, by default, the results % are stored in selftest_report.html in current work folder. % Example % >> selftest_yamlmatlab() % >> selftest_yamlmatlab(outFileName) % % %====================================================================== %{ Copyright (c) 2011 This program is a result of a joined cooperation of Energocentrum PLUS, s.r.o. and Czech Technical University (CTU) in Prague. The program is maintained by Energocentrum PLUS, s.r.o. and licensed under the terms of MIT license. Full text of the license is included in the program release. Author(s): Jiri Cigler, Dept. of Control Engineering, CTU Prague Jan Siroky, Energocentrum PLUS s.r.o. Implementation and Revisions: Auth Date Description of change ---- --------- ------------------------------------------------- jc 25-May-11 First implementation %} %====================================================================== fprintf('Running tests.\n'); outFname = 'selftest_report.html'; if numel(varargin) outFname = varargin{1}; end outStr = getHTMLHeader(); outStr = strcat(outStr,'<h1>Selftest report from:',datestr(now),'</h1>'); tests = dir([fileparts(which('selftest_yamlmatlab')) filesep 'test*.m']); for test=tests' [~,func]=fileparts(test.name); fhandle = str2func(func); stat = fhandle(); outStr = strcat(outStr, '<div id="MainTest"> <h2>',func, '</h2>', stat2html(stat,func),'</div>'); end outStr = strcat(outStr,'</BODY></HTML>'); fid = fopen(outFname,'w'); fprintf(fid,outStr); fclose(fid); fprintf('Opening internal browser.\n'); web(outFname,'-new'); end function html = stat2html(stat,name) if not(isstruct(stat)) error('Input argument must be a struct'); end html = ''; fn = fieldnames(stat); if all(ismember({'ok','desc'},fn)) if stat.ok flag = 'Passed'; else flag = '<b style="color:red">Failed</b>,'; end html = strcat(html,'<div id="Test"><h3>',name,': </h3> ', flag, ' <i>', stat.desc,'</i> </div>' ); end html = [html, '<table>']; for test = setdiff(fn',{'ok','desc'}) html = [html, '<tr>']; html = strcat(html, stat2html(stat.(test{1}),test{1})); html = [html, '</tr>']; end html = [html, '</table>']; end function str = getHTMLHeader() str = [ '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' ... '<HTML> ' ... '<HEAD>'... '<TITLE>::SELFTEST REPORT::</TITLE><STYLE> H2{color:blue} #MainTest{border: 1px blue solid;} h3,h4,h5,h6 {display: inline;} </STYLE>'... '</HEAD><BODY style="font-family:Arial, helvetica">']; end
github
jacksky64/imageProcessing-master
test_ReadYaml.m
.m
imageProcessing-master/yamlmatlab/+yaml/Tests/test_ReadYaml.m
8,883
utf_8
1647e455763d95a6c10948a007741f02
function stat = test_ReadYaml() % this function tests reading in the yaml file stat.ok = 1; stat.desc = ''; try %stat.test_ReadYaml_SimpleStructure = test_ReadYaml_SimpleStructure(); %stat.test_ReadYaml_DateTime = test_ReadYaml_DateTime(); fprintf('Testing read '); stat.test_RY_Matrices = test_RY_Matrices(); fprintf('.'); stat.test_RY_Whitespaces = test_RY_Whitespaces(); fprintf('.'); stat.test_RY_FloatingPoints = test_RY_FloatingPoints(); fprintf('.'); stat.test_RY_Indentation = test_RY_Indentation(); fprintf('.'); stat.test_RY_SequenceMapping = test_RY_SequenceMapping(); fprintf('.'); stat.test_RY_Simple = test_RY_Simple(); fprintf('.'); stat.test_RY_Time = test_RY_Time(); fprintf('.'); stat.test_RY_TimeVariants = test_RY_TimeVariants(); fprintf('.'); stat.test_RY_Import = test_RY_Import(); fprintf('.'); stat.test_RY_ImportDef = test_RY_ImportDef(); fprintf('.'); stat.test_RY_ImportNonex = test_RY_ImportNonex(); fprintf('.'); stat.test_RY_Inheritance = test_RY_Inheritance(); fprintf('.'); stat.test_RY_InheritanceMultiple = test_RY_InheritanceMultiple(); fprintf('.'); stat.test_RY_InheritanceLoop = test_RY_InheritanceLoop(); fprintf('.'); stat.test_RY_usecase_01 = test_RY_usecase_01(); fprintf('.\n'); catch stat.ok = 0; stat.desc = 'Program crash'; end end function result = PTH_PRIMITIVES() result = sprintf('Data%stest_primitives%s',filesep,filesep); end function result = PTH_IMPORT() result = sprintf('Data%stest_import%s',filesep,filesep); end function result = PTH_INHERITANCE() result = sprintf('Data%stest_inheritance%s',filesep,filesep); end function stat = test_RY_Matrices() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'matrices.yaml']); tv = load([PTH_PRIMITIVES() 'matrices.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_FloatingPoints() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'floating_points.yaml']); tv = load([PTH_PRIMITIVES() 'floating_points.mat']); if ~isequalwithequalnans(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_Indentation() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'indentation.yaml']); tv = load([PTH_PRIMITIVES() 'indentation.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_SequenceMapping() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'sequence_mapping.yaml']); tv = load([PTH_PRIMITIVES() 'sequence_mapping.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_Simple() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'simple.yaml']); tv = load([PTH_PRIMITIVES() 'simple.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_Time() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'time.yaml']); tv = load([PTH_PRIMITIVES() 'time.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_TimeVariants() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'time_variants.yaml']); tv = load([PTH_PRIMITIVES() 'time_variants.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_Import() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_IMPORT() 'import.yaml']); tv = load([PTH_IMPORT() 'import.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_ImportDef() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_IMPORT() 'import_def.yaml']); tv = load([PTH_IMPORT() 'import_def.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_ImportNonex() stat.ok = 0; stat.desc = 'Did not end with any exception.'; try try ry = ReadYaml([PTH_IMPORT() 'import_nonex.yaml'],1); catch ex if strcmp(ex.identifier, 'MATLAB:MATYAML:FileNotFound') stat.desc = ''; stat.ok = 1; else rethrow(ex); end; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_Inheritance() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_INHERITANCE() 'inheritance.yaml']); tv = load([PTH_INHERITANCE() 'inheritance.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_InheritanceMultiple() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_INHERITANCE() 'inheritance_multiple.yaml']); tv = load([PTH_INHERITANCE() 'inheritance_multiple.mat']); if ~isequal(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_InheritanceLoop() stat.ok = 0; stat.desc = 'Did not end with any exception.'; try try ry = ReadYaml([PTH_INHERITANCE() 'inheritance_loop.yaml']); catch ex if strcmp(ex.identifier, 'MATLAB:MATYAML:inheritedtwice') stat.desc = ''; stat.ok = 1; else rethrow(ex); end; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_Whitespaces() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'whitespaces.yaml']); if ~isfield(ry,'ImageFile') || ~isfield(ry,'ContoursCount') stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_RY_usecase_01() stat.ok = 1; stat.desc = ''; try ry = ReadYaml([PTH_PRIMITIVES() 'usecase_struct_01.yaml']); tv = load([PTH_PRIMITIVES() 'usecase_struct_01.mat']); if ~isequalwithequalnans(ry, tv.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end function stat = test_ReadYaml_SimpleStructure() stat.ok = 1; stat.desc = ''; try s = ReadYaml('simple.yaml'); ages = [s.age]; if not(isequal([33 27], ages)) || not(all(ismember({'John Smith', 'Mary Smith'}, {s.name}) )) stat.desc = ' Wrong values loaded'; stat.ok = 0; end catch stat.desc = 'Program crash'; stat.ok = 0; end end function stat = test_ReadYaml_DateTime() stat.ok = 1; stat.desc = ''; try s = ReadYaml('time.yaml'); if ~isa(s.Data.B1_S_SW{1},'DateTime') stat.desc = ' Wrong data type of datetick'; stat.ok = 0; end if isa(s.Data.B1_S_SW{2},'DateTime') stat.desc = ' Wrong data type of datetick'; stat.ok = 0; end catch stat.desc = 'Program crash'; stat.ok = 0; end end
github
jacksky64/imageProcessing-master
test_WriteYaml.m
.m
imageProcessing-master/yamlmatlab/+yaml/Tests/test_WriteYaml.m
1,745
utf_8
de37cbde8a33d40a7b1f05ef8e7f16cf
function stat = test_WriteYaml() stat.ok = 1; stat.desc = ''; try fprintf('Testing write '); stat.test_WY_Matrices = test_WY_Universal(PTH_PRIMITIVES(), 'matrices'); fprintf('.'); stat.test_WY_FloatingPoints = test_WY_Universal(PTH_PRIMITIVES(), 'floating_points'); fprintf('.'); stat.test_WY_Indentation = test_WY_Universal(PTH_PRIMITIVES(), 'indentation'); fprintf('.'); stat.test_WY_SequenceMapping = test_WY_Universal(PTH_PRIMITIVES(), 'sequence_mapping'); fprintf('.'); stat.test_WY_Simple = test_WY_Universal(PTH_PRIMITIVES(), 'simple'); fprintf('.'); stat.test_WY_Time = test_WY_Universal(PTH_PRIMITIVES(), 'time'); fprintf('.'); stat.test_WY_ComplexStructure = test_WY_Universal(PTH_IMPORT(), 'import'); fprintf('.'); stat.test_WY_usecase_01 = test_WY_Universal(PTH_PRIMITIVES(), 'usecase_struct_01'); fprintf('.\n'); catch stat.ok = 0; stat.desc = 'Program crash'; end end function result = PTH_PRIMITIVES() result = sprintf('Data%stest_primitives%s',filesep,filesep); end function result = PTH_IMPORT() result = sprintf('Data%stest_import%s',filesep,filesep); end function result = PTH_INHERITANCE() result = sprintf('Data%stest_inheritance%s',filesep,filesep); end function stat = test_WY_Universal(path, filename) stat.ok = 1; stat.desc = ''; try data = load([path, filesep, filename, '.mat']); WriteYaml('~temporary.yaml',data.testval); ry = ReadYaml('~temporary.yaml'); if ~isequalwithequalnans(ry, data.testval) stat.desc = 'Wrong values loaded'; stat.ok = 0; end; catch stat.ok = 0; stat.desc = 'Crash'; end; end
github
jacksky64/imageProcessing-master
dirPlus.m
.m
imageProcessing-master/dirPlus/dirPlus.m
11,958
utf_8
457bfd9e6ab55181cc8c367f5e9f417a
function output = dirPlus(rootPath, varargin) %dirPlus Recursively collect files or directories within a folder. % LIST = dirPlus(ROOTPATH) will search recursively through the folder % tree beneath ROOTPATH and collect a cell array LIST of all files it % finds. The list will contain the absolute paths to each file starting % at ROOTPATH. % % LIST = dirPlus(ROOTPATH, 'PropertyName', PropertyValue, ...) will % modify how files and directories are selected, as well as the format of % LIST, based on the property/value pairs specified. Valid properties % that the user can set are: % % GENERAL: % 'Struct' - A logical value determining if the output LIST should % instead be a structure array of the form returned by % the DIR function. If TRUE, LIST will be an N-by-1 % structure array instead of a cell array. % 'Depth' - A non-negative integer value for the maximum folder % tree depth that dirPlus will search through. A value % of 0 will only search in ROOTPATH, a value of 1 will % search in ROOTPATH and its subfolders, etc. Default % (and maximum allowable) value is the current % recursion limit set on the root object (i.e. % get(0, 'RecursionLimit')). % 'ReturnDirs' - A logical value determining if the output will be a % list of files or subdirectories. If TRUE, LIST will % be a cell array of subdirectory names/paths. Default % is FALSE. % 'PrependPath' - A logical value determining if the full path from % ROOTPATH to the file/subdirectory is prepended to % each item in LIST. The default TRUE will prepend the % full path, otherwise just the file/subdirectory name % is returned. This setting is ignored if the 'Struct' % argument is TRUE. % % FILE-SPECIFIC: % 'FileFilter' - A string defining a regular-expression pattern % that will be applied to the file name. Only files % matching the pattern will be included in LIST. % Default is '' (i.e. all files are included). % 'ValidateFileFcn' - A handle to a function that takes as input a % structure of the form returned by the DIR % function and returns a logical value. This % function will be applied to all files found and % only files that have a TRUE return value will be % included in LIST. Default is [] (i.e. all files % are included). % % DIRECTORY-SPECIFIC: % 'DirFilter' - A string defining a regular-expression pattern % that will be applied to the subdirectory name. % Only subdirectories matching the pattern will be % considered valid (i.e. included in LIST themselves % or having their files included in LIST). Default % is '' (i.e. all subdirectories are valid). The % setting of the 'RecurseInvalid' argument % determines if invalid subdirectories are still % recursed down. % 'ValidateDirFcn' - A handle to a function that takes as input a % structure of the form returned by the DIR function % and returns a logical value. This function will be % applied to all subdirectories found and only % subdirectories that have a TRUE return value will % be considered valid (i.e. included in LIST % themselves or having their files included in % LIST). Default is [] (i.e. all subdirectories are % valid). The setting of the 'RecurseInvalid' % argument determines if invalid subdirectories are % still recursed down. % 'RecurseInvalid' - A logical value determining if invalid % subdirectories (as identified by the 'DirFilter' % and 'ValidateDirFcn' arguments) should still be % recursed down. Default is FALSE (i.e the recursive % searching stops at invalid subdirectories). % % Examples: % % 1) Find all '.m' files: % % fileList = dirPlus(rootPath, 'FileFilter', '\.m$'); % % 2) Find all '.m' files, returning the list as a structure array: % % fileList = dirPlus(rootPath, 'Struct', true, ... % 'FileFilter', '\.m$'); % % 3) Find all '.jpg', '.png', and '.tif' files: % % fileList = dirPlus(rootPath, 'FileFilter', '\.(jpg|png|tif)$'); % % 4) Find all '.m' files in the given folder and its subfolders: % % fileList = dirPlus(rootPath, 'Depth', 1, 'FileFilter', '\.m$'); % % 5) Find all '.m' files, returning only the file names: % % fileList = dirPlus(rootPath, 'FileFilter', '\.m$', ... % 'PrependPath', false); % % 6) Find all '.jpg' files with a size of more than 1MB: % % bigFcn = @(s) (s.bytes > 1024^2); % fileList = dirPlus(rootPath, 'FileFilter', '\.jpg$', ... % 'ValidateFcn', bigFcn); % % 7) Find all '.m' files contained in folders containing the string % 'addons', recursing without restriction: % % fileList = dirPlus(rootPath, 'DirFilter', 'addons', ... % 'FileFilter', '\.m$', ... % 'RecurseInvalid', true); % % See also dir, regexp. % Author: Ken Eaton % Version: MATLAB R2016b % Last modified: 3/21/17 % Copyright 2017 by Kenneth P. Eaton %-------------------------------------------------------------------------- % Create input parser (only have to do this once, hence the use of a % persistent variable): persistent parser if isempty(parser) recursionLimit = get(0, 'RecursionLimit'); parser = inputParser(); parser.FunctionName = 'dirPlus'; parser.PartialMatching = true; % Add general parameters: addRequired(parser, 'rootPath', ... @(s) validateattributes(s, {'char'}, {'nonempty'})); addParameter(parser, 'Struct', false, ... @(b) validateattributes(b, {'logical'}, {'scalar'})); addParameter(parser, 'Depth', recursionLimit, ... @(s) validateattributes(s, {'numeric'}, ... {'scalar', 'nonnegative', ... 'nonnan', 'integer', ... '<=', recursionLimit})); addParameter(parser, 'ReturnDirs', false, ... @(b) validateattributes(b, {'logical'}, {'scalar'})); addParameter(parser, 'PrependPath', true, ... @(b) validateattributes(b, {'logical'}, {'scalar'})); % Add file-specific parameters: addParameter(parser, 'FileFilter', '', ... @(s) validateattributes(s, {'char'}, {'row'})); addParameter(parser, 'ValidateFileFcn', [], ... @(f) validateattributes(f, {'function_handle'}, ... {'scalar'})); % Add directory-specific parameters: addParameter(parser, 'DirFilter', '', ... @(s) validateattributes(s, {'char'}, {'row'})); addParameter(parser, 'ValidateDirFcn', [], ... @(f) validateattributes(f, {'function_handle'}, ... {'scalar'})); addParameter(parser, 'RecurseInvalid', false, ... @(b) validateattributes(b, {'logical'}, {'scalar'})); end % Parse input and recursively find contents: parse(parser, rootPath, varargin{:}); output = dirPlus_core(parser.Results.rootPath, ... rmfield(parser.Results, 'rootPath'), 0, true); if parser.Results.Struct output = vertcat(output{:}); end end %~~~Begin local functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ %-------------------------------------------------------------------------- % Core recursive function to find files and directories. function output = dirPlus_core(rootPath, optionStruct, depth, isValid) % Get current directory contents: rootData = dir(rootPath); dirIndex = [rootData.isdir]; subDirs = {}; validIndex = []; % Find valid subdirectories, only if necessary: if (depth < optionStruct.Depth) || optionStruct.ReturnDirs % Get subdirectories, not counting current or parent: dirData = rootData(dirIndex); subDirs = {dirData.name}.'; index = ~ismember(subDirs, {'.', '..'}); dirData = dirData(index); subDirs = subDirs(index); validIndex = true(size(subDirs)); if any(validIndex) % Apply directory name filter, if specified: nameFilter = optionStruct.DirFilter; if ~isempty(nameFilter) validIndex = ~cellfun(@isempty, regexp(subDirs, nameFilter)); end if any(validIndex) % Apply validation function to the directory list, if specified: validateFcn = optionStruct.ValidateDirFcn; if ~isempty(validateFcn) validIndex(validIndex) = arrayfun(validateFcn, ... dirData(validIndex)); end end end end % Determine if files or subdirectories are being returned: if optionStruct.ReturnDirs % Return directories % Use structure data or prepend full path, if specified: if optionStruct.Struct output = {dirData(validIndex)}; elseif any(validIndex) && optionStruct.PrependPath output = fullfile(rootPath, subDirs(validIndex)); else output = subDirs(validIndex); end elseif isValid % Return files % Find all files in the current directory: fileData = rootData(~dirIndex); output = {fileData.name}.'; if ~isempty(output) % Apply file name filter, if specified: fileFilter = optionStruct.FileFilter; if ~isempty(fileFilter) filterIndex = ~cellfun(@isempty, regexp(output, fileFilter)); fileData = fileData(filterIndex); output = output(filterIndex); end if ~isempty(output) % Apply validation function to the file list, if specified: validateFcn = optionStruct.ValidateFileFcn; if ~isempty(validateFcn) validateIndex = arrayfun(validateFcn, fileData); fileData = fileData(validateIndex); output = output(validateIndex); end % Use structure data or prepend full path, if specified: if optionStruct.Struct output = {fileData}; elseif ~isempty(output) && optionStruct.PrependPath output = fullfile(rootPath, output); end end end else % Return nothing output = {}; end % Check recursion depth: if (depth < optionStruct.Depth) % Select subdirectories to recurse down: if ~optionStruct.RecurseInvalid subDirs = subDirs(validIndex); validIndex = validIndex(validIndex); end % Recursively collect output from subdirectories: nSubDirs = numel(subDirs); if (nSubDirs > 0) subDirs = fullfile(rootPath, subDirs); output = {output; cell(nSubDirs, 1)}; for iSub = 1:nSubDirs output{iSub+1} = dirPlus_core(subDirs{iSub}, optionStruct, ... depth+1, validIndex(iSub)); end output = vertcat(output{:}); end end end %~~~End local functions~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
github
jacksky64/imageProcessing-master
main_FiltImage.m
.m
imageProcessing-master/poissonEditing/src/main_FiltImage.m
10,390
utf_8
a37410e03ca5b2e0d87897afdf432515
% ============================================================ % % Poisson image editing % ------------------------------------------------------------ % % FiltImage(Im, Solver, Mode, OutIm, AdditionalParameters) % inputs: % - Im > input image e.g 'dog.png' % - Solver> String containing 'I' or 'II', % I: solves the problem by mixing background and object % gradients and solving poisson equation over the entire % domain (using fourier properties) and imposing neumann % border conditions (see [Morel et al. 2012]). % II: solver the problem by inserting object gradients inside % omega and then integrating inside this region using % dirichlet border conditions, (see [Perez et al. 2003]). % - Mode > This string indicates which kind of experiment we want to do: % <> 'Flattening' Set small gradients to zero. % <> 'Enhancement' Increase the gradients of the regions of % the dark regions of the image. % - OutIm > File name of the output image, e.g. 'out.png'. % - Param > Additional parameters (depending on the 'Mode'). % <> Mode = 'Flattening' => Param = 'th'. [def 10] % if |GradI|<th is set to 0.% % <> Mode = 'Enhancement' => Param = 'th' 'alpha'. [def 50 2.5] % if |I|<th, GradI = alpha*GradI. % % ------------------------------------------------------------ % % Reference: % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis. % "Poisson Image Image Editing", Image Processing On Line IPOL, % 2015. % % ------------------------------------------------------------ % % Other relevant refs: % [Perez et al. 2003] % Pérez, P., Gangnet, M., & Blake, A. (2003). % Poisson image editing. ACM Transactions on Graphics, 22(3). % [Morel et al. 2012] % Morel, J. M., Petro, a. B., & Sbert, C. (2012). % Fourier implementation of Poisson image editing. % Pattern Recognition Letters, 33(3), 342–348. % [Limare et al. 2011] % Nicolas Limare, Jose-Luis Lisani, Jean-Michel Morel, Ana % Belén Petro, and Catalina Sbert, Simplest Color Balance, % Image Processing On Line, 1 (2011). % http://dx.doi.org/10.5201/ipol.2011.llmps-scb % ------------------------------------------------------------ % % copyright (c) 2015, % Matias Di Martino <[email protected]> % Gabriele Facciolo <[email protected]> % Enric Meinhardt <[email protected]> % % Licence: This code is released under the AGPL version 3. % Please see file LICENSE.txt for details. % ------------------------------------------------------------ % % Comments and suggestions are welcome at: [email protected] % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis % Paris 9/2015 % ============================================================ % function main_FiltImage( input_image_filename, ... solver, ... mode, ... out_image_filename, ... varargin) % ============================================ % % = Read inputs = % % ============================================ % addpath lib global verbose, verbose = 1; % for debugging % Read input images, Iin = imread(input_image_filename); % read input image % -------------------------------------------- % % - Display Exp Parameters and inputs - % % -------------------------------------------- % if verbose>0, c = clock; fprintf('====================================\n' ) fprintf('Experiment parameters: \n' ) fprintf('date: %4.0f-%02.0f-%02.0f (%02.0f:%02.0f) \n', ... c(1),c(2),c(3),c(4),c(5) ) fprintf('------------------------------------\n' ) fprintf(['background im > ' input_image_filename ' \n'] ) fprintf( 'verbose > %2.0d \n', verbose ) fprintf(['Solver > ' solver ' \n'] ) fprintf(['Mode > ' mode ' \n'] ) if nargin>4, fprintf(['Addit. par. 1 > ' varargin{1} ' \n'] ) if nargin>5, fprintf(['Addit. par. 2 > ' varargin{2} ' \n'] ) end end fprintf('====================================\n' ) clear c; end % (0) Compute Image gradient map, switch solver case 'I', Diff_Method = 'Fourier'; case 'II', Diff_Method = 'Backward'; otherwise error('Type unknown'), end G = ComputeGradient(Iin,Diff_Method); % ============================================ % % = (I) Modify the gradient map according = % % = to mode = % % ============================================ % switch lower(mode), % ---------------------------------------------------- % case 'flattening', % - % % ---------------------------------------------------- % if nargin>4, th = str2double(varargin{1}); % read input par, else % set default value, th = 10; end % find the portion of the image with low gradients, Omega = sqrt( G.x .^ 2 + G.y .^ 2 ) < th; % Set as 0 the gradients inside Omega, G.x(Omega==1) = 0; G.y(Omega==1) = 0; % ---------------------------------------------------- % case 'enhancement', % - % % ---------------------------------------------------- % if nargin>4, th = str2double(varargin{1}); % read input par, else % set default value, th = 50; end if nargin>5, alpha = str2double(varargin{2}); % read input par, else % set default value, alpha = 2.5; end % find the portion of the image with low intensity, Omega = Iin < th; % Amplification factor with smooth transition, % (i) First define a sigmoid func s = @(x) (alpha-1)*(1./(1+exp(-20*x+15)))+1; % [ s(0.5) ~ 1, s(1) ~ alpha with a smooth transition, ] % (ii) Now have smooth version of Omega to have a measure of the % distance of each point to the boundary, K = fspecial('Gaussian',[5 5],3); SmOmega = zeros(size(Omega)); % mem preloc. for c = 1:size(Omega,3), SmOmega(:,:,c) = conv2(double(Omega(:,:,c)),K,'same'); end % SmOmega is a image in the range [0,1] where pixels inside Omega % far from the boundary will have values arround 1, pixels outside % Omega far from the boundary will have values arround 0, and % finnaly pixels near the border will have a smooth transition % between 0 and 1. alphaMap = s(SmOmega); % Then the sigmoid mappinf "s" is applied to SmOmega, so values % arround SmOmega~0.5 have an amplification factor of 1 (the % grandient is preserved near the boundary), and values in the % interior of Omega are smoothly amplified with amplification % factor alpha. % Amplify the gradients in the dark areas G.x(Omega==1) = alphaMap(Omega==1).*G.x(Omega==1); G.y(Omega==1) = alphaMap(Omega==1).*G.y(Omega==1); otherwise, error('Unknown "mode" ') end % ============================================ % % = (II) Solve Poisson Equation = % % ============================================ % tic; switch solver, case 'I', I = SolvePoissonEq_I (G.x,G.y); case 'II', I = SolvePoissonEq_II(G.x,G.y,Omega,Iin); otherwise error('Type unknown'), end time = toc; if verbose>0, mt_printtime(time); end % ============================================ % % = (III) Normalize and adjust output = % % = dynamic range = % % ============================================ % switch lower(mode), % ---------------------------------------------------- % case 'flattening', % - % % ---------------------------------------------------- % % When we use Fourier solvers (e.i. SoilvePoissonEq_I) we need to % arbitrary set the DC component of the integrated gradient map (as no % dirichlet boundary conditions are imposed). In order to have and % output that can be easily compared with the input image, we set mean % and std of the output to match the input I = MatchMeanAndStd(I,Iin); % ---------------------------------------------------- % case 'enhancement', % - % % ---------------------------------------------------- % % When performing ehancement, we normalize Poisson result using % simple color balance to use all the dynamic range (as the % modification of the gradient field modifies the dynamic range of the % image and may produce saturation). s_low = 1; s_high = 1; % set the percentage of pix. we may saturate % see ref. [Limare et al. 2011] for a more complete descrition of this % normalization procedure. I = normalize(I,[0 255]); I = SimpleColorBalance(I,s_low,s_high); % Hist. equalization, % --------------------------------------------- % % - Computation of additional outputs. (Just - % % - for comparision with poisson results) - % % --------------------------------------------- % % (1) Input image with the same Simplest Color Balance. Iin_norm = SimpleColorBalance(Iin,s_low,s_high); imwrite(uint8(Iin_norm),'Iin_equalized.png'); % (2) Input image with a direct mapping of the intensity values, % Define an equivalent mapping, h = @(U,tau,alpha) ... (U<tau) .* ( 255 / ( 255+(alpha-1)*tau ) * alpha .* U ) ... + (U>=tau).* ( 255 / ( 255+(alpha-1)*tau ).* (U+(alpha-1)*tau) ); I_map = h(double(Iin),th,alpha); I_map = SimpleColorBalance(I_map,s_low,s_high); imwrite(uint8(I_map),'Iin_withDirectMapping.png'); end imwrite(uint8(I),out_image_filename); % save the output image, imwrite(uint8(255*Omega),'trimap.png'); % save the selected domain omega, end %function main %
github
jacksky64/imageProcessing-master
main_SeamlessCloning.m
.m
imageProcessing-master/poissonEditing/src/main_SeamlessCloning.m
8,789
utf_8
b7b37149c2e289f5676d40cd3622d481
% ============================================================ % % Poisson image editing % ------------------------------------------------------------ % % main_SeamlessCloning(BackIm, ObjIm, Omega, x0, y0, Solv, Mode, OutIm) % inputs: % - BackgroundIm > background image filename, e.g. 'Sunset.png' % - ObjIm > Object image filena, e.g. 'Sailboat.png' % - Omega > Binary image containing the mask over the object image % must be of the same size of ObjIm. % - x0, y0 > Location of the object in the reference system of the % background image. e.g. ['100' '230'] % - Solver > String containing 'I' or 'II', % I: solves the problem by mixing background and object % gradients and solving poisson equation over the entire % domain (using fourier properties) and imposing neumann % border conditions (see [Morel et al. 2012]). % II: solver the problem by inserting object gradients inside % omega and then integrating inside this region using % dirichlet border conditions, (see [Perez et al. 2003]). % - Mode > This string indicates which kind of experiment we want to do: % 'Replace' Just insert the gradients of the "object" inside % omega. % 'Max' Keep the higher gradinet between the object and % the background. % 'Average' Average Obj. and Back. gradients. % 'Sum' Sum Obj. and Back. gradients. % - OutIm > File name of the output image, e.g. 'out.png' % % ------------------------------------------------------------ % % Reference: % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis. % "Poisson Image Image Editing", Image Processing On Line IPOL, % 2015. % % ------------------------------------------------------------ % % Other relevants refs: % [Perez et al. 2003] % Pérez, P., Gangnet, M., & Blake, A. (2003). % Poisson image editing. ACM Transactions on Graphics, 22(3). % [Morel et al. 2012] % Morel, J. M., Petro, a. B., & Sbert, C. (2012). % Fourier implementation of Poisson image editing. % Pattern Recognition Letters, 33(3), 342–348. % ------------------------------------------------------------ % % copyright (c) 2015, % Matias Di Martino <[email protected]> % Gabriele Facciolo <[email protected]> % Enric Meinhardt <[email protected]> % % Licence: This code is released under the AGPL version 3. % Please see file LICENSE.txt for details. % ------------------------------------------------------------ % % Comments and sugestions are welcome at: [email protected] % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis % Paris 9/2015 % ============================================================ % function main_SeamlessCloning( background_image_filename, ... object_image_filename, ... omega_image_filename, ... x0, y0, ... solver, ... mode, ... out_image_filename) % ============================================ % % = Read inputs = % % ============================================ % addpath lib global verbose, verbose = 1; % for debugging % Read input images, BIm = double(imread(background_image_filename)); % read Background image [H ,W ,C] = size(BIm); % read ObjIm (to be inserted) OIm0 = imread(object_image_filename); [Ho,Wo,Co] = size(OIm0); % read the mask image with the area of interest, Omega0 = imread(omega_image_filename); Omega0 = Omega0==max(Omega0(:)); % Replicate the inputs if some of them is a gray image if Co==1, OIm0 = cat(3,OIm0,OIm0,OIm0); Co =3; end if C==1 , BIm = cat(3,BIm,BIm,BIm); C=3; end if size(Omega0,3) == 1, Omega0 = cat(3,Omega0,Omega0,Omega0); end % Sanity check: If the object we are inserting is larger than the % background image, truncate the object image. if Ho>H || Wo>W, % Bring the region of interest to the center of the image, [X,Y] = meshgrid(1:Wo,1:Ho); g_Omega0 = mean(Omega0,3); x_min = max(1, min(X(g_Omega0(:)==1))-3 ); y_min = max(1, min(Y(g_Omega0(:)==1))-3 ); Omega0 = circshift( Omega0, round([1-y_min 1-x_min]) ); OIm0 = circshift( OIm0, round([1-y_min 1-x_min]) ); % then, truncate the object image and the mask omega, Omega0 = Omega0(1:min(H,Ho),1:min(W,Wo),:); OIm0 = OIm0(1:min(H,Ho),1:min(W,Wo),:); % update the size, [Ho,Wo,~] = size(OIm0); clear g_Omega0 x_min y_min end % Create new images Omega and OIm with the same size of BIm -- Omega = zeros(H,W,C); OIm = zeros(H,W,C); Omega(1:Ho,1:Wo,:) = Omega0; Omega0 = mean(Omega0,3); OIm(1:Ho,1:Wo,:) = OIm0; [X,Y] = meshgrid(1:Wo,1:Ho); xg = mean(X(Omega0(:)==1)); yg = mean(Y(Omega0(:)==1)); x0 = str2double(x0); y0 = str2double(y0); Omega = circshift( Omega, round([y0-yg x0-xg]) ); OIm = circshift( OIm, round([y0-yg x0-xg]) ); clear xg yg X Y Omega0 OIm0 % ------------------------------------------------------------ if verbose>1, imwrite(uint8(normalize(Omega,[0 255])),'Omega.png'), end % -------------------------------------------- % % - Display Exp Parameters and inputs - % % -------------------------------------------- % % print a aux file showing the result of just copy and paste, aux = BIm; aux(Omega==1) = OIm(Omega==1); imwrite(uint8(aux),'output_2.png'); clear aux; if verbose>0, c = clock; fprintf('====================================\n' ) fprintf('Experiment parameters: \n' ) fprintf('date: %4.0f-%02.0f-%02.0f (%02.0f:%02.0f) \n', ... c(1),c(2),c(3),c(4),c(5) ) fprintf('------------------------------------\n' ) fprintf(['background im > ' background_image_filename ' \n'] ) fprintf(['object im > ' object_image_filename ' \n'] ) fprintf(['omega im > ' omega_image_filename ' \n'] ) fprintf( '[x0 y0] > %3.0d,%3.0d \n', x0, y0 ) fprintf( 'verbose > %2.0d \n', verbose ) fprintf(['Solver > ' solver ' \n'] ) fprintf(['Mode > ' mode ' \n'] ) fprintf('====================================\n' ) clear c end % ============================================ % % = (I) First test, combine gradients and = % % = and solve poisson eq. = % % ============================================ % switch solver case 'I', Diff_Method = 'Fourier'; case 'II', Diff_Method = 'Backward'; otherwise error('Type unknown'), end Grad_BIm = ComputeGradient(BIm,Diff_Method); Grad_OIm = ComputeGradient(OIm,Diff_Method); % -------------------------------------------- % % - Combine gradients - % % -------------------------------------------- % G = CombineGradients(Grad_BIm, Grad_OIm, Omega, mode); clear Grad_OIm Grad_BIm % ============================================ % % = (II) Solve Poisson Equation = % % ============================================ % tic; switch solver, case 'I', I = SolvePoissonEq_I(G.x,G.y); % recover the mean values to keep image appearence and colors, % recall that the mean value is lost when the DC components of % Fourier transform are set to zero. BIm_outside_Omega = BIm.*(1-Omega); I_outside_Omega = I.*(1-Omega); for c = 1:C, % mean value of the input image, (outside Omega) input_mean_value = sum(sum(BIm_outside_Omega(:,:,c))) / ... sum(sum(1-Omega(:,:,c))); % mean value of the output image, (outside Omega) out_mean_value = sum(sum(I_outside_Omega(:,:,c))) /... sum(sum(1-Omega(:,:,c))); % Set the mean value, I(:,:,c) = I(:,:,c) - out_mean_value + input_mean_value; end clear c BIm_outsideOmega I_outsideOmega ... input_mean_value out_mean_value case 'II', I = SolvePoissonEq_II(G.x,G.y,Omega,BIm); otherwise error('Type unknown'), end time = toc; if verbose>0, mt_printtime(time); end, % Output imwrite(uint8(I),out_image_filename); end %function main
github
jacksky64/imageProcessing-master
CombineGradients.m
.m
imageProcessing-master/poissonEditing/src/lib/CombineGradients.m
3,194
utf_8
01cf9c44ea8f850e41ba65e78beba866
% ======================================================= % % G = CombineGradients(G_Background, G_Object, Omega, Mode) % ======================================================= % function G = CombineGradients(G_Ba, G_Ob, Omega, Mode) % Input, % - G_Ba: Struct that contains, G.x and G.y (HxWxC) images that % corresponds to the background partial derivative. % - G_Ob: Idem G_Ba but for the object we want to insert. % - Omega: (HxWxC) binary image defining the domain where the object % should be inserted. length(Omega==1) should be equal to the % length(Obj). % - Mode: % 'Replace', (def) G_Ba outside O = Omega U d_Omega and G_Ob inside. % 'Max' , G_Ba outside O and max{G_Ob,G_Ba} inside. % 'Average', G_Ba outside O and 1/2*(G_Ob+G_Ba) inside. % 'Sum', G_Ba outside O and G_Ob+G_Ba inside. % % Output, % - G: struct with the combination of the gradients. % % ------------------------------------------------------------ % % Reference: % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis. % "Poisson Image Image Editing", Image Processing On Line IPOL, % 2015. % % ------------------------------------------------------------ % % Other relevant refs: % [Perez et al. 2003] % Pérez, P., Gangnet, M., & Blake, A. (2003). % Poisson image editing. ACM Transactions on Graphics, 22(3). % [Morel et al. 2012] % Morel, J. M., Petro, a. B., & Sbert, C. (2012). % Fourier implementation of Poisson image editing. % Pattern Recognition Letters, 33(3), 342–348. % ------------------------------------------------------------ % % copyright (c) 2015, % Matias Di Martino <[email protected]> % Gabriele Facciolo <[email protected]> % Enric Meinhardt <[email protected]> % % Licence: This code is released under the AGPL version 3. % Please see file LICENSE.txt for details. % ------------------------------------------------------------ % % Comments and suggestions are welcome at: [email protected] % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis % Paris 9/2015 % ============================================================ % % We will modify the set O = Omega U d_Omega O = padarray(Omega,[1 1],0,'both'); O = circshift(O,[1 0]) | circshift(O,[-1 0]) ... | circshift(O,[0 1]) | circshift(O,[0 -1]); O = O(2:end-1,2:end-1,:); % O is the set of pixels in Omega U d_Omega, % init. G = G_Ba; switch Mode, case 'Replace', G.x(O==1) = G_Ob.x(O==1); G.y(O==1) = G_Ob.y(O==1); case 'Average', G.x(O==1) = 1/2 * (G_Ob.x(O==1) + G_Ba.x(O==1) ); G.y(O==1) = 1/2 * (G_Ob.y(O==1) + G_Ba.y(O==1) ); case 'Sum' G.x(O==1) = G_Ob.x(O==1) + G_Ba.x(O==1); G.y(O==1) = G_Ob.y(O==1) + G_Ba.y(O==1); case 'Max', Mask_x = abs(G_Ba.x(O==1)) > abs(G_Ob.x(O==1)); Mask_y = abs(G_Ba.y(O==1)) > abs(G_Ob.y(O==1)); G.x(O==1) = G_Ba.x(O==1).*Mask_x + G_Ob.x(O==1).*(1-Mask_x); G.y(O==1) = G_Ba.y(O==1).*Mask_y + G_Ob.y(O==1).*(1-Mask_y); otherwise, error('[CombineGradients] Mode Unknown') end % switch end % function
github
jacksky64/imageProcessing-master
SolvePoissonEq_II.m
.m
imageProcessing-master/poissonEditing/src/lib/SolvePoissonEq_II.m
6,186
utf_8
001ac8fb1fc43c7002d3d84f2804a1af
% ======================================================= % % I = SolvePoissonEq_II(G) % % ======================================================= % function I = SolvePoissonEq_II(gx,gy,Omega,F) % ------------------------------------------------------- % % Problem: Find the function I that satisfies % I_omega = argmin{ int_Omega |Grad(I) - G|^2 dOmega } (P1) % this problem leads to the E-L equation: % I_xx + I_yy = Gx_x + Gy_y (1) % with (dirichlet) border cond. % I(dOmega) = F(dOmega) % ------------------------------------------------------- % % Input, % - gx and gy: are (HxWxC) images containing x and y partial % derivatives % - Omega: (HxWxC) binary image containing 1/0 if x is/isn't in Omega. % - F: (HxWxC) "Background image". It is used to impose dirichlet % boundary conditions, i.e. I(dOmega) = F(dOmega); % % Output, % - I: (HxWxC) I = F outside Omega and the solution of poisson Eq. (1) % inside Omega. % % ------------------------------------------------------------ % % Reference: % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis. % "Poisson Image Image Editing", Image Processing On Line IPOL, % 2015. % % ------------------------------------------------------------ % % Other relevants refs: % [Perez et al. 2003] % P??rez, P., Gangnet, M., & Blake, A. (2003). % Poisson image editing. ACM Transactions on Graphics, 22(3). % [Morel et al. 2012] % Morel, J. M., Petro, a. B., & Sbert, C. (2012). % Fourier implementation of Poisson image editing. % Pattern Recognition Letters, 33(3), 342-348. % ------------------------------------------------------------ % % copyright (c) 2015, % Matias Di Martino <[email protected]> % Gabriele Facciolo <[email protected]> % Enric Meinhardt <[email protected]> % % Licence: This code is released under the AGPL version 3. % Please see file LICENSE.txt for details. % Complete % ------------------------------------------------------------ % % Comments and sugestions are welcome at: [email protected] % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis % Paris 9/2015 % ============================================================ % if size(gx,3)>1, I = zeros(size(gx)); % init for c = 1:3, % solve for each channel indep. I(:,:,c) = SolvePoissonEq_II(... gx(:,:,c),gy(:,:,c),Omega(:,:,c),F(:,:,c)); end else % solve the problem if the input is a single channel, % (from now on we can assume that images are HxWx1.) F = double(F); % ==================================================== % % = (o) Expand inputs to have Neumann Bound. Cond. = % % ==================================================== % % this is necessary just when Omega reaches the edge of % the background image. In that case we don't have pixels % to set dirichlet bord. cond., hence we impose neumann B.C. n_pad = 1; gx = padarray(gx,n_pad*[1 1 0],0); gy = padarray(gy,n_pad*[1 1 0],0); Omega = padarray(Omega,n_pad*[1 1 0],'symmetric'); F = padarray(F,n_pad*[1 1 0],'symmetric'); % ==================================================== % % = (i) Definitions = % % ==================================================== % [H,W] = size(gx); HW = H*W; % --------------------------------------------- % % -(i).a Define Dx, Dy and L matrices - % % --------------------------------------------- % % {d(U)/di}(:) = Di*U(:), i = x,y, % pad the image domain (S) with zeros N = (H+2)*(W+2); mask = zeros(H+2,W+2); mask(2:end-1,2:end-1) = 1; % pixels inside the domain S idxS = find(mask==1); % keep the index of Pixels in S. clear mask % define the dilated domain in order to restrict the definition of the % operators only to the concerned pixels. % The mask dOmega is the same size as mask dOmega = padarray(Omega,[1 1],0,'both'); dOmega = dOmega | circshift(dOmega,[1 0]) | circshift(dOmega,[-1 0]) ... | circshift(dOmega,[0 1]) | circshift(dOmega,[0 -1]); dOmega([1 end],:,:) = 0; dOmega(:,[1 end],:) = 0; %Keep the index of Pixels in Omega \cup partial Omega. idx = find(dOmega==1); % forward scheme, Dx = (sparse(idx,idx+(H+2),1,N,N) - sparse(idx,idx,1,N,N)); Dy = (sparse(idx,idx+1 ,1,N,N) - sparse(idx,idx,1,N,N)); L = sparse(idx,idx,-4,N,N) ... + sparse(idx,idx+1,1,N,N) ... + sparse(idx,idx-1,1,N,N) ... + sparse(idx,idx+(H+2),1,N,N) ... + sparse(idx,idx-(H+2),1,N,N); % Keep pixels inside S Dx = Dx(idxS,idxS); Dy = Dy(idxS,idxS); L = L(idxS,idxS); clear idx idxS N % Correct the weight for those pixels that lie in the borders of S, Dx = Dx - sparse(1:HW,1:HW,sum(Dx,2),HW,HW); Dy = Dy - sparse(1:HW,1:HW,sum(Dy,2),HW,HW); L = L - sparse(1:HW,1:HW,sum(L ,2),HW,HW); % --------------------------------------------- % % -(i).b Define M_Omega, M_dOmega - % % --------------------------------------------- % % M_Omega is a HWxHW matrix such that M_Omega*x has the value of x(:) if % lies in Omega and 0 otherwise M_Omega = sparse(1:HW,1:HW,Omega(:),HW,HW); % M_dOmega is a HWxHW matrix such that M_dOmega*x has the value of x(:) if % lies in dOmega and 0 otherwise dOmega = padarray(Omega,[1 1],0,'both'); dOmega = circshift(dOmega,[1 0]) | circshift(dOmega,[-1 0]) ... | circshift(dOmega,[0 1]) | circshift(dOmega,[0 -1]); dOmega = dOmega(2:end-1,2:end-1); dOmega(Omega==1) = 0; M_dOmega = sparse(1:HW,1:HW,dOmega(:),HW,HW); % ==================================================== % % = (ii) Build the system = % % ==================================================== % idx = find(Omega == 1); S = sparse(1:length(idx),idx,1,length(idx),HW); A = L*M_Omega; % keep as unknowns just the pixels that lies inside Omega A = S*A*S';% S*A corresponds to the rows of A that corresponds to px in Omega b = Dx*gx(:) + Dy*gy(:) - L*M_dOmega*F(:); b = S*b; x = A\b; I = F; I(Omega(:)==1) = x; % Remove the pixels added I = I(n_pad+1:end-n_pad,n_pad+1:end-n_pad); end end % function
github
jacksky64/imageProcessing-master
ComputeGradient.m
.m
imageProcessing-master/poissonEditing/src/lib/ComputeGradient.m
3,444
utf_8
bd1d03aeb86f6542fd37171344e32bd4
% ======================================================= % % GradF = ComputeGradient(F,Method) % % ======================================================= % function GradF = ComputeGradient(F,Method) % Input, % - F: (HxWxC) image (C=1 gray, C=3 color image) % - Method: [def = 'Fourier'] {'Forward','Backward,'Centered','Fourier'} % Output, % - GradF: struct where GradF.x -> (HxWxC) x-partial derivative of F % and GradF.y -> (HxWxC) y-partial derivative of F % % ------------------------------------------------------------ % % Reference: % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis. % "Poisson Image Image Editing", Image Processing On Line IPOL, % 2015. % % ------------------------------------------------------------ % % Other relevant refs: % [Perez et al. 2003] % Pérez, P., Gangnet, M., & Blake, A. (2003). % Poisson image editing. ACM Transactions on Graphics, 22(3). % [Morel et al. 2012] % Morel, J. M., Petro, a. B., & Sbert, C. (2012). % Fourier implementation of Poisson image editing. % Pattern Recognition Letters, 33(3), 342–348. % ------------------------------------------------------------ % % copyright (c) 2015, % Matias Di Martino <[email protected]> % Gabriele Facciolo <[email protected]> % Enric Meinhardt <[email protected]> % % Licence: This code is released under the AGPL version 3. % Please see file LICENSE.txt for details. % ------------------------------------------------------------ % % Comments and suggestions are welcome at: [email protected] % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis % Paris 9/2015 % ============================================================ % F = double(F); if isempty(Method), Method = 'Fourier'; end % def value, switch Method, case 'Forward', % -- x'(i) = x(i+1)-x(i) -- % GradF.x = [F(:,2:end,:)-F(:,1:end-1,:) 0*F(:,1,:)]; GradF.y = [F(2:end,:,:)-F(1:end-1,:,:); 0*F(1,:,:)]; case 'Backward', % -- x'(i) = x(i)-x(i-1) -- % GradF.x = [0*F(:,1,:) F(:,2:end,:)-F(:,1:end-1,:)]; GradF.y = [0*F(1,:,:); F(2:end,:,:)-F(1:end-1,:,:)]; case 'Centered', % -- x'(i) = (x(i+1)-x(i-1))/2 -- % GradF.x = 1/2 * [0*F(:,1,:) F(:,3:end,:)-F(:,1:end-2,:) 0*F(:,1,:)]; GradF.y = 1/2 * [0*F(1,:,:); F(3:end,:,:)-F(1:end-2,:,:); 0*F(1,:,:)]; case 'Fourier', % -- see e.g. [Morel et al. 2012] -- % % First Expand the domain and the image, F = [F F(:,end:-1:1,:)]; F = [F; F(end:-1:1,:,:)]; [H,W,C] = size(F); GradF.x = zeros(H,W,C); GradF.y = zeros(H,W,C); % initialization i = sqrt(-1); % imaginary unit, ft = @(U) fftshift(fft2(U)); % 2D-Fourier transform, ift = @(U) real(ifft2(ifftshift(U))); % inv. Fourier trans., [Jc,Ic] = meshgrid( 1:W , 1:H ); % define the spatial j0 = floor(W/2)+1; i0 = floor(H/2)+1; % frequencies domain Jc = Jc - j0; Ic = Ic - i0; % (center) for c = 1:C, GradF.x(:,:,c) = ift( (i*2*pi/W*Jc).*ft(F(:,:,c)) ); GradF.y(:,:,c) = ift( (i*2*pi/H*Ic).*ft(F(:,:,c)) ); end GradF.x = GradF.x(1:H/2,1:W/2,:); GradF.y = GradF.y(1:H/2,1:W/2,:); otherwise, % -- Display an error -- % error('[ComputeGradient] Method unknown') end end %function
github
jacksky64/imageProcessing-master
SolvePoissonEq_I.m
.m
imageProcessing-master/poissonEditing/src/lib/SolvePoissonEq_I.m
3,235
utf_8
393a84c514368a5031b9f92cb1ff7c91
% ======================================================= % % I = SolvePoissonEq_I(Gx,Gy) % % ======================================================= % function I = SolvePoissonEq_I(gx,gy) % ------------------------------------------------------------ % % Problem: Find the function I that satisfies % I = argmin{ int_Omega |Grad(I) - G|^2 dOmega } (P1) % this problem leads to the E-L equation: % I_xx + I_yy = Gx_x + Gy_y (1) % with neaumann border cond. on I i.e. % I_n = 0 on dOmega (n is the direction perp. to dOmega) % ------------------------------------------------------------ % % Input, % - G: Input gradient map. G is a struct that contains % x/y-patial derivative in the field G.x/y % (G.x/y is a (HxWxC) image). G can be computed % e.g. using ComputeGradient() % % Output, % - I: (HxWxC) solution of poisson Eq. (1) in the Freq. % domain. % ------------------------------------------------------------ % % Reference: % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis. % "Poisson Image Image Editing", Image Processing On Line IPOL, % 2015. % Other Refs: % [Perez et al. 2003] % Pérez, P., Gangnet, M., & Blake, A. (2003). % Poisson image editing. ACM Transactions on Graphics, 22(3). % [Morel et al. 2012] % Morel, J. M., Petro, a. B., & Sbert, C. (2012). % Fourier implementation of Poisson image editing. % Pattern Recognition Letters, 33(3), 342–348. % ------------------------------------------------------------ % % copyright (c) 2015, % Matias Di Martino <[email protected]> % Gabriele Facciolo <[email protected]> % Enric Meinhardt <[email protected]> % % Licence: This code is released under the AGPL version 3. % Please see file LICENSE.txt for details. % ------------------------------------------------------------ % % Comments and sugestions are welcome at: [email protected] % M. Di Martino, G. Facciolo and E. Meinhardt-Llopis % Paris 9/2015 % ============================================================ % I = zeros(size(gx)); % init. % Quadruplicate by symmetry the discrete domain and the % input gradient field G. % Extend input gradient field (assuming that the original function % g is even (g(-x) = g(x)) and hence it's derivative is an odd % function (g'(-x) = -g'(x)) gx = [gx -gx(:,end:-1:1,:)]; gx = [gx; gx(end:-1:1,:,:)]; gy = [gy; -gy(end:-1:1,:,:)]; gy = [gy gy(:,end:-1:1,:)]; [H,W,C] = size(gx); % Define frequency domain, [wx,wy] = meshgrid(1:W,1:H); wx0 = floor(W/2)+1; wy0 = floor(H/2)+1; % zero frec wx = wx - wx0; wy = wy - wy0; i = sqrt(-1); % imaginary unit ft = @(U) fftshift(fft2(U)); % define a shortcut for the Fourier tran. ift = @(U) real(ifft2(ifftshift(U))); % and it's inverse. for c = 1:C, Gx = gx(:,:,c); Gy = gy(:,:,c); FT_I = ( (i*2*pi*wx/W).*ft(Gx) + (i*2*pi*wy/H).*ft(Gy) ) ./ ... ( (i*2*pi*wx/W).^2 + (i*2*pi*wy/H).^2 ); FT_I(wy0,wx0) = 0; % set DC value (undefined in the previous div.) Aux = ift(FT_I); I(:,:,c) = Aux(1:H/2,1:W/2); % keep the original portion of the space, end end % function
github
jacksky64/imageProcessing-master
findiff3.m
.m
imageProcessing-master/vecdenoise3d/findiff3.m
903
utf_8
199829b233fd9bfe30c4758b69510536
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function [d1Fj,d2Fj,d3Fj]=findiff3(Fj,boundary_conditions); d1Fj = Fj - shiftmirror(Fj,[1 0 0],boundary_conditions); d2Fj = Fj - shiftmirror(Fj,[0 1 0],boundary_conditions); d3Fj = Fj - shiftmirror(Fj,[0 0 1],boundary_conditions);
github
jacksky64/imageProcessing-master
shiftmirror.m
.m
imageProcessing-master/vecdenoise3d/shiftmirror.m
1,373
utf_8
5d1e42fa481a63116aef98eaebfc8186
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function AFjo = shiftmirror(AFj,e,boundary_conditions); % AFjo = AFj[.-e] with boundary conditions applied. I = size(AFj); if boundary_conditions ~= 'mirror', error('not implemented'); end; s = abs(e(1)); if e(1) > 0, AFjo = cat(1,AFj(s:-1:1,:,:),AFj(1:end-s,:,:)); elseif e(1) < 0, AFjo = cat(1,AFj(s+1:end,:,:),AFj(end:-1:end-s+1,:,:)); end; s = abs(e(2)); if e(2) > 0, AFjo = cat(2,AFj(:,s:-1:1,:),AFj(:,1:end-s,:)); elseif e(2) < 0, AFjo = cat(2,AFj(:,s+1:end,:),AFj(:,end:-1:end-s+1,:)); end; s = abs(e(3)); if e(3) > 0, AFjo = cat(3,AFj(:,:,s:-1:1),AFj(:,:,1:end-s)); elseif e(3) < 0, AFjo = cat(3,AFj(:,:,s+1:end),AFj(:,:,end:-1:end-s+1)); end;
github
jacksky64/imageProcessing-master
fmin1.m
.m
imageProcessing-master/vecdenoise3d/fmin1.m
3,387
utf_8
8912e0b35f55070abdf22e2bf29ca655
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function [lmbest ctxt finished] = fmin1(obj,lmin,lmax,relerr,objerr,ctxt,singlestep) if ~( exist('ctxt','var') && isfield(ctxt,'dirty') && isfield(ctxt,'ombest') && isfield(ctxt,'lmbest') && isfield(ctxt','l') ) o = zeros(4,4); dirty = ones(4,4); ombest = inf; % l(1,:) = exp(linspace(log(lmin(1)),log(lmax(1)),4)); % l(2,:) = exp(linspace(log(lmin(2)),log(lmax(2)),4)); l(1,:) = linspace(lmin(1),lmax(1),4); l(2,:) = linspace(lmin(2),lmax(2),4); else o = ctxt.o; dirty = ctxt.dirty; ombest = ctxt.ombest; lmbest = ctxt.lmbest; l = ctxt.l; end; if ~exist('singlestep','var') singlestep = 0; end; finished = 0; while true fprintf('.'); o = evaldirty(obj,o,dirty,l); dirty = ones(4,4); [om imi] = min(o); [om imj] = min(om); imi=imi(imj); ogap = max(o(:))-min(o(:)); fprintf('imi,imj: %1.0f,%1.0f\n',imi,imj); if om < ombest ombest = om lmbest = [l(1,imi) l(2,imj)] end; lmin(1) = l(1,max(imi-1,1)); lmax(1) = l(1,min(imi+1,4)); o(1,:) = o(max(imi-1,1),:); o(4,:) = o(min(imi+1,4),:); dirty(1,:) = dirty(1,:) - .5; dirty(4,:) = dirty(4,:) - .5; switch imi case {1,4} l(1,:) = linspace(lmin(1),lmax(1),4); case 2 l(1,:) = [lmin(1) 0.618*lmin(1)+0.382*l(1,imi) l(1,imi) lmax(1)]; o(3,:) = o(imi,:); dirty(3,:) = dirty(3,:)-.5; case 3 l(1,:) = [lmin(1) l(1,imi) 0.618*l(1,imi)+0.382*lmax(1) lmax(1)]; o(2,:) = o(imi,:); dirty(2,:) = dirty(2,:)-.5; end; lmin(2) = l(2,max(imj-1,1)); lmax(2) = l(2,min(imj+1,4)); o(:,1) = o(:,max(imj-1,1)); o(:,4) = o(:,min(imj+1,4)); dirty(:,1) = dirty(:,1) - .5; dirty(:,4) = dirty(:,4) - .5; switch imj case {1,4} l(2,:) = linspace(lmin(2),lmax(2),4); case 2 l(2,:) = [lmin(2) 0.618*lmin(2)+0.382*l(2,imj) l(2,imj) lmax(2)]; o(:,3) = o(:,imj); dirty(:,3) = dirty(:,3)-.5; case 3 l(2,:) = [lmin(2) l(2,imj) 0.618*l(2,imj)+0.382*lmax(2) lmax(2)]; o(:,2) = o(:,imj); dirty(:,2) = dirty(:,2)-.5; end; ogap if ( ( log(abs(lmax(1))) - log(abs(lmin(1))) ) + ... ( log(abs(lmax(2))) - log(abs(lmin(2))) ) < 2*relerr ) && ... ( ogap < objerr ) finished = 1; break; end; if singlestep break; end; end; ctxt.o = o; ctxt.dirty = dirty; ctxt.ombest = ombest; ctxt.lmbest = lmbest; ctxt.l = l; function o = evaldirty(obj,oin,d,l) d o = oin; for i=1:size(d,1) for j=1:size(d,2) if d(i,j) > 0 fprintf('%1.0f,%1.0f ',i,j); o(i,j) = obj(l(1,i),l(2,j)); end; end; end; o
github
jacksky64/imageProcessing-master
AFproduct.m
.m
imageProcessing-master/vecdenoise3d/AFproduct.m
1,984
utf_8
7400183a2fe4cc1d57bb9313a8c3bc85
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function [AF1,AF2,AF3] = AFproduct(cinv,dinv,lambdaC,lambdaD,F1,F2,F3,epsilon) % this is slightly less efficient but cleaner [d1F1,d2F1,d3F1] = findiff3(F1,'mirror'); [d1F2,d2F2,d3F2] = findiff3(F2,'mirror'); [d1F3,d2F3,d3F3] = findiff3(F3,'mirror'); % curl part %CCF1 = lambdaC * (d2F1-d1F2 + d3F1-d1F3 + epsilon) ./ (cinv + epsilon); %CCF2 = lambdaC * (d1F2-d2F1 + d3F2-d2F3 + epsilon) ./ (cinv + epsilon); %CCF3 = lambdaC * (d1F3-d3F1 + d2F3-d3F2 + epsilon) ./ (cinv + epsilon); % CCFki tmp = lambdaC * (d2F1-d1F2 + epsilon/2) ./ (cinv + epsilon); CCF12 = tmp - shiftmirror(tmp,[0 -1 0],'mirror'); CCF21 = -tmp + shiftmirror(tmp,[-1 0 0],'mirror'); tmp = lambdaC * (d3F1-d1F3 + epsilon/2) ./ (cinv + epsilon); CCF13 = tmp - shiftmirror(tmp,[0 0 -1],'mirror'); CCF31 = -tmp + shiftmirror(tmp,[-1 0 0],'mirror'); tmp = lambdaC * (d3F2-d2F3 + epsilon/2) ./ (cinv + epsilon); CCF23 = tmp - shiftmirror(tmp,[0 0 -1],'mirror'); CCF32 = -tmp + shiftmirror(tmp,[0 -1 0],'mirror'); AF1 = CCF12 + CCF13; AF2 = CCF21 + CCF23; AF3 = CCF31 + CCF32; % div part DDFt = lambdaD * (d1F1 + d2F2 + d3F3 + epsilon) ./ (dinv + epsilon); AF1 = F1 + AF1 + DDFt - shiftmirror(DDFt,[-1 0 0],'mirror'); AF2 = F2 + AF2 + DDFt - shiftmirror(DDFt,[0 -1 0],'mirror'); AF3 = F3 + AF3 + DDFt - shiftmirror(DDFt,[0 0 -1],'mirror');
github
jacksky64/imageProcessing-master
sigmaNest.m
.m
imageProcessing-master/vecdenoise3d/sigmaNest.m
1,286
utf_8
77c3a80a332f8702b81f57ed9a0fa7ac
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function sigmaNe = sigmaNest(SIGMANEST) global P sigmaNe = zeros(3,3); H = P.Y1; H = (H(1:end-1,:,:) - H(2:end,:,:))/sqrt(2); H = (H(:,1:end-1,:) - H(:,2:end,:))/sqrt(2); H = (H(:,:,1:end-1) - H(:,:,2:end))/sqrt(2); sigmaNe(1,1) = mad(H(:),1)/0.6745; H = P.Y2; H = (H(1:end-1,:,:) - H(2:end,:,:))/sqrt(2); H = (H(:,1:end-1,:) - H(:,2:end,:))/sqrt(2); H = (H(:,:,1:end-1) - H(:,:,2:end))/sqrt(2); sigmaNe(2,2) = mad(H(:),1)/0.6745; H = P.Y3; H = (H(1:end-1,:,:) - H(2:end,:,:))/sqrt(2); H = (H(:,1:end-1,:) - H(:,2:end,:))/sqrt(2); H = (H(:,:,1:end-1) - H(:,:,2:end))/sqrt(2); sigmaNe(3,3) = mad(H(:),1)/0.6745;
github
jacksky64/imageProcessing-master
MSEest_GCV.m
.m
imageProcessing-master/vecdenoise3d/MSEest_GCV.m
1,246
utf_8
a90a0b21a5ef4a9dbc5f20b0ce08ba6d
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function MSEo = MSEest_GCV(lambda,PRINT_LEVEL,F1,F2,F3,sigma) global P epsi = 0.01*sigma; Npts = 3*prod(P.IY); lambdaC = lambda(1); lambdaD = lambda(2); % add noise N1 = randn(P.IY); N2 = randn(P.IY); N3 = randn(P.IY); [FN1,FN2,FN3] = vecdenoise3(P.Y1+epsi*N1,P.Y2+epsi*N2,P.Y3+epsi*N3,lambdaC,lambdaD,P.REG_p,P.SOLVER,PRINT_LEVEL); divNpts = (N1(:)'*(FN1(:)-F1(:))+N2(:)'*(FN2(:)-F2(:))+N3(:)'*(FN3(:)-F3(:)))/(Npts*epsi); MSEo = ((norm(P.Y1(:)-F1(:)).^2 + norm(P.Y2(:)-F2(:)).^2 + norm(P.Y3(:)-F3(:)).^2) / Npts) /(1-divNpts)^2-sigma^2; MSEo = 10 * log10(MSEo); end
github
jacksky64/imageProcessing-master
MSEest_SURE.m
.m
imageProcessing-master/vecdenoise3d/MSEest_SURE.m
1,279
utf_8
5754188fbd396ed8025272bd4994a942
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function MSEo = MSEest_SURE(lambda,PRINT_LEVEL,F1,F2,F3,sigma) global P sigma2 = sigma*sigma; %epsi = .01; epsi = .01*sigma; Npts = 3*prod(P.IY); lambdaC = lambda(1); lambdaD = lambda(2); % add noise N1 = randn(P.IY); N2 = randn(P.IY); N3 = randn(P.IY); [FN1,FN2,FN3] = vecdenoise3(P.Y1+epsi*N1,P.Y2+epsi*N2,P.Y3+epsi*N3,lambdaC,lambdaD,P.REG_p,P.SOLVER,PRINT_LEVEL); divNpts = (N1(:)'*(FN1(:)-F1(:))+N2(:)'*(FN2(:)-F2(:))+N3(:)'*(FN3(:)-F3(:)))/(Npts*epsi); MSEo = ((norm(P.Y1(:)-F1(:)).^2 + norm(P.Y2(:)-F2(:)).^2 + norm(P.Y3(:)-F3(:)).^2) / Npts) - sigma2 + 2*sigma2*divNpts; MSEo = 10 * log10(MSEo);
github
jacksky64/imageProcessing-master
MSEest.m
.m
imageProcessing-master/vecdenoise3d/MSEest.m
2,285
utf_8
614ddcbf1e795cc78a677330fb08f62a
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function MSEo = MSEest(ORACLE,lambda,PRINT_LEVEL,CONTINUE) global P if nargin < 4, CONTINUE = 0; end; lambdaC = lambda(1); lambdaD = lambda(2); if PRINT_LEVEL > 1, fprintf('\nlambdaC = %.3e, lambdaD = %.3e\n',lambdaC,lambdaD); elseif PRINT_LEVEL > 0, fprintf('lambdaC = %.3e, lambdaD = %.3e _',lambdaC,lambdaD); end; if CONTINUE && exist('P.F3','var'), [P.F1,P.F2,P.F3] = vecdenoise3(P.Y1,P.Y2,P.Y3,lambdaC,lambdaD,P.REG_p,P.SOLVER,PRINT_LEVEL,P.F1,P.F2,P.F3); else, [P.F1,P.F2,P.F3] = vecdenoise3(P.Y1,P.Y2,P.Y3,lambdaC,lambdaD,P.REG_p,P.SOLVER,PRINT_LEVEL); end; if PRINT_LEVEL > 1, fprintf('++ ORACLE ++\n'); elseif PRINT_LEVEL > 0, fprintf(' _'); end; switch ORACLE, case 'oracle', MSEo = 10 * log10(norm(P.Yt1(:)-P.F1(:)).^2 + norm(P.Yt2(:)-P.F2(:)).^2 + norm(P.Yt3(:)-P.F3(:)).^2) - 10*log10(3*prod(P.IY)); case 'none', MSEo = nan; case 'gcv', MSEo = MSEest_GCV(lambda,PRINT_LEVEL,P.F1,P.F2,P.F3,trace(P.sigmaNe)/3); % XXX for debugging only %MSEo_oracle = 10 * log10(norm(P.Yt1(:)-F1(:)).^2 + norm(P.Yt2(:)-F2(:)).^2 + norm(P.Yt3(:)-F3(:)).^2) - 10*log10(3*prod(P.IY)); %fprintf(' oracle = %f, GCV = %f',MSEo_oracle,MSEo); case 'sure', MSEo = MSEest_SURE(lambda,PRINT_LEVEL,P.F1,P.F2,P.F3,trace(P.sigmaNe)/3); % XXX for debugging only %MSEo_oracle = 10 * log10(norm(P.Yt1(:)-F1(:)).^2 + norm(P.Yt2(:)-F2(:)).^2 + norm(P.Yt3(:)-F3(:)).^2) - 10*log10(3*prod(P.IY)); %fprintf(' oracle = %f, SURE = %f',MSEo_oracle,MSEo); otherwise, error('not implemented.'); end; if PRINT_LEVEL > 0, fprintf(' MSEo = % -2.2f dB\n',MSEo); end;
github
jacksky64/imageProcessing-master
vecdenoise3.m
.m
imageProcessing-master/vecdenoise3d/vecdenoise3.m
3,724
utf_8
00fa793db67147d4a79bac1ea3791701
% Vector Field Denoising with DIV-CURL Regularization % % Author: Pouya Dehghani Tafti <[email protected]> % Biomedical Imaging Group, EPFL, Lausanne % http://bigwww.epfl.ch/ % % Dates: 08 Feb. 2012 (current release) % ?? Feb. 2011 (this implementation) % % References: % % P. D. Tafti and M. Unser, On regularized reconstruction of vector fields, % IEEE Trans. Image Process., vol. 20, no. 11, pp. 3163–78, 2011. % % P. D. Tafti, R. Delgado-Gonzalo, A. F. Stalder, and M. Unser, Variational % enhancement and denoising of flow field images, Proc. 8th IEEE Int. Symp. % Biomed. Imaging (ISBI 2011), pp. 1061–4, Chicago, IL, 2011. function [F1,F2,F3] = vecdenoise3(Y1,Y2,Y3,lambdaC,lambdaD,REG_p,SOLVER,PRINT_LEVEL,F1,F2,F3) % % function [F1,F2,F3] = vecdenoise3(Y1,Y2,Y3,lambdaC,lambdaD,REG_p,SOLVER,PRINT_LEVEL) % % REG_p == 1 -> L1 regularization, REG_p ==2 -> L2 regularization % SOLVER.outer_maxk, SOLVER.inner_maxk, SOLVER.inner_eps : iteration parameters % SOLVER.epsilon is added to numerators and denuminators to avoid division by zero IY = size(Y1); if nargin < 11, F1 = zeros(IY); F2 = zeros(IY); F3 = zeros(IY); end; % OUTER MM ITERATION ko = 0; while 1, % outer ko = ko + 1; if ko > SOLVER.outer_maxk, break; end; if PRINT_LEVEL > 1, fprintf('== %d ==\n',ko); elseif PRINT_LEVEL > 0, if mod(ko,10) == 0, fprintf('o'); else, fprintf('.'); end; end; % diffs [d1F1,d2F1,d3F1] = findiff3(F1,'mirror'); [d1F2,d2F2,d3F2] = findiff3(F2,'mirror'); [d1F3,d2F3,d3F3] = findiff3(F3,'mirror'); % div DF = d1F1 + d2F2 + d3F3; % curl CF1 = d3F2 - d2F3; CF2 = d1F3 - d3F1; CF3 = d2F1 - d1F2; if ko == 1, % zero initialization AF1 = F1; AF2 = F2; AF3 = F3; dinv = ones(size(AF1)); cinv = ones(size(AF1)); else, % weights switch REG_p, case 1, dinv = abs(DF); cinv = sqrt(CF1.^2 + CF2.^2 + CF3.^2); if PRINT_LEVEL > 1, fprintf('J[L1] in = %2.3f\n',norm(F1(:)-Y1(:))^2+norm(F2(:)-Y2(:))^2+norm(F3(:)-Y3(:))^2+lambdaC*sum(cinv(:))+lambdaD*sum(dinv(:))); end; case 2, dinv = 1; cinv = 1; otherwise, error('not implemented.'); end; % matrix-vector product [AF1,AF2,AF3] = AFproduct(cinv,dinv,lambdaC,lambdaD,F1,F2,F3,SOLVER.epsilon); end; % INNER CG ITERATION % local variables k r1,r2,r3,rr,rr_new p1,p2,p3,pAp alpha,beta r1 = Y1 - AF1; r2 = Y2 - AF2; r3 = Y3 - AF3; rr = r1(:)'*r1(:) + r2(:)'*r2(:) + r3(:)'*r3(:); p1 = r1; p2 = r2; p3 = r3; for ki=1:SOLVER.inner_maxk, % inner if PRINT_LEVEL > 1, if mod(ki,10) == 0, fprintf('o'); else, fprintf('.'); end; end; [Ap1,Ap2,Ap3] = AFproduct(cinv,dinv,lambdaC,lambdaD,p1,p2,p3,SOLVER.epsilon); pAp = p1(:)'*Ap1(:) + p2(:)'*Ap2(:) + p3(:)'*Ap3(:); alpha = rr/pAp; F1 = F1 + alpha*p1; F2 = F2 + alpha*p2; F3 = F3 + alpha*p3; r1 = r1 - alpha*Ap1; r2 = r2 - alpha*Ap2; r3 = r3 - alpha*Ap3; rr_new = r1(:)'*r1(:) + r2(:)'*r2(:) + r3(:)'*r3(:); beta = rr_new/rr; if sqrt(rr_new) < SOLVER.inner_eps, % fixme XXX replace by cond on beta break; end; p1 = r1 + beta*p1; p2 = r2 + beta*p2; p3 = r3 + beta*p3; rr = rr_new; end; %inner if PRINT_LEVEL > 1, fprintf(' (%d)\n',ki); end; end; % outer
github
jacksky64/imageProcessing-master
QC_signatures.m
.m
imageProcessing-master/QC/QC_signatures.m
4,365
utf_8
f04870a73e5c0cb3b6f451f4b7fa6998
% [dist]= QC_signatures(PF, QF, PW, QW, F_sim, m) % % Computes the Quadratic-Chi (QC) histogram distance between two % signatures (a convenient representation for sparse histograms). % QC distances are Quadratic-Form distances with a cross-bin % chi-squared-like normalization. This normalization reduces the effect of % large bins having undue influence. The Quadratic-Form part of QC takes care % of cross-bin relationships (e.g. red and orange). % % For more details on this distance see the paper: % The Quadratic-Chi Histogram Distance Family % Ofir Pele, Michael Werman % ECCV 2010 % Please cite the paper if you use this code. % % Output: % dist - the computed distance. % % Required Input: % PF - DxN matrix, where each column is a D-dimensional feature vector % of the first signature. % QF - DxM matrix, where each column is a D-dimensional feature vector. % of the second signature. % PW - 1xN or Nx1, weights of first signature. % QW - 1xM or Mx1, weights of second signature. % F_sim - a function (handle) that gets as an input two D-dimensional % feature vectors and returns the similarity between them. % m - The normalization factor (large m correspond to a large reduction of large bins effect). % In paper used 0.5 (QCS) or 0.9 (QCN). % Pre-condition: 0 <= m < 1, otherwise not continuous. % % % Time Complexity: % O((N+M)^2) * O(F_sim) % % Examples of usage: % See commented bottom of demo_QC2 and demo_QC3 function [dist]= QC_signatures(PF, QF, PW, QW, F_sim, m); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % sizes and asserts %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% D= size(PF,1); N= size(PF,2); assert(size(QF,1)==D); M= size(QF,2); assert(length(PW)==N); assert(length(QW)==M); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % P & Q %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (size(PW,1)==1) P= [PW, zeros(1,M)]; else P= [PW', zeros(1,M)]; end if (size(QW,1)==1) Q= [zeros(1,N), QW]; else P= [zeros(1,N), QW']; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % A %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% len= length(P); A= zeros(len, len); for i=1:N for j=1:N A(i,j)= F_sim(PF(:,i),PF(:,j)); end end for i=1:N for j=1:M d= F_sim(PF(:,i),QF(:,j)); A(i,j+N)= d; A(j+N,i)= d; end end for i=1:M for j=1:M A(i+N,j+N)= F_sim(QF(:,i),QF(:,j)); end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% dist= QC_full_full(P, Q, A, m); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Copyright (c) 2010, Ofir Pele % All rights reserved. % Redistribution and use in source and binary forms, with or without % modification, are permitted provided that the following conditions are % met: % * Redistributions of source code must retain the above copyright % notice, this list of conditions and the following disclaimer. % * Redistributions in binary form must reproduce the above copyright % notice, this list of conditions and the following disclaimer in the % documentation and/or other materials provided with the distribution. % * Neither the name of the The Hebrew University of Jerusalem nor the % names of its contributors may be used to endorse or promote products % derived from this software without specific prior written permission. % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS % IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, % THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR % PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR % CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, % EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, % PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR % PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF % LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING % NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS % SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
github
jacksky64/imageProcessing-master
struct2xml.m
.m
imageProcessing-master/str2xml/struct2xml.m
7,457
utf_8
24791efbc3f8e2ee07c5fc9e192b90c9
function varargout = struct2xml( s, varargin ) %Convert a MATLAB structure into a xml file % [ ] = struct2xml( s, file ) % xml = struct2xml( s ) % % A structure containing: % s.XMLname.Attributes.attrib1 = "Some value"; % s.XMLname.Element.Text = "Some text"; % s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2"; % s.XMLname.DifferentElement{1}.Text = "Some more text"; % s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2"; % s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1"; % s.XMLname.DifferentElement{2}.Text = "Even more text"; % % Will produce: % <XMLname attrib1="Some value"> % <Element>Some text</Element> % <DifferentElement attrib2="2">Some more text</Element> % <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement> % </XMLname> % % Please note that the following strings are substituted % '_dash_' by '-', '_colon_' by ':' and '_dot_' by '.' % % Written by W. Falkena, ASTI, TUDelft, 27-08-2010 % On-screen output functionality added by P. Orth, 01-12-2010 % Multiple space to single space conversion adapted for speed by T. Lohuis, 11-04-2011 % Val2str subfunction bugfix by H. Gsenger, 19-9-2011 if (nargin ~= 2) if(nargout ~= 1 || nargin ~= 1) error(['Supported function calls:' sprintf('\n')... '[ ] = struct2xml( s, file )' sprintf('\n')... 'xml = struct2xml( s )']); end end if(nargin == 2) file = varargin{1}; if (isempty(file)) error('Filename can not be empty'); end if (isempty(strfind(file,'.xml'))) file = [file '.xml']; end end if (~isstruct(s)) error([inputname(1) ' is not a structure']); end if (length(fieldnames(s)) > 1) error(['Error processing the structure:' sprintf('\n') 'There should be a single field in the main structure.']); end xmlname = fieldnames(s); xmlname = xmlname{1}; %substitute special characters xmlname_sc = xmlname; xmlname_sc = strrep(xmlname_sc,'_dash_','-'); xmlname_sc = strrep(xmlname_sc,'_colon_',':'); xmlname_sc = strrep(xmlname_sc,'_dot_','.'); %create xml structure docNode = com.mathworks.xml.XMLUtils.createDocument(xmlname_sc); %process the rootnode docRootNode = docNode.getDocumentElement; %append childs parseStruct(s.(xmlname),docNode,docRootNode,[inputname(1) '.' xmlname '.']); if(nargout == 0) %save xml file xmlwrite(file,docNode); else varargout{1} = xmlwrite(docNode); end end % ----- Subfunction parseStruct ----- function [] = parseStruct(s,docNode,curNode,pName) fnames = fieldnames(s); for i = 1:length(fnames) curfield = fnames{i}; %substitute special characters curfield_sc = curfield; curfield_sc = strrep(curfield_sc,'_dash_','-'); curfield_sc = strrep(curfield_sc,'_colon_',':'); curfield_sc = strrep(curfield_sc,'_dot_','.'); if (strcmp(curfield,'Attributes')) %Attribute data if (isstruct(s.(curfield))) attr_names = fieldnames(s.Attributes); for a = 1:length(attr_names) cur_attr = attr_names{a}; %substitute special characters cur_attr_sc = cur_attr; cur_attr_sc = strrep(cur_attr_sc,'_dash_','-'); cur_attr_sc = strrep(cur_attr_sc,'_colon_',':'); cur_attr_sc = strrep(cur_attr_sc,'_dot_','.'); [cur_str,succes] = val2str(s.Attributes.(cur_attr)); if (succes) curNode.setAttribute(cur_attr_sc,cur_str); else disp(['Warning. The text in ' pName curfield '.' cur_attr ' could not be processed.']); end end else disp(['Warning. The attributes in ' pName curfield ' could not be processed.']); disp(['The correct syntax is: ' pName curfield '.attribute_name = ''Some text''.']); end elseif (strcmp(curfield,'Text')) %Text data [txt,succes] = val2str(s.Text); if (succes) curNode.appendChild(docNode.createTextNode(txt)); else disp(['Warning. The text in ' pName curfield ' could not be processed.']); end else %Sub-element if (isstruct(s.(curfield))) %single element curElement = docNode.createElement(curfield_sc); curNode.appendChild(curElement); parseStruct(s.(curfield),docNode,curElement,[pName curfield '.']) elseif (iscell(s.(curfield))) %multiple elements for c = 1:length(s.(curfield)) curElement = docNode.createElement(curfield_sc); curNode.appendChild(curElement); if (isstruct(s.(curfield){c})) parseStruct(s.(curfield){c},docNode,curElement,[pName curfield '{' num2str(c) '}.']) else disp(['Warning. The cell ' pName curfield '{' num2str(c) '} could not be processed, since it contains no structure.']); end end else %eventhough the fieldname is not text, the field could %contain text. Create a new element and use this text curElement = docNode.createElement(curfield_sc); curNode.appendChild(curElement); [txt,succes] = val2str(s.(curfield)); if (succes) curElement.appendChild(docNode.createTextNode(txt)); else disp(['Warning. The text in ' pName curfield ' could not be processed.']); end end end end end %----- Subfunction val2str ----- function [str,succes] = val2str(val) succes = true; str = []; if (isempty(val)) return; %bugfix from H. Gsenger elseif (ischar(val)) %do nothing elseif (isnumeric(val)) val = num2str(val); else succes = false; end if (ischar(val)) %add line breaks to all lines except the last (for multiline strings) lines = size(val,1); val = [val char(sprintf('\n')*[ones(lines-1,1);0])]; %transpose is required since indexing (i.e., val(nonspace) or val(:)) produces a 1-D vector. %This should be row based (line based) and not column based. valt = val'; remove_multiple_white_spaces = true; if (remove_multiple_white_spaces) %remove multiple white spaces using isspace, suggestion of T. Lohuis whitespace = isspace(val); nonspace = (whitespace + [zeros(lines,1) whitespace(:,1:end-1)])~=2; nonspace(:,end) = [ones(lines-1,1);0]; %make sure line breaks stay intact str = valt(nonspace'); else str = valt(:); end end end
github
jacksky64/imageProcessing-master
xml2struct.m
.m
imageProcessing-master/str2xml/xml2struct.m
6,955
utf_8
58f0b998cc71b30b4a6a12b330cfe950
function [ s ] = xml2struct( file ) %Convert xml file into a MATLAB structure % [ s ] = xml2struct( file ) % % A file containing: % <XMLname attrib1="Some value"> % <Element>Some text</Element> % <DifferentElement attrib2="2">Some more text</Element> % <DifferentElement attrib3="2" attrib4="1">Even more text</DifferentElement> % </XMLname> % % Will produce: % s.XMLname.Attributes.attrib1 = "Some value"; % s.XMLname.Element.Text = "Some text"; % s.XMLname.DifferentElement{1}.Attributes.attrib2 = "2"; % s.XMLname.DifferentElement{1}.Text = "Some more text"; % s.XMLname.DifferentElement{2}.Attributes.attrib3 = "2"; % s.XMLname.DifferentElement{2}.Attributes.attrib4 = "1"; % s.XMLname.DifferentElement{2}.Text = "Even more text"; % % Please note that the following characters are substituted % '-' by '_dash_', ':' by '_colon_' and '.' by '_dot_' % % Written by W. Falkena, ASTI, TUDelft, 21-08-2010 % Attribute parsing speed increased by 40% by A. Wanner, 14-6-2011 % Added CDATA support by I. Smirnov, 20-3-2012 % % Modified by X. Mo, University of Wisconsin, 12-5-2012 if (nargin < 1) clc; help xml2struct return end if isa(file, 'org.apache.xerces.dom.DeferredDocumentImpl') || isa(file, 'org.apache.xerces.dom.DeferredElementImpl') % input is a java xml object xDoc = file; else %check for existance if (exist(file,'file') == 0) %Perhaps the xml extension was omitted from the file name. Add the %extension and try again. if (isempty(strfind(file,'.xml'))) file = [file '.xml']; end if (exist(file,'file') == 0) error(['The file ' file ' could not be found']); end end %read the xml file xDoc = xmlread(file); end %parse xDoc into a MATLAB structure s = parseChildNodes(xDoc); end % ----- Subfunction parseChildNodes ----- function [children,ptext,textflag] = parseChildNodes(theNode) % Recurse over node children. children = struct; ptext = struct; textflag = 'Text'; if hasChildNodes(theNode) childNodes = getChildNodes(theNode); numChildNodes = getLength(childNodes); for count = 1:numChildNodes theChild = item(childNodes,count-1); [text,name,attr,childs,textflag] = getNodeData(theChild); if (~strcmp(name,'#text') && ~strcmp(name,'#comment') && ~strcmp(name,'#cdata_dash_section')) %XML allows the same elements to be defined multiple times, %put each in a different cell if (isfield(children,name)) if (~iscell(children.(name))) %put existsing element into cell format children.(name) = {children.(name)}; end index = length(children.(name))+1; %add new element children.(name){index} = childs; if(~isempty(fieldnames(text))) children.(name){index} = text; end if(~isempty(attr)) children.(name){index}.('Attributes') = attr; end else %add previously unknown (new) element to the structure children.(name) = childs; if(~isempty(text) && ~isempty(fieldnames(text))) children.(name) = text; end if(~isempty(attr)) children.(name).('Attributes') = attr; end end else ptextflag = 'Text'; if (strcmp(name, '#cdata_dash_section')) ptextflag = 'CDATA'; elseif (strcmp(name, '#comment')) ptextflag = 'Comment'; end %this is the text in an element (i.e., the parentNode) if (~isempty(regexprep(text.(textflag),'[\s]*',''))) if (~isfield(ptext,ptextflag) || isempty(ptext.(ptextflag))) ptext.(ptextflag) = text.(textflag); else %what to do when element data is as follows: %<element>Text <!--Comment--> More text</element> %put the text in different cells: % if (~iscell(ptext)) ptext = {ptext}; end % ptext{length(ptext)+1} = text; %just append the text ptext.(ptextflag) = [ptext.(ptextflag) text.(textflag)]; end end end end end end % ----- Subfunction getNodeData ----- function [text,name,attr,childs,textflag] = getNodeData(theNode) % Create structure of node info. %make sure name is allowed as structure name name = toCharArray(getNodeName(theNode))'; name = strrep(name, '-', '_dash_'); name = strrep(name, ':', '_colon_'); name = strrep(name, '.', '_dot_'); attr = parseAttributes(theNode); if (isempty(fieldnames(attr))) attr = []; end %parse child nodes [childs,text,textflag] = parseChildNodes(theNode); if (isempty(fieldnames(childs)) && isempty(fieldnames(text))) %get the data of any childless nodes % faster than if any(strcmp(methods(theNode), 'getData')) % no need to try-catch (?) % faster than text = char(getData(theNode)); text.(textflag) = toCharArray(getTextContent(theNode))'; end end % ----- Subfunction parseAttributes ----- function attributes = parseAttributes(theNode) % Create attributes structure. attributes = struct; if hasAttributes(theNode) theAttributes = getAttributes(theNode); numAttributes = getLength(theAttributes); for count = 1:numAttributes %attrib = item(theAttributes,count-1); %attr_name = regexprep(char(getName(attrib)),'[-:.]','_'); %attributes.(attr_name) = char(getValue(attrib)); %Suggestion of Adrian Wanner str = toCharArray(toString(item(theAttributes,count-1)))'; k = strfind(str,'='); attr_name = str(1:(k(1)-1)); attr_name = strrep(attr_name, '-', '_dash_'); attr_name = strrep(attr_name, ':', '_colon_'); attr_name = strrep(attr_name, '.', '_dot_'); attributes.(attr_name) = str((k(1)+2):(end-1)); end end end
github
jacksky64/imageProcessing-master
Registration.m
.m
imageProcessing-master/LmRegistration/Registration.m
22,902
utf_8
3ffdabb779c0cebe002f96fc7d225a22
function varargout = Registration(varargin) % REGISTRATION MATLAB code for Registration.fig % REGISTRATION, by itself, creates a new REGISTRATION or raises the existing % singleton*. % % H = REGISTRATION returns the handle to a new REGISTRATION or the handle to % the existing singleton*. % % REGISTRATION('CALLBACK',hObject,eventData,handles,...) calls the local % function named CALLBACK in REGISTRATION.M with the given input arguments. % % REGISTRATION('Property','Value',...) creates a new REGISTRATION or raises the % existing singleton*. Starting from the left, property value pairs are % applied to the GUI before Registration_OpeningFcn gets called. An % unrecognized property name or invalid value makes property application % stop. All inputs are passed to Registration_OpeningFcn via varargin. % % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one % instance to run (singleton)". % % See also: GUIDE, GUIDATA, GUIHANDLES % Edit the above text to modify the response to help Registration % Last Modified by GUIDE v2.5 23-May-2012 10:01:44 % Begin initialization code - DO NOT EDIT gui_Singleton = 1; gui_State = struct('gui_Name', mfilename, ... 'gui_Singleton', gui_Singleton, ... 'gui_OpeningFcn', @Registration_OpeningFcn, ... 'gui_OutputFcn', @Registration_OutputFcn, ... 'gui_LayoutFcn', [] , ... 'gui_Callback', []); if nargin && ischar(varargin{1}) gui_State.gui_Callback = str2func(varargin{1}); end if nargout [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); else gui_mainfcn(gui_State, varargin{:}); end addpath('common'); addpath('output'); addpath('testdata'); % End initialization code - DO NOT EDIT % --- Executes just before Registration is made visible. function Registration_OpeningFcn(hObject, eventdata, handles, varargin) % This function has no output args, see OutputFcn. % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % varargin command line arguments to Registration (see VARARGIN) % Choose default command line output for Registration handles.output = hObject; % Update handles structure guidata(hObject, handles); % UIWAIT makes Registration wait for user response (see UIRESUME) % uiwait(handles.figure1); % --- Outputs from this function are returned to the command line. function varargout = Registration_OutputFcn(hObject, eventdata, handles) % varargout cell array for returning output args (see VARARGOUT); % hObject handle to figure % eventdata reserved - to be defined in a future version of MATLAB % handles structure with handles and user data (see GUIDATA) % Get default command line output from handles structure varargout{1} = handles.output; % --- Executes on button press in opensourceButton. function opensourceButton_Callback(hObject, eventdata, handles) %get source file [filename, pathname] = uigetfile({'*.png', 'PNG files (*.png)'; ... '*.jpg', 'JPEG files (*.jpg)'; ... '*.*', 'All files (*.*)'}, ... 'Choose a source image'); if isequal(filename,0) || isequal(pathname,0) disp('User pressed cancel') %warndlg('User pressed cancel'); else fullpath = fullfile(pathname, filename); disp(['User selected ', fullpath]); % display source file axes(handles.sourceAxes); handles.sourceImg = imread(fullpath); handles.sourcePath = fullpath; handles.cursourceImg = handles.sourceImg; %handles.cursourcedispImg = handles.cursourceImg; imshow(handles.cursourceImg); end guidata(hObject, handles); % --- Executes on button press in opentargetButton. function opentargetButton_Callback(hObject, eventdata, handles) % get target file [filename, pathname] = uigetfile({'*.png', 'PNG files (*.png)'; ... '*.jpg', 'JPEG files (*.jpg)'; ... '*.*', 'All files (*.*)'}, ... 'Choose a target image'); if isequal(filename,0) || isequal(pathname,0) disp('User pressed cancel') else fullpath = fullfile(pathname, filename); disp(['User selected ', fullpath]); % display target file axes(handles.targetAxes); handles.targetImg = imread(fullpath); handles.curtargetImg = handles.targetImg; handles.targetPath = fullpath; imshow(handles.curtargetImg); end guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function sourceAxes_CreateFcn(hObject, eventdata, handles) axis off; % test application data %matrices.rand_35 = randn(35); %setappdata(hObject,'mydata',matrices); % --- Executes during object creation, after setting all properties. function targetAxes_CreateFcn(hObject, eventdata, handles) axis off; % Hint: place code in OpeningFcn to populate targetAxes % --- Executes on button press in sourceinverseButton. function sourceinverseButton_Callback(hObject, eventdata, handles) % inverse the intensity if ~isfield(handles, 'cursourceImg'); %display('Open a source image first...'); warndlg('Open a source image first...'); else handles.cursourceImg = imcomplement(handles.cursourceImg); % display axes(handles.sourceAxes); imshow(handles.cursourceImg); end % update guidata guidata(hObject, handles); % --- Executes on button press in sourcethresholdButton. function sourcethresholdButton_Callback(hObject, eventdata, handles) % get threshold value %sourcethresholdVal = get(handles.sourcethresholdSlider, 'Value'); sourcethresholdVal = str2double(get(handles.sourcethresholdEdit, 'String')); if sourcethresholdVal>=0.0 && sourcethresholdVal <=1.0 set(handles.sourcethresholdSlider, 'Value', sourcethresholdVal); handles.cursrcThreshold = sourcethresholdVal; % binarization with given threshold if ~isfield(handles, 'cursourceImg'); %display('Open a source image first...'); warndlg('Open a source image first...'); else handles.bisrcImg = im2bw(handles.cursourceImg, sourcethresholdVal); % display axes(handles.sourceAxes); imshow(handles.bisrcImg); end else %display('Input a valid threshold(0-1)...'); warndlg('Input a valid threshold(0-1)...'); end % update guidata guidata(hObject, handles); % --- Executes on button press in srcextractchannelButton. function srcextractchannelButton_Callback(hObject, eventdata, handles) if ~isfield(handles, 'sourceImg') %display('Open a source image first...'); warndlg('Open a source image first...'); else % get channel [~, ~, d] = size(handles.sourceImg); if ~isfield(handles, 'cursrcChannel') %handles.cursrcChannel = 1; %display('Choose a channel first...'); warndlg('Choose a channel first...'); else if handles.cursrcChannel > 0 && d > 1 handles.cursourceImg = handles.sourceImg(:,:,handles.cursrcChannel); else if handles.cursrcChannel == 0 handles.cursourceImg = rgb2gray(handles.cursourceImg); else handles.cursourceImg = handles.cursourceImg(:,:,1); end end % display axes(handles.sourceAxes); imshow(handles.cursourceImg); end end % update guidata guidata(hObject, handles); % --- Executes on slider movement. function sourcethresholdSlider_Callback(hObject, eventdata, handles) % get source threshold handles.cursrcThreshold = get(hObject, 'Value'); % display theshold %set(handles.cursrcthresholdStatic, 'string', handles.cursrcThreshold); set(handles.sourcethresholdEdit, 'string', handles.cursrcThreshold); guidata(hObject, handles); % --- Executes during object creation, after setting all properties. function sourcethresholdSlider_CreateFcn(hObject, eventdata, handles) if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end % --- Executes on button press in extractsrcfiducialButton. function extractsrcfiducialButton_Callback(hObject, eventdata, handles) % extract fiducials if ~isfield(handles, 'cursourceImg'); %display('Open a source image first...'); warndlg('Open a source image first...'); else if ~isfield(handles, 'cursrcThreshold') %display('Choose a threshold first...'); warndlg('Choose a threshold first...'); else handles.sourcePts = extractLM( handles.cursourceImg, handles.cursrcThreshold); % display axes(handles.sourceAxes); hold on plot(handles.sourcePts(:, 2), handles.sourcePts(:, 1), 'bo', 'LineWidth', 2, ... 'MarkerSize', 15); hold off % save result if isfield(handles, 'srcRect') handles.sourcePts = bsxfun(@plus, handles.sourcePts, [handles.srcRect(2) handles.srcRect(1)] ) ; end sourcePts = handles.sourcePts; save('output/sourcePts.txt', 'sourcePts', '-ASCII'); end end % update guidata(hObject, handles); function resultAxes_CreateFcn(hObject, eventdata, handles) axis off; function sourcepreGroup_SelectionChangeFcn(hObject, eventdata, handles) curchannelTag = get(eventdata.NewValue, 'Tag'); switch curchannelTag case 'redradiobutton' handles.cursrcChannel = 1; case 'greenradiobutton' handles.cursrcChannel = 2; case 'blueradiobutton' handles.cursrcChannel = 3; case 'grayradiobutton' handles.cursrcChannel = 0; otherwise handles.cursrcChannel = -1; end % debug handles.cursrcChannel guidata(hObject, handles); function extracttarfiducialButton_Callback(hObject, eventdata, handles) % extract fiducials if ~isfield(handles, 'curtargetImg'); %display('Open a target image first...'); warndlg('Open a target image first...'); else if ~isfield(handles, 'curtarThreshold') %display('Choose a threshold first...'); warndlg('Choose a threshold first...'); else handles.targetPts = extractLM( handles.curtargetImg, handles.curtarThreshold); % display axes(handles.targetAxes); hold on plot(handles.targetPts(:, 2), handles.targetPts(:, 1), 'r+', 'LineWidth', 2, ... 'MarkerSize', 15); hold off % save result if isfield(handles, 'tarRect') handles.targetPts = bsxfun(@plus, handles.targetPts, [handles.tarRect(2) handles.tarRect(1)] ) ; end targetPts = handles.targetPts; save('output/targetPts.txt', 'targetPts', '-ASCII'); end end % update guidata(hObject, handles); function targetthresholdSlider_Callback(hObject, eventdata, handles) % get source threshold handles.curtarThreshold = get(hObject, 'Value'); % display theshold %set(handles.curtarthresholdStatic, 'string', handles.curtarThreshold); set(handles.targetthresholdEdit, 'string', handles.curtarThreshold); guidata(hObject, handles); function targetthresholdSlider_CreateFcn(hObject, eventdata, handles) % Hint: slider controls usually have a light gray background. if isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor',[.9 .9 .9]); end function targetinverseButton_Callback(hObject, eventdata, handles) % inverse the intensity if ~isfield(handles, 'curtargetImg'); %display('Open a target image first...'); warndlg('Open a target image first...'); else handles.curtargetImg = imcomplement(handles.curtargetImg); % display axes(handles.targetAxes); imshow(handles.curtargetImg); end % update guidata guidata(hObject, handles); function tarextractchannelButton_Callback(hObject, eventdata, handles) if ~isfield(handles, 'targetImg'); %display('Open a target image first...'); warndlg('Open a target image first...'); else % get channel [~,~,d] = size(handles.targetImg); if ~isfield(handles, 'curtarChannel') %handles.curtarChannel = 1; %display('Choose a channel first...'); warndlg('Choose a channel first...'); else if handles.curtarChannel > 0 && d > 1 handles.curtargetImg = handles.targetImg(:,:,handles.curtarChannel); else if handles.curtarChannel == 0 handles.curtargetImg = rgb2gray(handles.curtargetImg); else handles.curtargetImg = handles.curtargetImg(:,:,1); end end % display axes(handles.targetAxes); imshow(handles.curtargetImg); end end % update guidata guidata(hObject, handles); function targetthresholdButton_Callback(hObject, eventdata, handles) % get threshold value %targetthresholdVal = get(handles.targetthresholdSlider, 'Value'); targetthresholdVal = str2double(get(handles.targetthresholdEdit, 'String')); % binarization with given threshold if targetthresholdVal>=0.0 && targetthresholdVal <=1.0 set(handles.targetthresholdSlider, 'Value', targetthresholdVal); handles.curtarThreshold = targetthresholdVal; if ~isfield(handles, 'curtargetImg'); %display('Open a target image first...'); warndlg('Open a target image first...'); else handles.bitarImg = im2bw(handles.curtargetImg, targetthresholdVal); % display axes(handles.targetAxes); imshow(handles.bitarImg); end else %display('Input a valid threshold(0-1)...'); warndlg('Input a valid threshold(0-1)...'); end % update guidata guidata(hObject, handles); function targetpreGroup_SelectionChangeFcn(hObject, eventdata, handles) curchannelTag = get(eventdata.NewValue, 'Tag'); switch curchannelTag case 'redradiobutton' handles.curtarChannel = 1; case 'greenradiobutton' handles.curtarChannel = 2; case 'blueradiobutton' handles.curtarChannel = 3; case 'grayradiobutton' handles.curtarChannel = 0; otherwise handles.curtarChannel = -1; end % debug handles.curtarChannel guidata(hObject, handles); function regButton_Callback(hObject, eventdata, handles) % landmark/fiducial based registration % initialize parameters distthreshold = get(handles.distthresholdEdit, 'String'); params.distthreshold = str2num(distthreshold); %7; simithreshold = get(handles.simithresholdEdit, 'String'); params.simithreshold = str2num(simithreshold); %0.02; if ~isfield(handles, 'curmodel') %display('Choose a model evaluation method...'); warndlg('Choose a model evaluation method...'); else params.checkinliner = handles.curmodel; end leastsquares = get(handles.lsCheckbox, 'Value'); if leastsquares == get(handles.lsCheckbox, 'Max') params.leastsquares = 1; else params.leastsquares = 0; end params.debug = 0; if ~isfield(handles, 'curoutput') %display('Choose a output method...'); warndlg('Choose a output method...'); else if ~isfield(handles,'sourcePts') || ~isfield(handles, 'targetPts') %display('Extract landmarks/fiducials first'); warndlg('Extract landmarks/fiducials first'); else % % display axes(handles.resultAxes); %if ~isfield(handles, 'matchinfo') || ~isfield(handles, 'lsmatchinfo') [handles.matchinfo, handles.lsmatchinfo] = lmRegistration(handles.sourcePts, handles.targetPts, params); %end if handles.curoutput == 1 registered = imgTransform( handles.sourceImg, size(handles.targetImg), handles.lsmatchinfo.affinematrix, 'affine'); imshow(registered) hold on h = imshow(handles.targetImg); set(h, 'AlphaData', 0.6) hold off f = getframe(gca); imwrite(f.cdata, 'output/resultImg.png'); %print(h, '-dpng', 'resultImg'); else h = plot(handles.targetPts(:, 2), handles.targetPts(:, 1), 'r+', 'LineWidth', 2, 'MarkerSize', 10); hold on plot(handles.lsmatchinfo.sourceptstrans(:,2), handles.lsmatchinfo.sourceptstrans(:,1), 'bo', 'LineWidth', 2, 'MarkerSize', 10); hold off f = getframe(gca); imwrite(f.cdata, 'output/resultPts.png'); %print(handles.resultAxes, '-dpng', 'resultPts'); end % % save matchedpts matchedPts = [handles.lsmatchinfo.matchsourcetranspts handles.lsmatchinfo.matchtargetpts]; save('output/matchedPts.txt', 'matchedPts', '-ASCII'); end end guidata(hObject, handles); function srcresetButton_Callback(hObject, eventdata, handles) if ~isfield(handles, 'sourcePath') %disp('Open a new file first...') warndlg('Open a new file first...') else fullpath = handles.sourcePath; display(['Reset ', fullpath]); % display target file axes(handles.sourceAxes); handles.sourceImg = imread(fullpath); handles.cursourceImg = handles.sourceImg; imshow(handles.cursourceImg); end guidata(hObject, handles); function tarresetButton_Callback(hObject, eventdata, handles) if ~isfield(handles, 'targetPath') %disp('Open a new file first...') warndlg('Open a new file first...') else fullpath = handles.targetPath; display(['Reset ', fullpath]); % display target file axes(handles.targetAxes); handles.targetImg = imread(fullpath); handles.curtargetImg = handles.targetImg; imshow(handles.curtargetImg); end guidata(hObject, handles); function targetcropButton_Callback(hObject, eventdata, handles) axes(handles.targetAxes); if ~isfield(handles, 'curtargetImg'); %display('Open a target image first'); warndlg('Open a target image first'); else rect = fix(getrect); [r, c] = size(handles.curtargetImg); % validate rect coordinates if rect(2) < 1 rect(4) = rect(4) + rect(2) - 1; rect(2) = 1; end if rect(2) >= r rect(2) = 0; end if rect(1) < 1 rect(3) = rect(3) + rect(1) - 1; end if rect(1) >= c rect(1) = 0; end if rect(2) + rect(4) > r && ~rect(2) == 0 rect(4) = r - rect(2); end if rect(1) + rect(3) > c && ~rect(1) == 0 rect(3) = c - rect(1); end if rect(2) == 0 || rect(1) == 0 %display('Choose a valid rect region'); warndlg('Choose a valid rect region...'); else %cropedImg = handles.curtargetImg(rect(2):rect(2)+rect(4), rect(1):rect(1)+rect(3), :); cropedImg = imcrop(handles.curtargetImg, rect); handles.tarRect = rect; handles.curtargetImg = cropedImg; imshow(cropedImg); end end guidata(hObject, handles); function sourcecropButton_Callback(hObject, eventdata, handles) %#ok<*INUSL> axes(handles.sourceAxes); if ~isfield(handles, 'cursourceImg'); %display('Open a source image first...'); warndlg('Open a source image first...'); else rect = fix(getrect); [r, c] = size(handles.cursourceImg); % validate rect coordinates if rect(2) < 1 rect(4) = rect(4) + rect(2) - 1; rect(2) = 1; end if rect(2) >= r rect(2) = 0; end if rect(1) < 1 rect(3) = rect(3) + rect(1) - 1; end if rect(1) >= c rect(1) = 0; end if rect(2) + rect(4) > r && ~rect(2) == 0 rect(4) = r - rect(2); end if rect(1) + rect(3) > c && ~rect(1) == 0 rect(3) = c - rect(1); end if rect(2) == 0 || rect(1) == 0 %display('Choose a valid rect region...'); warndlg('Choose a valid rect region...'); else %cropedImg = handles.cursourceImg(rect(2):rect(2)+rect(4), rect(1):rect(1)+rect(3), :); cropedImg = imcrop(handles.cursourceImg, rect); handles.srcRect = rect; handles.cursourceImg = cropedImg; %handles.cursourceImg = zeros(size(handles.cursourceImg)); %handles.cursourceImg(rect(2):rect(2)+rect(4), rect(1):rect(1)+rect(3), :) = cropedImg; imshow(cropedImg); end end guidata(hObject, handles); function distthresholdEdit_Callback(hObject, eventdata, handles) %#ok<*INUSD> function distthresholdEdit_CreateFcn(hObject, eventdata, handles) % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function simithresholdEdit_Callback(hObject, eventdata, handles) function simithresholdEdit_CreateFcn(hObject, eventdata, handles) % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function lsCheckbox_Callback(hObject, eventdata, handles) function modelGroup_SelectionChangeFcn(hObject, eventdata, handles) curmodelTag = get(eventdata.NewValue, 'Tag'); switch curmodelTag case 'medianradioButton' handles.curmodel = 1; case 'allradioButton' handles.curmodel = 0; otherwise handles.curmodel = 0; end guidata(hObject, handles); function outputGroup_SelectionChangeFcn(hObject, eventdata, handles) curoutputTag = get(eventdata.NewValue, 'Tag'); switch curoutputTag case 'imgradioButton' handles.curoutput = 1; case 'ptsradioButton' handles.curoutput = 0; otherwise handles.curoutput = 1; end guidata(hObject, handles); function sourcepreGroup_CreateFcn(hObject, eventdata, handles) handles.cursrcChannel = 1; guidata(hObject, handles); function targetpreGroup_CreateFcn(hObject, eventdata, handles) handles.curtarChannel = 1; guidata(hObject, handles); function modelGroup_CreateFcn(hObject, eventdata, handles) handles.curmodel = 1; guidata(hObject, handles); function outputGroup_CreateFcn(hObject, eventdata, handles) handles.curoutput = 1; guidata(hObject, handles); function targetthresholdEdit_Callback(hObject, eventdata, handles) function targetthresholdEdit_CreateFcn(hObject, eventdata, handles) % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end function sourcethresholdEdit_Callback(hObject, eventdata, handles) function sourcethresholdEdit_CreateFcn(hObject, eventdata, handles) % Hint: edit controls usually have a white background on Windows. % See ISPC and COMPUTER. if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor')) set(hObject,'BackgroundColor','white'); end
github
jacksky64/imageProcessing-master
lmRegistration.m
.m
imageProcessing-master/LmRegistration/common/lmRegistration.m
8,629
utf_8
bf6732a28dec675581a967a8422e81d0
function [matchinfo, lsmatchinfo] = lmRegistration(sourcepts, targetpts, params) % %lmRegistration - Landmark/Fiducial based Registraiton % %Input: % sourcepts: landmarks/fiducials in source image % targetpts: lamdmarks/fiducials in target image % params : parameters for registration % %Outpup: % matchinfo : registration results without least squares matching % lsmatchinfo: registration results with least squares matching % minmatchptsind: index of matched landmarks/fiducials in both image % minaffinematrix: affine transform matrix % %Author: % Tian Cao, Department of Computer Science, UNC-Chapel Hill % sourceptssize = size(sourcepts,1); targetptssize = size(targetpts,1); distmatrixsource = zeros(sourceptssize, sourceptssize); distmatrixtarget = zeros(targetptssize, targetptssize); %% generate distance matrix %for i = 1:sourceptssize % for j = 1:sourceptssize % distmatrixsource(i,j) = sqrt((sourcepts(i,1)-sourcepts(j,1))^2 ... % + (sourcepts(i,2) - sourcepts(j,2))^2); % end % end distmatrixsource = sqrt(dist2(sourcepts(:,1), sourcepts(:,1)) + ... dist2(sourcepts(:,2), sourcepts(:,2))); %for i = 1:targetptssize % for j = 1:targetptssize % distmatrixtarget(i,j) = sqrt((targetpts(i,1)-targetpts(j,1))^2 ... % + (targetpts(i,2) - targetpts(j,2))^2); % end %end distmatrixtarget = sqrt(dist2(targetpts(:,1), targetpts(:,1)) + ... dist2(targetpts(:,2), targetpts(:,2))); % find close neighbors for each landmark/fiducial from distance matries closestneighborsource = zeros(sourceptssize, 3); closestneighborsourceratio = zeros(sourceptssize, 1); for i = 1:sourceptssize sourcedist = distmatrixsource(i,:); [~, I] = sort(sourcedist); closestneighborsource(i,1) = i; closestneighborsource(i,2) = I(2); closestneighborsource(i,3) = I(3); closestneighborsourceratio(i) = distmatrixsource(i, I(2))/distmatrixsource(i, I(3)); end %[~, ind] = sort(distmatrixsource, 2); %closestneighborsource(:,1:3) = ind(:,1:3); %closestneighborsourceratio(i) = distmatrixsource(:, ind(:,2))./distmatrixsource(:, ind(:,3)); closestneighbortarget = zeros(targetptssize, 3); closestneighbortargetratio = zeros(targetptssize, 1); for i = 1:targetptssize targetdist = distmatrixtarget(i,:); [~, I] = sort(targetdist); closestneighbortarget(i,1) = i; closestneighbortarget(i,2) = I(2); closestneighbortarget(i,3) = I(3); closestneighbortargetratio(i) = distmatrixtarget(i, I(2))/distmatrixtarget(i, I(3)); end %% begin registration affinetransformResult = zeros(size(sourcepts,1)*size(targetpts,1), 9); ptsind = 0; if size(sourcepts,1) >= size(targetpts,1) validptsnum = size(targetpts,1); else validptsnum = size(sourcepts,1); end for i = 1: size(sourcepts,1) for j = 1:size(targetpts,1) if (closestneighborsourceratio(i) <= closestneighbortargetratio(j)*(1+params.simithreshold)) ... && (closestneighborsourceratio(i) >= closestneighbortargetratio(j)*(1-params.simithreshold)) A = zeros(6,6); B = zeros(6,1); %affinematrix = zeros(6,1); % compute affine transform matrix X1 = [sourcepts(closestneighborsource(i,1),2) sourcepts(closestneighborsource(i,1),1)]; X2 = [sourcepts(closestneighborsource(i,2),2) sourcepts(closestneighborsource(i,2),1)]; X3 = [sourcepts(closestneighborsource(i,3),2) sourcepts(closestneighborsource(i,3),1)]; A(1,:) = [X1(1) X1(2) 0 0 1 0]; A(2,:) = [0 0 X1(1) X1(2) 0 1]; A(3,:) = [X2(1) X2(2) 0 0 1 0]; A(4,:) = [0 0 X2(1) X2(2) 0 1]; A(5,:) = [X3(1) X3(2) 0 0 1 0]; A(6,:) = [0 0 X3(1) X3(2) 0 1]; B(1) = targetpts(closestneighbortarget(j,1),2); B(2) = targetpts(closestneighbortarget(j,1),1); B(3) = targetpts(closestneighbortarget(j,2),2); B(4) = targetpts(closestneighbortarget(j,2),1); B(5) = targetpts(closestneighbortarget(j,3),2); B(6) = targetpts(closestneighbortarget(j,3),1); if ~(det(A)==0) affinematrix = A\B; sourceptstrans = zeros(size(sourcepts,1), size(sourcepts,2)); % transformed source pts sourceptstrans(:,2) = sourcepts*[affinematrix(2) affinematrix(1)]' ... + repmat(affinematrix(5),size(sourcepts,1),1); sourceptstrans(:,1) = sourcepts*[affinematrix(4) affinematrix(3)]' ... + repmat(affinematrix(6),size(sourcepts,1),1); % compute dist between transformed source pts and target pts distpts = dist2(sourceptstrans, targetpts); [mindistpts, minind] = min(distpts, [], 2); inliernum = numel(unique(minind(find(mindistpts <= params.distthreshold^2)))); %display([i, j, inliernum]); ptsind = ptsind + 1; affinetransformResult(ptsind, 1:2) = [i j]; [sortedmindispts, ind] = sort(mindistpts); if ~params.checkinliner == 1 affinetransformResult(ptsind, 3) = median(sortedmindispts(1:validptsnum)); else affinetransformResult(ptsind, 3) = inliernum; end %affinetransformResult(ptsind, 3) = median(mindistpts(1:validptsnum)); %affinetransformResult(ptsind, 3) = sortedmindispts(5); affinetransformResult(ptsind, 4:end) = affinematrix; end end end end affinetransformResult(find(affinetransformResult(:,1) == 0),:) = []; if ~params.checkinliner == 1 [~, mind] = min(affinetransformResult(:, 3), [], 1); else [~, mind] = max(affinetransformResult(:, 3), [], 1); end %mind = 55; %mind = 45; matchptsind = affinetransformResult(mind, 1:2); affinematrix = affinetransformResult(mind, 4:end); % transformed source pts sourceptstrans = ptsTransform( sourcepts, affinematrix); %% computer mae and std of matching pts matchinfo = computeMatching(sourceptstrans, targetpts, params); matchinfo.matchsourcepts = sourcepts(matchinfo.ind, 1:2); matchinfo.sourceptstrans = sourceptstrans; matchinfo.affinematrix = affinematrix; matchinfo.matchptsind = matchptsind; %% least square affine registration if params.leastsquares == 1 ind = matchinfo.ind; indmin = matchinfo.indmin; % for debug if params.debug == 1 % display matching pts matchinfo.matchsourcetranspts = sourceptstrans(ind, 1:2); figure plot(matchinfo.matchtargetpts(:, 2), matchinfo.matchtargetpts(:, 1), 'r+'); hold on plot(matchinof.matchsourcetranspts(:,2), matchinof.matchsourcetranspts(:,1), 'b*'); end matchptssize = size(matchinfo.matchsourcepts,1); A = zeros(2*matchptssize, 6); B = zeros(2*matchptssize, 1); A(1:matchptssize, :) = [matchinfo.matchsourcepts(:,2) matchinfo.matchsourcepts(:,1) zeros(matchptssize,1) ... zeros(matchptssize,1) ones(matchptssize,1) zeros(matchptssize,1)]; A(matchptssize+1:end, :) = [zeros(matchptssize,1) zeros(matchptssize,1) matchinfo.matchsourcepts(:,2)... matchinfo.matchsourcepts(:,1) zeros(matchptssize,1) ones(matchptssize, 1)]; B(1:matchptssize) = matchinfo.matchtargetpts(:,2); B(matchptssize+1:end) = matchinfo.matchtargetpts(:,1); if ~(det(A'*A)==0) minaffinematrix = (A'*A)\(A'*B); minmatchptsind = [ind indmin(ind)]; else minaffinematrix = affinematrix; minmatchptsind = matchptsind; end lssourceptstrans = ptsTransform( sourcepts, minaffinematrix); %% compute mae and std of matching pts lsmatchinfo = computeMatching(lssourceptstrans, targetpts, params); lsmatchinfo.matchsourcepts = sourcepts(lsmatchinfo.ind, 1:2); %lsmatchinfo.matchtargetpts = targetpts() lsmatchinfo.sourceptstrans = lssourceptstrans; lsmatchinfo.affinematrix = minaffinematrix; lsmatchinfo.matchptsind = minmatchptsind; else %minaffinematrix = affinematrix; %minmatchptsind = matchptsind; lsmatchinfo = matchinfo; end
github
jacksky64/imageProcessing-master
imagesAlign.m
.m
imageProcessing-master/piotr/toolbox/videos/imagesAlign.m
8,167
utf_8
d125eb5beb502d940be5bd145521f34b
function [H,Ip] = imagesAlign( I, Iref, varargin ) % Fast and robust estimation of homography relating two images. % % The algorithm for image alignment is a simple but effective variant of % the inverse compositional algorithm. For a thorough overview, see: % "Lucas-kanade 20 years on A unifying framework," % S. Baker and I. Matthews. IJCV 2004. % The implementation is optimized and can easily run at 20-30 fps. % % type may take on the following values: % 'translation' - translation only % 'rigid' - translation and rotation % 'similarity' - translation, rotation and scale % 'affine' - 6 parameter affine transform % 'rotation' - pure rotation (about x, y and z) % 'projective' - full 8 parameter homography % Alternatively, type may be a vector of ids between 1 and 8, specifying % exactly the types of transforms allowed. The ids correspond, to: 1: % translate-x, 2: translate-y, 3: uniform scale, 4: shear, 5: non-uniform % scale, 6: rotate-z, 7: rotate-x, 8: rotate-y. For example, to specify % translation use type=[1,2]. If the transforms don't form a group, the % returned homography may have more degrees of freedom than expected. % % Parameters (in rough order of importance): [resample] controls image % downsampling prior to computing H. Runtime is proportional to area, so % using resample<1 can dramatically speed up alignment, and in general not % degrade performance much. [sig] controls image smoothing, sig=2 gives % good performance, setting sig too low causes loss of information and too % high will violate the linearity assumption. [epsilon] defines the % stopping criteria, use to adjust performance versus speed tradeoff. % [lambda] is a regularization term that causes small transforms to be % favored, in general any small non-zero setting of lambda works well. % [outThr] is a threshold beyond which pixels are considered outliers, be % careful not to set too low. [minArea] determines coarsest scale beyond % which the image is not downsampled (should not be set too low). [H0] can % be used to specify an initial alignment. Use [show] to display results. % % USAGE % [H,Ip] = imagesAlign( I, Iref, varargin ) % % INPUTS % I - transformed version of I % Iref - reference grayscale double image % varargin - additional params (struct or name/value pairs) % .type - ['projective'] see above for options % .resample - [1] image resampling prior to homography estimation % .sig - [2] amount of Gaussian spatial smoothing to apply % .epsilon - [1e-3] stopping criteria (min change in error) % .lambda - [1e-6] regularization term favoring small transforms % .outThr - [inf] outlier threshold % .minArea - [4096] minimum image area in coarse to fine search % .H0 - [eye(3)] optional initial homography estimate % .show - [0] optionally display results in figure show % % OUTPUTS % H - estimated homography to transform I into Iref % Ip - tranformed version of I (slow to compute) % % EXAMPLE % Iref = double(imread('cameraman.tif'))/255; % H0 = [eye(2)+randn(2)*.1 randn(2,1)*10; randn(1,2)*1e-3 1]; % I = imtransform2(Iref,H0^-1,'pad','replicate'); % o=50; P=ones(o)*1; I(150:149+o,150:149+o)=P; % prmAlign={'outThr',.1,'resample',.5,'type',1:8,'show'}; % [H,Ip]=imagesAlign(I,Iref,prmAlign{:},1); % tic, for i=1:30, H=imagesAlign(I,Iref,prmAlign{:},0); end; % t=toc; fprintf('average fps: %f\n',30/t) % % See also imTransform2 % % 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] % get parameters dfs={'type','projective','resample',1,'sig',2,'epsilon',1e-3,... 'lambda',1e-6,'outThr',inf,'minArea',4096,'H0',eye(3),'show',0}; [type,resample,sig,epsilon,lambda,outThr,minArea,H0,show] = ... getPrmDflt(varargin,dfs,1); filt = filterGauss(2*ceil(sig*2.5)+1,[],sig^2); % determine type of transformation to recover if(isnumeric(type)), assert(length(type)<=8); else id=find(strcmpi(type,{'translation','rigid','similarity','affine',... 'rotation','projective'})); msgId='piotr:imagesAlign'; if(isempty(id)), error(msgId,'unknown type: %s',type); end type={1:2,[1:2 6],[1:3 6],1:6,6:8,1:8}; type=type{id}; end; keep=zeros(1,8); keep(type)=1; keep=keep>0; % compute image alignment (optionally resample first) prm={keep,filt,epsilon,H0,minArea,outThr,lambda}; if( resample==1 ), H=imagesAlign1(I,Iref,prm); else S=eye(3); S([1 5])=resample; H0=S*H0*S^-1; prm{4}=H0; I1=imResample(I,resample); Iref1=imResample(Iref,resample); H=imagesAlign1(I1,Iref1,prm); H=S^-1*H*S; end % optionally rectify I and display results (can be expensive) if(nargout==1 && show==0), return; end Ip = imtransform2(I,H,'pad','replicate'); if(show), figure(show); clf; s=@(i) subplot(2,3,i); Is=[I Iref Ip]; ri=[min(Is(:)) max(Is(:))]; D0=abs(I-Iref); D1=abs(Ip-Iref); Ds=[D0 D1]; di=[min(Ds(:)) max(Ds(:))]; s(1); im(I,ri,0); s(2); im(Iref,ri,0); s(3); im(D0,di,0); s(4); im(Ip,ri,0); s(5); im(Iref,ri,0); s(6); im(D1,di,0); s(3); title('|I-Iref|'); s(6); title('|Ip-Iref|'); end end function H = imagesAlign1( I, Iref, prm ) % apply recursively if image large [keep,filt,epsilon,H0,minArea,outThr,lambda]=deal(prm{:}); [h,w]=size(I); hc=mod(h,2); wc=mod(w,2); if( w*h<minArea ), H=H0; else I1=imResample(I(1:(h-hc),1:(w-wc)),.5); Iref1=imResample(Iref(1:(h-hc),1:(w-wc)),.5); S=eye(3); S([1 5])=2; H0=S^-1*H0*S; prm{4}=H0; H=imagesAlign1(I1,Iref1,prm); H=S*H*S^-1; end % smooth images (pad first so dimensions unchanged) O=ones(1,(length(filt)-1)/2); hs=[O 1:h h*O]; ws=[O 1:w w*O]; Iref=conv2(conv2(Iref(hs,ws),filt','valid'),filt,'valid'); I=conv2(conv2(I(hs,ws),filt','valid'),filt,'valid'); % pad images with nan so later can determine valid regions hs=[1 1 1:h h h]; ws=[1 1 1:w w w]; I=I(hs,ws); Iref=Iref(hs,ws); hs=[1:2 h+3:h+4]; I(hs,:)=nan; Iref(hs,:)=nan; ws=[1:2 w+3:w+4]; I(:,ws)=nan; Iref(:,ws)=nan; % convert weights hardcoded for 128x128 image to given image dims wts=[1 1 1.0204 .03125 1.0313 0.0204 .00055516 .00055516]; s=sqrt(numel(Iref))/128; wts=[wts(1:2) wts(3)^(1/s) wts(4)/s wts(5)^(1/s) wts(6)/s wts(7:8)/(s*s)]; % prepare subspace around Iref [~,Hs]=ds2H(-ones(1,8),wts); Hs=Hs(:,:,keep); K=size(Hs,3); [h,w]=size(Iref); Ts=zeros(h,w,K); k=0; if(keep(1)), k=k+1; Ts(:,1:end-1,k)=Iref(:,2:end); end if(keep(2)), k=k+1; Ts(1:end-1,:,k)=Iref(2:end,:); end pTransf={'method','bilinear','pad','none','useCache'}; for i=k+1:K, Ts(:,:,i)=imtransform2(Iref,Hs(:,:,i),pTransf{:},1); end Ds=Ts-Iref(:,:,ones(1,K)); Mref = ~any(isnan(Ds),3); if(0), figure(10); montage2(Ds); end Ds = reshape(Ds,[],size(Ds,3)); % iteratively project Ip onto subspace, storing transformation lambda=lambda*w*h*eye(K); ds=zeros(1,8); err=inf; for i=1:100 s=svd(H); if(s(3)<=1e-4*s(1)), H=eye(3); return; end Ip=imtransform2(I,H,pTransf{:},0); dI=Ip-Iref; dI0=abs(dI); M=Mref & ~isnan(Ip); M0=M; if(outThr<inf), M=M & dI0<outThr; end M1=find(M); D=Ds(M1,:); ds1=(D'*D + lambda)^(-1)*(D'*dI(M1)); if(any(isnan(ds1))), ds1=zeros(K,1); end ds(keep)=ds1; H1=ds2H(ds,wts); H=H*H1; H=H/H(9); err0=err; err=dI0; err(~M0)=0; err=mean2(err); del=err0-err; if(0), fprintf('i=%03i err=%e del=%e\n',i,err,del); end if( del<epsilon ), break; end end end function [H,Hs] = ds2H( ds, wts ) % compute homography from offsets ds Hs=eye(3); Hs=Hs(:,:,ones(1,8)); Hs(2,3,1)=wts(1)*ds(1); % 1 x translation Hs(1,3,2)=wts(2)*ds(2); % 2 y translation Hs(1:2,1:2,3)=eye(2)*wts(3)^ds(3); % 3 scale Hs(2,1,4)=wts(4)*ds(4); % 4 shear Hs(1,1,5)=wts(5)^ds(5); % 5 scale non-uniform ct=cos(wts(6)*ds(6)); st=sin(wts(6)*ds(6)); Hs(1:2,1:2,6)=[ct -st; st ct]; % 6 rotation about z ct=cos(wts(7)*ds(7)); st=sin(wts(7)*ds(7)); Hs([1 3],[1 3],7)=[ct -st; st ct]; % 7 rotation about x ct=cos(wts(8)*ds(8)); st=sin(wts(8)*ds(8)); Hs(2:3,2:3,8)=[ct -st; st ct]; % 8 rotation about y H=eye(3); for i=1:8, H=Hs(:,:,i)*H; end end
github
jacksky64/imageProcessing-master
opticalFlow.m
.m
imageProcessing-master/piotr/toolbox/videos/opticalFlow.m
7,361
utf_8
b97e8c1f623eca07c6f1a0fff26d171e
function [Vx,Vy,reliab] = opticalFlow( I1, I2, varargin ) % Coarse-to-fine optical flow using Lucas&Kanade or Horn&Schunck. % % Implemented 'type' of optical flow estimation: % LK: http://en.wikipedia.org/wiki/Lucas-Kanade_method % HS: http://en.wikipedia.org/wiki/Horn-Schunck_method % SD: Simple block-based sum of absolute differences flow % LK is a local, fast method (the implementation is fully vectorized). % HS is a global, slower method (an SSE implementation is provided). % SD is a simple but potentially expensive approach. % % Common parameters: 'smooth' determines smoothing prior to computing flow % and can make flow estimation more robust. 'filt' determines amount of % median filtering of the computed flow field which improves results but is % costly. 'minScale' and 'maxScale' control image scales in the pyramid. % Setting 'maxScale'<1 results in faster but lower quality results, e.g. % maxScale=.5 makes flow computation about 4x faster. Method specific % parameters: 'radius' controls window size (and smoothness of flow) for LK % and SD. 'nBlock' determines number of blocks tested in each direction for % SD, computation time is O(nBlock^2). For HS, 'alpha' controls tradeoff % between data and smoothness term (and smoothness of flow) and 'nIter' % determines number of gradient decent steps. % % USAGE % [Vx,Vy,reliab] = opticalFlow( I1, I2, pFlow ) % % INPUTS % I1, I2 - input images to calculate flow between % pFlow - parameters (struct or name/value pairs) % .type - ['LK'] may be 'LK', 'HS' or 'SD' % .smooth - [1] smoothing radius for triangle filter (may be 0) % .filt - [0] median filtering radius for smoothing flow field % .minScale - [1/64] minimum pyramid scale (must be a power of 2) % .maxScale - [1] maximum pyramid scale (must be a power of 2) % .radius - [10] integration radius for weighted window [LK/SD only] % .nBlock - [5] number of tested blocks [SD only] % .alpha - [1] smoothness constraint [HS only] % .nIter - [250] number of iterations [HS only] % % OUTPUTS % Vx, Vy - x,y components of flow [Vx>0->right, Vy>0->down] % reliab - reliability of flow in given window % % EXAMPLE - compute LK flow on test images % load opticalFlowTest; % [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK'); % figure(1); im(I1); figure(2); im(I2); % figure(3); im([Vx Vy]); colormap jet; % % EXAMPLE - rectify I1 to I2 using computed flow % load opticalFlowTest; % [Vx,Vy]=opticalFlow(I1,I2,'smooth',1,'radius',10,'type','LK'); % I1=imtransform2(I1,[],'vs',-Vx,'us',-Vy,'pad','replicate'); % figure(1); im(I1); figure(2); im(I2); % % EXAMPLE - compare LK/HS/SD flows % load opticalFlowTest; % prm={'smooth',1,'radius',10,'alpha',20,'nIter',250,'type'}; % tic, [Vx1,Vy1]=opticalFlow(I1,I2,prm{:},'LK'); toc % tic, [Vx2,Vy2]=opticalFlow(I1,I2,prm{:},'HS'); toc % tic, [Vx3,Vy3]=opticalFlow(I1,I2,prm{:},'SD','minScale',1); toc % figure(1); im([Vx1 Vy1; Vx2 Vy2; Vx3 Vy3]); colormap jet; % % See also convTri, imtransform2, medfilt2 % % 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 default parameters and do error checking dfs={ 'type','LK', 'smooth',1, 'filt',0, 'minScale',1/64, ... 'maxScale',1, 'radius',10, 'nBlock',5, 'alpha',1, 'nIter',250 }; [type,smooth,filt,minScale,maxScale,radius,nBlock,alpha,nIter] = ... getPrmDflt(varargin,dfs,1); assert(any(strcmp(type,{'LK','HS','SD'}))); if( ~ismatrix(I1) || ~ismatrix(I2) || any(size(I1)~=size(I2)) ) error('Input images must be 2D and have same dimensions.'); end % run optical flow in coarse to fine fashion if(~isa(I1,'single')), I1=single(I1); I2=single(I2); end [h,w]=size(I1); nScales=max(1,floor(log2(min([h w 1/minScale])))+1); for s=1:max(1,nScales + round(log2(maxScale))) % get current scale and I1s and I2s at given scale scale=2^(nScales-s); h1=round(h/scale); w1=round(w/scale); if( scale==1 ), I1s=I1; I2s=I2; else I1s=imResample(I1,[h1 w1]); I2s=imResample(I2,[h1 w1]); end % initialize Vx,Vy or upsample from previous scale if(s==1), Vx=zeros(h1,w1,'single'); Vy=Vx; else r=sqrt(h1*w1/numel(Vx)); Vx=imResample(Vx,[h1 w1])*r; Vy=imResample(Vy,[h1 w1])*r; end % transform I2s according to current estimate of Vx and Vy if(s>1), I2s=imtransform2(I2s,[],'pad','replciate','vs',Vx,'us',Vy); end % smooth images I1s=convTri(I1s,smooth); I2s=convTri(I2s,smooth); % run optical flow on current scale switch type case 'LK', [Vx1,Vy1,reliab]=opticalFlowLk(I1s,I2s,radius); case 'HS', [Vx1,Vy1,reliab]=opticalFlowHs(I1s,I2s,alpha,nIter); case 'SD', [Vx1,Vy1,reliab]=opticalFlowSd(I1s,I2s,radius,nBlock,1); end Vx=Vx+Vx1; Vy=Vy+Vy1; % finally median filter the resulting flow field if(filt), Vx=medfilt2(Vx,[filt filt],'symmetric'); end if(filt), Vy=medfilt2(Vy,[filt filt],'symmetric'); end end r=sqrt(h*w/numel(Vx)); if(r~=1), Vx=imResample(Vx,[h w])*r; Vy=imResample(Vy,[h w])*r; end if(r~=1 && nargout==3), reliab=imResample(reliab,[h w]); end end function [Vx,Vy,reliab] = opticalFlowLk( I1, I2, radius ) % Compute elements of A'A and also of A'b radius=min(radius,floor(min(size(I1,1),size(I1,2))/2)-1); [Ix,Iy]=gradient2(I1); It=I2-I1; AAxy=convTri(Ix.*Iy,radius); AAxx=convTri(Ix.^2,radius)+1e-5; ABxt=convTri(-Ix.*It,radius); AAyy=convTri(Iy.^2,radius)+1e-5; AByt=convTri(-Iy.*It,radius); % Find determinant and trace of A'A AAdet=AAxx.*AAyy-AAxy.^2; AAdeti=1./AAdet; AAtr=AAxx+AAyy; % Compute components of velocity vectors (A'A)^-1 * A'b Vx = AAdeti .* ( AAyy.*ABxt - AAxy.*AByt); Vy = AAdeti .* (-AAxy.*ABxt + AAxx.*AByt); % Check for ill conditioned second moment matrices reliab = 0.5*AAtr - 0.5*sqrt(AAtr.^2-4*AAdet); end function [Vx,Vy,reliab] = opticalFlowHs( I1, I2, alpha, nIter ) % compute derivatives (averaging over 2x2 neighborhoods) pad = @(I,p) imPad(I,p,'replicate'); crop = @(I,c) I(1+c:end-c,1+c:end-c); Ex = I1(:,2:end)-I1(:,1:end-1) + I2(:,2:end)-I2(:,1:end-1); Ey = I1(2:end,:)-I1(1:end-1,:) + I2(2:end,:)-I2(1:end-1,:); Ex = Ex/4; Ey = Ey/4; Et = (I2-I1)/4; Ex = pad(Ex,[1 1 1 2]) + pad(Ex,[0 2 1 2]); Ey = pad(Ey,[1 2 1 1]) + pad(Ey,[1 2 0 2]); Et=pad(Et,[0 2 1 1])+pad(Et,[1 1 1 1])+pad(Et,[1 1 0 2])+pad(Et,[0 2 0 2]); Z=1./(alpha*alpha + Ex.*Ex + Ey.*Ey); reliab=crop(Z,1); % iterate updating Ux and Vx in each iter if( 1 ) [Vx,Vy]=opticalFlowHsMex(Ex,Ey,Et,Z,nIter); Vx=crop(Vx,1); Vy=crop(Vy,1); else Ex=crop(Ex,1); Ey=crop(Ey,1); Et=crop(Et,1); Z=crop(Z,1); Vx=zeros(size(I1),'single'); Vy=Vx; f=single([0 1 0; 1 0 1; 0 1 0])/4; for i = 1:nIter Mx=conv2(Vx,f,'same'); My=conv2(Vy,f,'same'); m=(Ex.*Mx+Ey.*My+Et).*Z; Vx=Mx-Ex.*m; Vy=My-Ey.*m; end end end function [Vx,Vy,reliab] = opticalFlowSd( I1, I2, radius, nBlock, step ) % simple block-based sum of absolute differences flow [h,w]=size(I1); k=2*nBlock+1; k=k*k; D=zeros(h,w,k,'single'); k=1; rng = @(x,w) max(1+x*step,1):min(w+x*step,w); for x=-nBlock:nBlock, xs0=rng(x,w); xs1=rng(-x,w); for y=-nBlock:nBlock, ys0=rng(y,h); ys1=rng(-y,h); D(ys0,xs0,k)=abs(I1(ys0,xs0)-I2(ys1,xs1)); k=k+1; end end D=convTri(D,radius); [reliab,D]=min(D,[],3); k=2*nBlock+1; Vy=mod(D-1,k)+1; Vx=(D-Vy)/k+1; Vy=(nBlock+1-Vy)*step; Vx=(nBlock+1-Vx)*step; end
github
jacksky64/imageProcessing-master
seqWriterPlugin.m
.m
imageProcessing-master/piotr/toolbox/videos/seqWriterPlugin.m
8,280
utf_8
597792f79fff08b8bb709313267c3860
function varargout = seqWriterPlugin( cmd, h, varargin ) % Plugin for seqIo and videoIO to allow writing of seq files. % % Do not call directly, use as plugin for seqIo or videoIO instead. % The following is a list of commands available (swp=seqWriterPlugin): % h=swp('open',h,fName,info) % Open a seq file for writing (h ignored). % h=swp('close',h) % Close seq file (output h is -1). % swp('addframe',h,I,[ts]) % Writes video frame (and timestamp). % swp('addframeb',h,I,[ts]) % Writes video frame with no encoding. % info = swp('getinfo',h) % 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 % varargout = seqWriterPlugin( 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, SEQREADERPLUGIN % % Piotr's Computer Vision Matlab Toolbox Version 2.66 % 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 fids infos tNms; if(isempty(h1)), h1=int32(now); hs=int32([]); infos={}; tNms={}; end nIn=nargin-2; in=varargin; o1=[]; cmd=lower(cmd); % open seq file if(strcmp(cmd,'open')) chk(nIn,2); h=length(hs)+1; hs(h)=h1; varargout={h1}; h1=h1+1; [pth,name]=fileparts(in{1}); if(isempty(pth)), pth='.'; end fName=[pth filesep name]; [infos{h},fids(h),tNms{h}]=open(fName,in{2}); return; end % Get the handle for this instance [v,h]=ismember(h,hs); if(~v), error('Invalid load plugin handle'); end fid=fids(h); info=infos{h}; tNm=tNms{h}; % close seq file if(strcmp(cmd,'close')) writeHeader(fid,info); chk(nIn,0); varargout={-1}; fclose(fid); kp=[1:h-1 h+1:length(hs)]; hs=hs(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 'addframe', chk(nIn,1,2); info=addFrame(fid,info,tNm,1,in{:}); case 'addframeb', chk(nIn,1,2); info=addFrame(fid,info,tNm,0,in{:}); case 'getinfo', chk(nIn,0); o1=info; otherwise, error(['Unrecognized command: "' cmd '"']); end infos{h}=info; varargout={o1}; 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 writing, create space for header t=[fName '.seq']; if(exist(t,'file')), delete(t); end t=[fName '-seek.mat']; if(exist(t,'file')), delete(t); end fid=fopen([fName '.seq'],'w','l'); assert(fid~=-1); fwrite(fid,zeros(1,1024),'uint8'); % initialize info struct (w all fields necessary for writeHeader) assert(isfield2(info,{'width','height','fps','codec'},1)); switch(info.codec) case {'monoraw', 'imageFormat100'}, frmt=100; nCh=1; ext='raw'; case {'raw', 'imageFormat200'}, frmt=200; nCh=3; ext='raw'; case {'monojpg', 'imageFormat102'}, frmt=102; nCh=1; ext='jpg'; case {'jpg', 'imageFormat201'}, frmt=201; nCh=3; ext='jpg'; case {'monopng', 'imageFormat001'}, frmt=001; nCh=1; ext='png'; case {'png', 'imageFormat002'}, frmt=002; nCh=3; ext='png'; otherwise, error('unknown format'); end; s=1; if(strcmp(ext,'jpg')), s=getImgFile('wjpg8c'); end if(strcmp(ext,'png')), s=getImgFile('png'); if(s), info.writeImg=@(p) png('write',p{:}); end; end if(strcmp(ext,'png') && ~s), s=getImgFile('pngwritec'); if(s), info.writeImg=@(p) pngwritec(p{:}); end; end if(~s), error('Cannot find Matlab''s source image writer'); end info.imageFormat=frmt; info.ext=ext; if(any(strcmp(ext,{'jpg','png'}))), info.seek=1024; info.seekNm=t; end if(~isfield2(info,'quality')), info.quality=80; end info.imageBitDepth=8*nCh; info.imageBitDepthReal=8; nByte=info.width*info.height*nCh; info.imageSizeBytes=nByte; info.numFrames=0; info.trueImageSize=nByte+6+512-mod(nByte+6,512); % 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); end function info = addFrame( fid, info, tNm, encode, I, ts ) % write frame nCh=info.imageBitDepth/8; ext=info.ext; c=info.numFrames+1; if( encode ) siz = [info.height info.width nCh]; assert(size(I,1)==siz(1) && size(I,2)==siz(2) && size(I,3)==siz(3)); end switch ext case 'raw' % write an uncompressed image (assume imageBitDepthReal==8) if( ~encode ), assert(numel(I)==info.imageSizeBytes); else if(nCh==3), t=I(:,:,3); I(:,:,3)=I(:,:,1); I(:,:,1)=t; end if(nCh==1), I=I'; else I=permute(I,[3,2,1]); end end fwrite(fid,I(:),'uint8'); pad=info.trueImageSize-info.imageSizeBytes-6; case 'jpg' if( encode ) % write/read to/from temporary .jpg (not that much overhead) p=struct('quality',info.quality,'comment',{{}},'mode','lossy'); for t=0:99, try wjpg8c(I,tNm,p); fr=fopen(tNm,'r'); assert(fr>0); break; catch, pause(.01); fr=-1; end; end %#ok<CTCH> if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr); end assert(I(1)==255 && I(2)==216 && I(end-1)==255 && I(end)==217); % JPG fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10; case 'png' if( encode ) % write/read to/from temporary .png (not that much overhead) p=cell(1,17); if(nCh==1), p{4}=0; else p{4}=2; end p{1}=I; p{3}=tNm; p{5}=8; p{8}='none'; p{16}=cell(0,2); for t=0:99, try info.writeImg(p); fr=fopen(tNm,'r'); assert(fr>0); break; catch, pause(.01); fr=-1; end; end %#ok<CTCH> if(fr<0), error(['write fail: ' tNm]); end; I=fread(fr); fclose(fr); end fwrite(fid,numel(I)+4,'uint32'); fwrite(fid,I); pad=10; otherwise, assert(false); end % store seek info if(any(strcmp(ext,{'jpg','png'}))) if(length(info.seek)<c+1), info.seek=[info.seek; zeros(c,1)]; end info.seek(c+1)=info.seek(c)+numel(I)+10+pad; end % write timestamp if(nargin<6),ts=(c-1)/info.fps; end; s=floor(ts); ms=round(mod(ts,1)*1000); fwrite(fid,s,'int32'); fwrite(fid,ms,'uint16'); info.numFrames=c; % pad with zeros if(pad>0), fwrite(fid,zeros(1,pad),'uint8'); end end function writeHeader( fid, info ) fseek(fid,0,'bof'); % first 4 bytes store OxFEED, next 24 store 'Norpix seq ' fwrite(fid,hex2dec('FEED'),'uint32'); fwrite(fid,['Norpix seq' 0 0],'uint16'); % next 8 bytes for version (3) and header size (1024), then 512 for descr fwrite(fid,[3 1024],'int32'); if(isfield(info,'descr')), d=info.descr(:); else d=('No Description')'; end d=[d(1:min(256,end)); zeros(256-length(d),1)]; fwrite(fid,d,'uint16'); % write remaining info vals=[info.width info.height info.imageBitDepth info.imageBitDepthReal ... info.imageSizeBytes info.imageFormat info.numFrames 0 ... info.trueImageSize]; fwrite(fid,vals,'uint32'); % store frame rate and pad with 0's fwrite(fid,info.fps,'float64'); fwrite(fid,zeros(1,432),'uint8'); % write seek info for compressed images to disk if(any(strcmp(info.ext,{'jpg','png'}))) seek=info.seek(1:info.numFrames); %#ok<NASGU> try save(info.seekNm,'seek'); catch; end %#ok<CTCH> end end
github
jacksky64/imageProcessing-master
kernelTracker.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
seqIo.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
seqReaderPlugin.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
pcaApply.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
forestTrain.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
fernsRegTrain.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
rbfDemo.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
pdist2.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
pca.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
kmeans2.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
acfModify.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
acfDetect.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
bbGt.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
bbApply.m
.m
imageProcessing-master/piotr/toolbox/detector/bbApply.m
21,195
utf_8
cc9744e55c6b8442486ba7f71e3f84ce
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,2)) 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
jacksky64/imageProcessing-master
imwrite2.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
convnFast.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
imMlGauss.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
montage2.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
jitterImage.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
movieToImages.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
toolboxUpdateHeader.m
.m
imageProcessing-master/piotr/toolbox/external/toolboxUpdateHeader.m
2,255
utf_8
7a5b75e586be48da97c84d20b59887ff
function toolboxUpdateHeader % Update the headers of all the files. % % USAGE % toolboxUpdateHeader % % 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] header={ '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]'}; 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
jacksky64/imageProcessing-master
toolboxGenDoc.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
toolboxHeader.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
mdot.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
m2html.m
.m
imageProcessing-master/piotr/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,'&','&amp;'); str = strrep(str,'<','&lt;'); str = strrep(str,'>','&gt;'); str = strrep(str,'"','&quot;'); %=============================================================================== 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
jacksky64/imageProcessing-master
doxysearch.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
doxywrite.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
doxyread.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
imwrite2split.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
playmovies.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
pca_apply_large.m
.m
imageProcessing-master/piotr/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
jacksky64/imageProcessing-master
montages2.m
.m
imageProcessing-master/piotr/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));