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
|
interpretColor.m
|
.m
|
imageProcessing-master/Matlab Slicer/imStacks/+uiextras/interpretColor.m
| 3,396 |
utf_8
|
ec1f7605145817838d2c9b712af4287d
|
function col = interpretColor(str)
%interpretColor Interpret a color as an RGB triple
%
% rgb = uiextras.interpretColor(col) interprets the input color COL and
% returns the equivalent RGB triple. COL can be one of:
% * RGB triple of floating point numbers in the range 0 to 1
% * RGB triple of UINT8 numbers in the range 0 to 255
% * single character: 'r','g','b','m','y','c','k','w'
% * string: one of 'red','green','blue','magenta','yellow','cyan','black'
% 'white'
% * HTML-style string (e.g. '#FF23E0')
%
% Examples:
% >> uiextras.interpretColor( 'r' )
% ans =
% 1 0 0
% >> uiextras.interpretColor( 'cyan' )
% ans =
% 0 1 1
% >> uiextras.interpretColor( '#FF23E0' )
% ans =
% 1.0000 0.1373 0.8784
%
% See also: ColorSpec
% Copyright 2005-2010 The MathWorks Ltd.
% $Revision: 329 $
% $Date: 2010-08-26 09:53:44 +0100 (Thu, 26 Aug 2010) $
if ischar( str )
str = strtrim(str);
str = dequote(str);
if str(1)=='#'
% HTML-style string
if numel(str)==4
col = [hex2dec( str(2) ), hex2dec( str(3) ), hex2dec( str(4) )]/15;
elseif numel(str)==7
col = [hex2dec( str(2:3) ), hex2dec( str(4:5) ), hex2dec( str(6:7) )]/255;
else
error( 'UIExtras:interpretColor:BadColor', 'Invalid HTML color %s', str );
end
elseif all( ismember( str, '1234567890.,; []' ) )
% Try the '[0 0 1]' thing first
col = str2num( str ); %#ok<ST2NM>
if numel(col) == 3
% Conversion worked, so just check for silly values
col(col<0) = 0;
col(col>1) = 1;
end
else
% that didn't work, so try the name
switch upper(str)
case {'R','RED'}
col = [1 0 0];
case {'G','GREEN'}
col = [0 1 0];
case {'B','BLUE'}
col = [0 0 1];
case {'C','CYAN'}
col = [0 1 1];
case {'Y','YELLOW'}
col = [1 1 0];
case {'M','MAGENTA'}
col = [1 0 1];
case {'K','BLACK'}
col = [0 0 0];
case {'W','WHITE'}
col = [1 1 1];
case {'N','NONE'}
col = [nan nan nan];
otherwise
% Failed
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
end
elseif isfloat(str) || isdouble(str)
% Floating point, so should be a triple in range 0 to 1
if numel(str)==3
col = double( str );
col(col<0) = 0;
col(col>1) = 1;
else
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
elseif isa(str,'uint8')
% UINT8, so range is implicit
if numel(str)==3
col = double( str )/255;
col(col<0) = 0;
col(col>1) = 1;
else
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
else
error( 'UIExtras:interpretColor:BadColor', 'Could not interpret color %s', num2str( str ) );
end
function str = dequote(str)
str(str=='''') = [];
str(str=='"') = [];
str(str=='[') = [];
str(str==']') = [];
|
github
|
jacksky64/imageProcessing-master
|
Container.m
|
.m
|
imageProcessing-master/Matlab Slicer/imStacks/+uiextras/Container.m
| 22,989 |
utf_8
|
c9212141cf493e285730ee2a6af4d5c6
|
classdef Container < hgsetget
%Container Container base class
%
% c = uiextras.Container() creates a new container object. Container
% is an abstract class and can only be constructed as the first
% actual of a descendent class.
%
% c = uiextras.Container(param,value,...) creates a new container
% object and sets one or more property values.
%
% See also: uiextras.Box
% uiextras.ButtonBox
% uiextras.CardPanel
% uiextras.Grid
% Copyright 2009-2010 The MathWorks, Inc.
% $Revision: 367 $
% $Date: 2011-02-10 16:25:22 +0000 (Thu, 10 Feb 2011) $
properties
DeleteFcn % function to call when the layout is being deleted [function handle]
end % Public properties
properties( Dependent, Transient )
BackgroundColor % background color [r g b]
BeingDeleted % is the object in the process of being deleted [on|off]
Children % list of the children of the layout [handle array]
Enable % allow interaction with the contents of this layout [on|off]
Parent % handle of the parent container or figure [handle]
Position % position [left bottom width height]
Tag % tag [string]
Type % the object type (class) [string]
Units % position units [inches|centimeters|normalized|points|pixels|characters]
Visible % is the layout visible on-screen [on|off]
end % dependent properties
properties( Access = protected, Hidden, Transient )
Listeners = cell( 0, 1 ) % array of listeners
end % protected properties
properties( SetAccess = private, GetAccess = protected, Hidden, Transient )
UIContainer % associated uicontainer
end % read-only protected properties
properties( Access = private, Hidden, Transient )
Children_ = zeros( 0, 1 ) % private copy of the children list
ChildListeners = cell( 0, 2 ) % listeners for changes to children
Enable_ = 'on' % private copy of the enabled state
CurrentSize_ = [0 0] % private copy of the size
end % private properties
methods
function obj = Container( varargin )
%Container Container base class constructor
%
% obj = Container(param,value,...) creates a new Container
% object using the (optional) property values specified. This
% may only be called by child classes.
% Check that we're using the right graphics version
if isHGUsingMATLABClasses()
error( 'GUILayout:WrongHGVersion', 'Trying to run using double-handle MATLAB graphics against the new graphics system. Please re-install.' );
end
% Find if parent has been supplied
parent = uiextras.findArg( 'Parent', varargin{:} );
if isempty( parent )
parent = gcf();
end
units = uiextras.findArg( 'Units', varargin{:} );
if isempty( units )
units = 'Normalized';
end
% Create container
args = {
'Parent', parent, ...
'Units', units, ...
'BorderType', 'none'
};
obj.UIContainer = uipanel( args{:} );
% Set the background color
obj.setPropertyFromDefault( 'BackgroundColor' );
% Tag it!
set( obj.UIContainer, 'Tag', strrep( class( obj ), '.', ':' ) );
% Create listeners to resizing of container
containerObj = handle( obj.UIContainer );
obj.Listeners{end+1,1} = handle.listener( containerObj, findprop( containerObj, 'PixelBounds' ), 'PropertyPostSet', @obj.onResized );
% Create listeners to addition of container children
obj.Listeners{end+1,1} = handle.listener( containerObj, 'ObjectChildAdded', @obj.onChildAddedEvent );
% Watch out for the graphics being destroyed
obj.Listeners{end+1,1} = handle.listener( containerObj, 'ObjectBeingDestroyed', @obj.onContainerBeingDestroyed );
% Store Container in container
setappdata( obj.UIContainer, 'Container', obj );
end % constructor
function container = double( obj )
%double Convert a container to an HG double handle.
%
% D = double(C) converts a container C to an HG handle D.
container = obj.UIContainer;
end % double
function pos = getpixelposition( obj )
%getpixelposition get the absolute pixel position
%
% POS = GETPIXELPOSITION(C) gets the absolute position of the container C
% within its parent window. The returned position is in pixels.
pos = getpixelposition( obj.UIContainer );
end % getpixelposition
function tf = isprop( obj, name )
%isprop does this object have the specified property
%
% TF = ISPROP(C,NAME) checks whether the object C has a
% property named NAME. The result, TF, is true if the
% property exists, false otherwise.
tf = ismember( name, properties( obj ) );
end % isprop
function p = ancestor(obj,varargin)
%ancestor Get object ancestor
%
% P = ancestor(H,TYPE) returns the handle of the closest ancestor of h
% that matches one of the types in TYPE, or empty if there is no matching
% ancestor. TYPE may be a single string (single type) or cell array of
% strings (types). If H is a vector of handles then P is a cell array the
% same length as H and P{n} is the ancestor of H(n). If H is one of the
% specified types then ancestor returns H.
%
% P = ANCESTOR(H,TYPE,'TOPLEVEL') finds the highest level ancestor of one
% of the types in TYPE
%
% If H is not an Handle Graphics object, ANCESTOR returns empty.
p = ancestor( obj.UIContainer, varargin{:} );
end %ancestor
function delete( obj )
%delete destroy this layout
%
% If the user destroys the object, we *must* also remove any
% graphics
if ~isempty( obj.DeleteFcn )
uiextras.callCallback( obj.DeleteFcn, obj, [] );
end
if ishandle( obj.UIContainer ) ...
&& ~strcmpi( get( obj.UIContainer, 'BeingDeleted' ), 'on' )
delete( obj.UIContainer );
end
end % delete
end % public methods
methods
function set.Position( obj, value )
set( obj.UIContainer, 'Position', value );
end % set.Position
function value = get.Position( obj )
value = get( obj.UIContainer, 'Position' );
end % get.Position
function set.Children( obj, value )
% Check
oldChildren = obj.Children_;
newChildren = value;
[tf, loc] = ismember( oldChildren, newChildren );
if ~isequal( size( oldChildren ), size( newChildren ) ) || any( ~tf )
error( 'GUILayout:Container:InvalidPropertyValue', ...
'Property ''Children'' may only be set to a permutation of itself.' )
end
% Set
obj.Children_ = newChildren;
% Reorder ChildListeners
obj.ChildListeners(loc,:) = obj.ChildListeners;
% Redraw
obj.redraw();
end % set.Children
function value = get.Children( obj )
value = obj.Children_;
end % get.Children
function set.Enable( obj, value )
% Check
if ~ischar( value ) || ~ismember( lower( value ), {'on','off'} )
error( 'GUILayout:Container:InvalidPropertyValue', ...
'Property ''Enable'' may only be set to ''on'' or ''off''.' )
end
% Apply
value = lower( value );
% If we want to switch on but our parent is off, just store
% in the app data.
if strcmp( value, 'on' )
if isappdata( obj.Parent, 'Container' )
parentObj = getappdata( obj.Parent, 'Container' );
if strcmpi( parentObj.Enable, 'off' )
setappdata( obj.UIContainer, 'OldEnableState', value );
value = 'off';
end
end
end
obj.Enable_ = value;
% Apply to children
ch = obj.Children_;
for ii=1:numel( ch )
obj.helpSetChildEnable( ch(ii), obj.Enable_ );
end
% Do the work
obj.onEnable( obj, value );
end % set.Enable
function value = get.Enable( obj )
value = obj.Enable_;
end % get.Enable
function set.Units( obj, value )
set( obj.UIContainer, 'Units', value );
end % set.Units
function value = get.Units( obj )
value = get( obj.UIContainer, 'Units' );
end % get.Units
function set.Parent( obj, value )
set( obj.UIContainer, 'Parent', double( value ) );
end % set.Parent
function value = get.Parent( obj )
value = get( obj.UIContainer, 'Parent' );
end % get.Parent
function set.Tag( obj, value )
set( obj.UIContainer, 'Tag', value );
end % set.Tag
function value = get.Tag( obj )
value = get( obj.UIContainer, 'Tag' );
end % get.Tag
function value = get.Type( obj )
value = class( obj );
end % get.Type
function value = get.BeingDeleted( obj )
value = get( obj.UIContainer, 'BeingDeleted' );
end % get.BeingDeleted
function set.Visible( obj, value )
set( obj.UIContainer, 'Visible', value );
end % set.Visible
function value = get.Visible( obj )
value = get( obj.UIContainer, 'Visible' );
end % get.Visible
function set.BackgroundColor( obj, value )
set( obj.UIContainer, 'BackgroundColor', value );
obj.onBackgroundColorChanged( obj, value );
end % set.BackgroundColor
function value = get.BackgroundColor( obj )
value = get( obj.UIContainer, 'BackgroundColor' );
end % get.BackgroundColor
end % accessor methods
methods( Access = protected )
function onResized( obj, source, eventData ) %#ok<INUSD>
%onResized Callback that fires when a container is resized.
newSize = getpixelposition( obj );
newSize = newSize([3,4]);
if any(newSize ~= obj.CurrentSize_)
% Size has changed, so must redraw
obj.CurrentSize_ = newSize;
obj.redraw();
end
end % onResized
function onContainerBeingDestroyed( obj, source, eventData ) %#ok<INUSD>
%onContainerBeingDestroyed Callback that fires when the container dies
delete( obj );
end % onContainerBeingDestroyed
function onChildAdded( obj, source, eventData ) %#ok<INUSD>
%onChildAdded Callback that fires when a child is added to a container.
obj.redraw();
end % onChildAdded
function onChildRemoved( obj, source, eventData ) %#ok<INUSD>
%onChildRemoved Callback that fires when a container child is destroyed or reparented.
obj.redraw();
end % onChildRemoved
function onBackgroundColorChanged( obj, source, eventData ) %#ok<INUSD,MANU>
%onBackgroundColorChanged Callback that fires when the container background color is changed
end % onChildRemoved
function onEnable( obj, source, eventData ) %#ok<INUSD,MANU>
%onEnable Callback that fires when the enable state is changed
end % onChildRemoved
function c = getValidChildren( obj )
%getValidChildren Return a list of only those children not being deleted
c = obj.Children;
c( strcmpi( get( c, 'BeingDeleted' ), 'on' ) ) = [];
end % getValidChildren
function repositionChild( obj, child, position )
%repositionChild adjust the position and visibility of a child
if position(3)<=0 || position(4)<=0
% Not enough space, so move offscreen instead
set( child, 'Position', [-100 -100 10 10] );
else
% There's space, so make sure visibility is on
% First determine whether to use "Position" or "OuterPosition"
if isprop( child, 'ActivePositionProperty' )
propname = get( child, 'ActivePositionProperty' );
else
propname = 'Position';
end
% Now set the position in pixels, changing the units first if
% necessary
oldunits = get( child, 'Units' );
if strcmpi( oldunits, 'Pixels' )
set( child, propname, position );
else
% Other units, so switch to pixels before setting
set( child, 'Units', 'pixels' );
set( child, propname, position );
set( child, 'Units', oldunits );
end
end
end % repositionChild
function setPropertyFromDefault( obj, propName )
%getPropertyDefault Retrieve a default property value. If the
%value is not found in the parent or any of its ancestors the
%supplied defValue is used.
error( nargchk( 2, 2, nargin ) );
parent = get( obj.UIContainer, 'Parent' );
myClass = class(obj);
if strncmp( myClass, 'uiextras.', 9 )
myClass = myClass(10:end);
end
defPropName = ['Default',myClass,propName];
% Getting the default will fail if the default does not exist
% of has an invalid value. In that case we leave the current
% value as it is.
try
obj.(propName) = uiextras.get( parent, defPropName );
catch err %#ok<NASGU>
% Failed, so leave it alone
end
end % setPropertyFromDefault
function helpSetChildEnable( ~, child, state )
% Set the enabled state of one child widget
if strcmpi( get( child, 'Type' ), 'uipanel' )
% Might be another layout
if isappdata( child, 'Container' )
child = getappdata( child, 'Container' );
else
% Can't enable a panel
child = [];
end
elseif isprop( child, 'Enable' )
% It supports enabling directly
else
% Doesn't support enabling
child = [];
end
if ~isempty( child )
% We will use a piece of app data
% to track the original state to ensure we don't
% re-enable something that shouldn't be.
if strcmpi( state, 'On' )
if isappdata( child, 'OldEnableState' )
set( child, 'Enable', getappdata( child, 'OldEnableState' ) );
rmappdata( child, 'OldEnableState' );
else
set( child, 'Enable', 'on' );
end
else
if ~isappdata( child, 'OldEnableState' )
setappdata( child, 'OldEnableState', get( child, 'Enable' ) );
end
set( child, 'Enable', 'off' );
end
end
end % helpSetChildEnable
end % protected methods
methods( Abstract = true, Access = protected )
redraw( obj )
end % abstract methods
methods( Access = private, Sealed = true )
function onChildAddedEvent( obj, source, eventData ) %#ok<INUSL>
%onChildAddedEvent Callback that fires when a child is added to a container.
% Find child in Children
child = eventData.Child;
if ismember( child, obj.Children_ )
return % not *really* being added
end
% Only hook up internally if not a "hidden" child.
if ~isprop( child, 'HandleVisibility' ) ...
|| strcmpi( get( child, 'HandleVisibility' ), 'off' )
return;
end
% We don't want to do anything to the panel title
if isappdata( obj.UIContainer, 'PanelTitleCreate' ) ...
&& getappdata( obj.UIContainer, 'PanelTitleCreate' )
% This child is the panel label. Set its visibility off so
% we don't see it again.
set( child, 'HandleVisibility', 'off' );
return;
end
% We also need to ignore legends as they are positioned by
% their associated axes.
if isa( child, 'axes' ) && strcmpi( get( child, 'Tag' ), 'legend' )
return;
end
% Add element to Children
obj.Children_(end+1,:) = child;
% Add elements to ChildListeners. A bug in R2009a and
% earlier means we have to be careful about this
if isBeforeR2009b()
obj.ChildListeners(end+1,:) = ...
{handle.listener( child, 'ObjectBeingDestroyed', {@helpDeleteChild,obj} ), ...
handle.listener( child, 'ObjectParentChanged', {@helpReparentChild,obj} )};
else
obj.ChildListeners(end+1,:) = ...
{handle.listener( child, 'ObjectBeingDestroyed', @obj.onChildBeingDestroyedEvent ), ...
handle.listener( child, 'ObjectParentChanged', @obj.onChildParentChangedEvent )};
end
% We are taking over management of position and will do it
% in either pixel or normalized units.
units = lower( get( child, 'Units' ) );
if ~ismember( units, {'pixels' ,'normalized'} )
set( child, 'Units', 'Pixels' );
end
% If we are disabled, make sure the children are too
if strcmpi( obj.Enable_, 'off' )
helpSetChildEnable( obj, child, obj.Enable_ );
end
% Call onChildAdded
eventData = uiextras.ChildEvent( child, numel( obj.Children_ ) );
obj.onChildAdded( obj, eventData );
end % onChildAddedEvent
function onChildBeingDestroyedEvent( obj, source, eventData ) %#ok<INUSD>
%onChildBeingDestroyedEvent Callback that fires when a container child is destroyed.
% Find child in Children
[dummy, loc] = ismember( source, obj.Children_ ); %#ok<ASGLU>
% Remove element from Children
obj.Children_(loc,:) = [];
% Remove elements from ChildListeners
obj.ChildListeners(loc,:) = [];
% If we are in our death throes, don't start calling callbacks
if ishandle( obj.UIContainer ) && ~strcmpi( get( obj.UIContainer, 'BeingDeleted' ), 'ON' )
% Call onChildRemoved
eventData = uiextras.ChildEvent( source, loc );
obj.onChildRemoved( obj, eventData );
end
end % onChildBeingDestroyedEvent
function onChildParentChangedEvent( obj, source, eventData )
%onChildParentChangedEvent Callback that fires when a container child is reparented.
if isempty( eventData.NewParent ) ...
|| eventData.NewParent == obj.UIContainer
return % not being reparented *away*
end
% Find child in Children
[dummy, loc] = ismember( source, obj.Children_ ); %#ok<ASGLU>
% Remove element from Children
obj.Children_(loc,:) = [];
% Remove elements from ChildListeners
obj.ChildListeners(loc,:) = [];
% Call onChildRemoved
eventData = uiextras.ChildEvent( source, loc );
obj.onChildRemoved( obj, eventData );
end % onChildParentChangedEvent
end % private sealed methods
end % classdef
% -------------------------------------------------------------------------
% Helper functions to work around a bug in R2009a and earlier
function ok = isBeforeR2009b()
persistent matlabVersionDate;
if isempty( matlabVersionDate )
v = ver( 'MATLAB' );
matlabVersionDate = datenum( v.Date );
% uiwait( msgbox( sprintf( 'Got MATLAB version date: %s', v.Date ) ) )
end
ok = ( matlabVersionDate <= datenum( '15-Jan-2009', 'dd-mmm-yyyy' ) );
end
function helpDeleteChild( src, evt, obj )
obj.onChildBeingDestroyedEvent( src, evt );
end % helpDeleteChild
function helpReparentChild( src, evt, obj )
obj.onChildParentChangedEvent( src, evt );
end % helpReparentChild
|
github
|
jacksky64/imageProcessing-master
|
loadLayoutIcon.m
|
.m
|
imageProcessing-master/Matlab Slicer/imStacks/+uiextras/loadLayoutIcon.m
| 3,144 |
utf_8
|
978b9b2fbeb6c98ed1c9a5dd59865fca
|
function cdata = loadLayoutIcon(imagefilename,bgcol)
%loadLayoutIcon Load an icon and set the transparent color
%
% cdata = uiextras.loadLayoutIcon(filename) tries to load the icon specified by
% filename. If the icon is a PNG file with transparency then transparent
% pixels are set to NaN. If not, then any pixel that is pure green is set
% to transparent (i.e. "green screen"). The resulting CDATA is an RGB
% double array.
%
% cdata = uiextras.loadLayoutIcon(filename,bgcol) tries to merge with the
% specified background colour bgcol. Fully transparent pixels are still
% set to NaN, but partially transparent ones are merged with the
% background.
%
% See also: IMREAD
% Copyright 2005-2010 The MathWorks Ltd.
% $Revision: 288 $
% $Date: 2010-07-14 12:23:50 +0100 (Wed, 14 Jul 2010) $
error( nargchk( 1, 2, nargin ) );
if nargin < 2
bgcol = get( 0, 'DefaultUIControlBackgroundColor' );
end
% First try normally
this_dir = fileparts( mfilename( 'fullpath' ) );
icon_dir = fullfile( this_dir, 'Resources' );
if exist( imagefilename, 'file' )
[cdata,map,alpha] = imread( imagefilename );
elseif exist( fullfile( icon_dir, imagefilename ), 'file' )
[cdata,map,alpha] = imread( fullfile( icon_dir, imagefilename ));
else
error( 'GUILayout:loadIcon:FileNotFound', 'Cannot open file ''%s''.', imagefilename );
end
if ~isempty( map )
cdata = ind2rgb( cdata, map );
end
% Convert to double before applying transparency
cdata = convertToDouble( cdata );
[rows,cols,depth] = size( cdata ); %#ok<NASGU>
if ~isempty( alpha )
alpha = convertToDouble( alpha );
f = find( alpha==0 );
if ~isempty( f )
cdata(f) = nan;
cdata(f + rows*cols) = nan;
cdata(f + 2*rows*cols) = nan;
end
% Now blend partial alphas
f = find( alpha(:)>0 & alpha(:)<1 );
if ~isempty(f)
cdata(f) = cdata(f).*alpha(f) + bgcol(1)*(1-alpha(f));
cdata(f + rows*cols) = cdata(f + rows*cols).*alpha(f) + bgcol(2)*(1-alpha(f));
cdata(f + 2*rows*cols) = cdata(f + 2*rows*cols).*alpha(f) + bgcol(3)*(1-alpha(f));
end
else
% Instead do a "green screen", treating anything pure-green as transparent
f = find((cdata(:,:,1)==0) & (cdata(:,:,2)==1) & (cdata(:,:,3)==0));
cdata(f) = nan;
cdata(f + rows*cols) = nan;
cdata(f + 2*rows*cols) = nan;
end
%-------------------------------------------------------------------------%
function cdata = convertToDouble( cdata )
% Convert an image to double precision in the range 0 to 1
switch lower( class( cdata ) )
case 'double'
% Do nothing
case 'single'
cdata = double( cdata );
case 'uint8'
cdata = double( cdata ) / 255;
case 'uint16'
cdata = double( cdata ) / 65535;
case 'int8'
cdata = ( double( cdata ) + 128 ) / 255;
case 'int16'
cdata = ( double( cdata ) + 32768 ) / 65535;
otherwise
error( 'GUILayout:LoadIcon:BadCData', ...
'Image data of type ''%s'' is not supported.', class( cdata ) );
end
|
github
|
jacksky64/imageProcessing-master
|
slicer.m
|
.m
|
imageProcessing-master/Matlab Slicer/imStacks/oldSlicer/slicer.m
| 64,794 |
utf_8
|
43e52862e3ac94765c312862049ce1bb
|
function varargout = slicer(varargin)
%SLICER Interactive visualization of 3D images
%
% SLICER is an graphical interface to explore slices of a 3D image.
% Index of the current slice is given under the slider, mouse position as
% well as cursor value are indicated when mouse is moved over image, and
% scrollbars allow to navigate within image.
%
% SLICER should work with any kind of 3D images: binary, gray scale
% (integer or floating-point) or color RGB.
%
% slicer(IMG)
% where IMG is a preloaded M*N*P matrix, opens the slicer GUI,
% initialized with image IMG.
% User can change current slice with the slider to the left, X and Y
% position with the two corresponding sliders, and change the zoom in the
% View menu.
%
% slicer(IMGNAME, ...)
% Load the stack specified by IMGNAME. It can be either a tif bundle, the
% first file of a series, or a 3D image stored in one of the medical
% image format:
% * DICOM (*.dcm)
% * Analyze (*.hdr)
% * MetaImage (*.mhd, *.mha)
% It is also possible to import a raw data file, from the File->Import
% menu.
%
% slicer
% without argument opens a dialog to read a file (either a set of slices
% or a bundle-stack).
%
% slicer(..., PARAM, VALUE)
% Specifies one or more display options as name-value parameter pairs.
% Available parameter names are:
% * 'slice' the display uses slice given by VALUE as current slice
% * 'position' VALUE contains a 1-by-2 vector corresponding to the
% (x,y) indices of the upper-left displayed pixel, starting from 1,
% and up to the number of voxels in that dimension
% * 'zoom' set up the initial zoom (the ratio between the number
% of voxels, or user units for calibrated images, and the number of
% points on the screen).
% * 'name' gives a name to the image (for display in title bar)
% * 'spacing' specifies the size of voxel elements. VALUE is a 1-by-3
% row vector containing spacing in x, y and z direction.
% * 'origin' specifies coordinate of first voxel in user space
% * 'displayRange' the values of min and max gray values to display. The
% default behaviour is to use [0 255] for uint8 images, or to
% compute bounds such as 95% of the voxels are converted to visible
% gray levels for other image types.
%
% Requires:
% * readstack for importing stacks
% * Image Processing Toolbox for reading 2D and 3D images
%
% Examples:
% % Explore 3D image stored in 3D Analyze format
% metadata = analyze75info('brainMRI.hdr');
% IMG = analyze75read(metadata);
% slicer(IMG);
%
% % show the 10-th slice, with initial magnification equal to 8
% slicer(IMG, 'slice', 10, 'zoom', 8, 'name', 'Brain');
%
% ---------
% author: David Legland, david.legland(at)grignon.inra.fr
% INRA - Cepia Software Platform
% created the 21/11/2003
% http://www.pfl-cepia.inra.fr/index.php?page=slicer
% HISTORY
% 28/06/2004 allows small images
% 15/10/2004 add slider for positioning, zoom, and possibility to load
% images
% 18/10/2004 correct bug for input image type (was set to uint8), and
% in positioning. Also add remembering of last opened path.
% 19/10/2004 correct bugs in display (view window too large)
% 26/10/2004 correct bug for color images (were seen as gray-scale)
% 25/03/2005 add size of image in title, and starting options
% 29/03/2005 automatically find best zoom when starting, if no zoom is
% specified. Add doc.
% 21/02/2006 adapt to windows file format
% 11/08/2006 display value of clicked points
% 14/11/2006 add possibility to use slicer('imageName.tif');
% 30/11/2006 correct bug for binary images introduced with last modif.
% 06/12/2006 another bug correction for control on images
% 08/08/2007 improve control on coordinate of clicked pixel
% 05/01/2010 remove buttons, and put zooms in menu
% 06/01/2010 change license, update help, add histogram
% 09/03/2010 use dim(1)=x, dim(2)=y
% 09/03/2010 add support for voxel spacing, change input options syntax
% 10/03/2010 update help, add more input options, update pixel display
% 20/06/2010 add a dialog to change image resolution
% 22/06/2010 keep grayscale range when transforming image, add about dlg
% 12/10/2010 add support to vector images (display the vector norm)
% 19/10/2010 add shortcuts and menu shortcuts
% 22/10/2010 add support for import of raw stacks
% 25/10/2010 change management of 3D rotations
% 05/11/2010 display RGB histogram as 3 separate bands
% 10/11/2010 add support for Look-Up Tables, clean up menus
% 11/01/2011 fix calibration bugs, update display
% 02/03/2011 add support for single color LUTs
% 27/04/2011 read indexed dicom images, rewrite image import
% 27/04/2011 enhance histogram and display of float RGB
% 12/08/2011 fix bug when running without input
% 29/08/2011 add support for continuous z-sliding
% Last Modified by GUIDE v2.5 26-Apr-2011 10:57:02
% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @slicer_OpeningFcn, ...
'gui_OutputFcn', @slicer_OutputFcn, ...
'gui_LayoutFcn', [] , ...
'gui_Callback', []);
if nargin && ischar(varargin{1})
gui_State.gui_Callback = str2func(varargin{1});
end
if nargin && isnumeric(varargin{1})
varargin = [varargin(1) {'name', inputname(1)} varargin(2:end)];
end
if nargout
[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT
% ===========================================================
%% Initialization functions
% --- Executes just before slicer is made visible.
function slicer_OpeningFcn(hObject, eventdata, handles, varargin) %#ok<INUSL>
% 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 slicer (see VARARGIN)
% Choose default command line output for slicer
handles.output = hObject;
% set up global options
handles.view = [512 512]; % in pixels
handles.lastPath = pwd;
handles.titlePattern = 'Slicer - %s [%dx%dx%d] - %g:%g';
handles.pixelCoordRounded = true;
% reset image information
handles = resetImageData(handles);
% attach a listener for mouse wheel scrolling
set(handles.mainFrame, 'WindowScrollWheelFcn', @mouseWheelScrolled);
% setup listeners for slider continuous changes
hListener = handle.listener(handles.moveZSlider, 'ActionEvent', ...
@moveZSlider_Callback2);
setappdata(handles.moveZSlider, 'sliderListeners', hListener);
% Update handles structure
guidata(hObject, handles);
% if no image specified, open a dialog to choose the file to load
if isempty(varargin)
showLoadImageDialog(handles);
handles = guidata(hObject);
% in case the user cancels, display an empty image
if isempty(get(handles.imageDisplay, 'UserData'))
% initialize with a default image
img = zeros([256, 256, 10], 'uint8');
img(:) = 255;
set(handles.imageDisplay, 'UserData', img);
handles = setupImage(handles);
end
else
var = varargin{1};
if isnumeric(var) || islogical(var)
% when input is a 3D or 4D numeric array, use it as image data
if length(size(var)) < 3
error('Input should be a 3 or 4 dimensions matrix');
end
set(handles.imageDisplay, 'UserData', var);
handles = setupImage(handles);
elseif ischar(var)
% if a character string is given, try to load from an image file
importImageDataFile(handles, var);
handles = guidata(handles.mainFrame);
elseif isa(var, 'Image')
% Try to interpret as Image object (not included in default slicer)
if ndims(var) ~= 3
error('Need an <Image> object with dimension 3');
end
set(handles.imageDisplay, 'UserData', getBuffer(var));
handles = setupImage(handles);
% extract image name
name = var.name;
if ~isempty(name)
handles.imgName = name;
end
% extract spatial calibration
handles.voxelOrigin = var.origin;
handles.voxelSize = var.spacing;
handles.voxelSizeUnit = var.unitName;
else
error('First argument of "slicer" should be either an image or a string');
end
varargin(1) = [];
end
% Set current slice in the middle of the stack by default
handles.slice = ceil(handles.dim(3) / 2);
setSlice(handles);
% Parses other input arguments
handles = parseInputOptions(handles, varargin{:});
updateTitle(handles);
% Update handles structure
guidata(hObject, handles);
function handles = parseInputOptions(handles, varargin)
% Parse optional input arguments
% iterate over couples of input arguments
while length(varargin) > 1
param = varargin{1};
switch lower(param)
case 'slice'
% setup initial slice
pos = varargin{2};
handles.slice = pos(1);
case 'position'
% setup position of upper-left visible pixel (1-indexed)
pos = varargin{2};
handles.cornerPixel = pos(1:2);
case 'zoom'
% setup initial zoom
zoom = varargin{2};
if zoom > handles.zoomMin && zoom < handles.zoomMax
handles.zoom = zoom;
else
disp('slicer: zoom value outside allowed limits');
end
case 'spacing'
handles.voxelSize = varargin{2};
case 'origin'
handles.voxelOrigin = varargin{2};
case 'name'
handles.imgName = varargin{2};
case 'displayrange'
handles.grayscaleExtent = varargin{2};
otherwise
error(['Unknown parameter name: ' param]);
end
varargin(1:2) = [];
end
function handles = resetImageData(handles)
% Reset handles fields corresponding to image info to default values
% display info
% size of the view box, in pixels
handles.view = [512 512];
handles.dim = [10 10 10];
% index of current slice
handles.slice = 1;
% index of first visible pixel (x, y indices)
handles.cornerPixel = [1 1];
% position, in user unit, of first visible point in viewbox
handles.cornerPosition = [0 0];
% current zoom: mutliplier applied to user units when converted to pixel
handles.zoom = 1;
% TODO: zoomMin and zoomMax should depend on image
handles.zoomMin = 1 / 256;
handles.zoomMax = 256;
% Calibration info, in user unit, in xyz order
handles.voxelOrigin = [0 0 0];
handles.voxelSize = [1 1 1];
handles.voxelSizeUnit = '';
% grayscale calibration, will be initialized automatically
handles.grayscaleExtent = [];
% initialize image info flags
handles.color = false;
handles.vector = false;
% empty lut (corresponds to usual gray-scale)
handles.lut = [];
% meta info
% name of image
handles.imgName = '';
% meta-information obtained with rich formats (analyze, metaImage...)
% given as a structure, and dependent on fileformat used
handles.imgInfo = [];
function h_img = displayNewImage(handles)
% extract data
dim = handles.dim;
zoom = handles.zoom;
view = handles.view;
cdata = computeDisplayData(handles);
% reset current axis
cla(handles.imageDisplay);
hold on;
% create an empty image with the appropriate size and data,
% and init to the specified slice
if handles.color
% display as color image
h_img = imshow(cdata, 'parent', handles.imageDisplay);
else
% Display as gray-scale
% compute grayscale extent
extent = handles.grayscaleExtent;
% show grayscale image with appropriate display range
h_img = imshow(cdata, ...
'parent', handles.imageDisplay, ...
'DisplayRange', extent);
% apply image LUT
if isempty(handles.lut)
colormap(gray);
else
colormap(handles.lut);
end
end
% extract calibration data
spacing = handles.voxelSize(1:2);
origin = handles.voxelOrigin(1:2);
% set up appropriate axes
xdata = ([0 dim(1)-1] * spacing(1) + origin(1));
ydata = ([0 dim(2)-1] * spacing(2) + origin(2));
set(h_img, 'XData', xdata);
set(h_img, 'YData', ydata);
% user-coordinates of corner point
cornerPoint = (handles.cornerPixel - 1) .* spacing + origin;
% setup bounds of viewport: one half-pixel around each bound
viewMin = cornerPoint - spacing / 2;
viewMax = cornerPoint + view ./ zoom + spacing / 2;
set(handles.imageDisplay, 'XLim', [viewMin(1) viewMax(1)]);
set(handles.imageDisplay, 'YLim', [viewMin(2) viewMax(2)]);
% set up the gui options of image
hold on;
set(h_img, 'ButtonDownFcn', ...
'slicer(''imageDisplay_ButtonDownFcn'',gcbo,[],guidata(gcbo))');
set(gcf, 'WindowButtonMotionFcn', ...
'slicer(''imageDisplay_ButtonMotionFcn'',gcbo,[],guidata(gcbo))');
% update X and Y sliders
updateXYSliders(handles);
% update control for changing slice
zmax = dim(3);
zslice = handles.slice;
zslice = min(max(zslice, 1), zmax);
handles.slice = zslice;
updateZControls(handles);
updateTitle(handles);
function data = computeDisplayData(handles)
% Extract data to display as color or grayscale planar image
img = get(handles.imageDisplay, 'UserData');
zslice = handles.slice;
if handles.color
% display as color image
data = img(:, :, :, zslice);
elseif handles.vector
% in case of a vector image, display the norm of the vector
dim = size(img);
data = zeros(dim(1), dim(2));
for i = 1:size(img, 3)
data = data + double(img(:, :, i, zslice)) .^ 2;
end
data = sqrt(data);
else
% for grayscale images, simply extract the appropriate slice
data = img(:, :, zslice);
end
function setImageLUT(hObject, eventdata, handles, lutName) %#ok<INUSL,DEFNU>
% Change the LUT of the grayscale image, and refresh the display
% lut is specified by its name.
nGrays = 256;
if strmatch(lutName, 'inverted')
lut = repmat((255:-1:0)', 1, 3) / 255;
elseif strmatch(lutName, 'blue-gray-red')
lut = gray(nGrays);
lut(1,:) = [0 0 1];
lut(end,:) = [1 0 0];
elseif strmatch(lutName, 'colorcube')
img = get(handles.imageDisplay, 'userdata');
nLabels = round(max(img(:)));
map = colorcube(double(nLabels) + 2);
lut = [0 0 0; map(sum(map==0, 2)~=3 & sum(map==1, 2)~=3, :)];
elseif strmatch(lutName, 'redLUT')
lut = gray(nGrays);
lut(:, 2:3) = 0;
elseif strmatch(lutName, 'greenLUT')
lut = gray(nGrays);
lut(:, [1 3]) = 0;
elseif strmatch(lutName, 'blueLUT')
lut = gray(nGrays);
lut(:, 1:2) = 0;
elseif strmatch(lutName, 'yellowLUT')
lut = gray(nGrays);
lut(:, 3) = 0;
elseif strmatch(lutName, 'cyanLUT')
lut = gray(nGrays);
lut(:, 1) = 0;
elseif strmatch(lutName, 'magentaLUT')
lut = gray(nGrays);
lut(:, 2) = 0;
else
lut = feval(lutName, nGrays);
end
handles.lut = lut;
colormap(handles.imageDisplay, lut);
% update gui data
guidata(handles.mainFrame, handles);
function updateTitle(handles)
% set up title of the figure, containing name of figure and current zoom
% setup name
if isempty(handles.imgName)
imgName = 'Unknown Image';
else
imgName = handles.imgName;
end
% display new title
zoom = handles.zoom;
title = sprintf(handles.titlePattern, imgName, ...
handles.dim, max(1, zoom), max(1, 1/zoom));
set(handles.mainFrame, 'Name', title);
function setupSliderHandle(hd, mini, maxi, value, step)
% setup min, max,
set(hd, 'Min', mini);
set(hd, 'Max', maxi);
% compute step if not specified
if ~exist('step', 'var')
step = .05;
end
step2 = min(step*10, (maxi-mini)/2);
% setup step, or make slider invisible
eps = 1e-10;
if value-mini >= -eps && value-maxi <= eps && (maxi-mini) > eps
value = min(max(value, mini), maxi);
set(hd, 'value', value);
set(hd, 'sliderstep', [step step2]);
set(hd, 'Enable', 'on');
set(hd, 'Visible', 'on');
else
set(hd, 'sliderstep', [1 1]);
set(hd, 'Visible', 'off');
end
function [mini maxi] = computeGrayScaleExtent(img)
% compute grayscale extent of a grayscale image
% check image data type
if isa(img, 'uint8')
% use min-max values depending on image type
[mini maxi] = computeTypeExtent(img);
elseif islogical(img)
% for binary images, the grayscale extent is defined by the type
mini = 0;
maxi = 1;
elseif ndims(img) > 3
% case of vector image: compute max of norm
dim = size(img);
norm = zeros(dim([1 2 4]));
for i = 1:dim(3)
norm = norm + squeeze(img(:,:,i,:)) .^ 2;
end
mini = 0;
maxi = sqrt(max(norm(:)));
else
% for float images, display 99 percents of dynamic
[mini maxi] = computeGrayscaleAdjustement(img, .01);
end
function [mini maxi] = computeTypeExtent(img)
% use min-max values depending on image type
type = class(img);
mini = intmin(type);
maxi = intmax(type);
% if image has only positive values, use 0 as min
if min(img(:)) >= 0
mini = 0;
end
function [mini maxi] = computeExtremeValues(img) %#ok<DEFNU>
% compute min and max (finite) values in image
mini = min(img(isfinite(img)));
maxi = max(img(isfinite(img)));
% If the difference is too small, use default range check
if abs(maxi-mini) < 1e-12
warning('Slicer:Grayscale', ...
'could not determine grayscale extent from data');
mini = 0;
maxi = 1;
end
function [mini maxi] = computeGrayscaleAdjustement(img, alpha)
% compute grayscale range that maximize vizualisation
% use default value for alpha if not specified
if nargin == 1
alpha = .01;
end
% extreme values in image
minValue = min(img(isfinite(img)));
maxValue = max(img(isfinite(img)));
% compute histogram
x = linspace(double(minValue), double(maxValue), 10000);
h = hist(double(img(:)), x);
% special case of images with black background
if h(1) > sum(h) * .2
x = x(2:end);
h = h(2:end);
end
cumh = cumsum(h);
cdf = cumh / cumh(end);
% find indices of extreme values
ind1 = find(cdf >= alpha/2, 1, 'first');
ind2 = find(cdf <= 1-alpha/2, 1, 'last');
% compute grascale extent
mini = floor(x(ind1));
maxi = ceil(x(ind2));
% small control to avoid mini==maxi
if abs(maxi - mini) < 1e-12
mini = minValue;
maxi = maxValue;
if abs(maxi - mini) < 1e-12
mini = 0;
maxi = 1;
end
end
% --- Outputs from this function are returned to the command line.
function varargout = slicer_OutputFcn(hObject, eventdata, handles) %#ok<INUSL>
% 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 during object creation, after setting all properties.
function moveZSlider_CreateFcn(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to moveZSlider (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, change
% 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor',[.9 .9 .9]);
else
set(hObject, 'BackgroundColor',...
get(0,'defaultUicontrolBackgroundColor')); %#ok<UNRCH>
end
% ===========================================================
%% General purpose functions
% ------------------------------------------------
function setSlice(handles)
% change the current slice.
% slice number is the third value of field POS in handles.
% get slice
slice = handles.slice;
% change inner data of image
cdata = computeDisplayData(handles);
set(handles.h_img, 'CData', cdata);
% update gui information for slider and textbox
set(handles.moveZSlider, 'Value', slice);
set(handles.sliceNumberText, 'String', num2str(slice));
% update gui data
guidata(handles.mainFrame, handles);
% ------------------------------------------------
function setZoom(handles)
% Update zoom of current display
% handles structure with handles and user data (see GUIDATA)
zoom = handles.zoom;
% check zoom has valid values
if zoom > handles.zoomMax || zoom < handles.zoomMin
disp('zoom value out of bounds');
return;
end
% compute display extent, in physical coordinates
xlim = get(handles.imageDisplay, 'XLim');
ylim = get(handles.imageDisplay, 'YLim');
viewSize = handles.view/zoom;
viewCorner1 = [xlim(1) ylim(1)];
viewCorner2 = viewCorner1 + viewSize;
%
imageExtent = computeImagePhysicalExtent(handles);
if viewCorner2(1) > imageExtent(2)
viewCorner1(1) = imageExtent(1);
end
if viewCorner2(2) > imageExtent(4)
viewCorner1(2) = imageExtent(3);
end
viewCorner2 = viewCorner1 + viewSize;
set(handles.imageDisplay, 'XLim', [viewCorner1(1) viewCorner2(1)]);
set(handles.imageDisplay, 'YLim', [viewCorner1(2) viewCorner2(2)]);
handles.cornerPosition = viewCorner1;
% update title of the frame
updateTitle(handles);
updateXYSliders(handles);
% gui data already updated in updateXYSLiders
%guidata(handles.mainFrame, handles);
function updateXYSliders(handles)
% update sliders for x and y positions
% current zoom
zoom = handles.zoom;
% set up appropriate axes
xlim = get(handles.imageDisplay, 'XLim');
ylim = get(handles.imageDisplay, 'YLim');
% image extent in physical coordinates
imageExtent = computeImagePhysicalExtent(handles);
% size of viewbox in user units
viewSize = handles.view / zoom;
% compute limit for x slider bar
xmin = imageExtent(1);
xmax = imageExtent(2) - viewSize(1);
hd = handles.moveXSlider;
setupSliderHandle(hd, xmin, xmax, xlim(1), .01);
% compute limit for y slider bar
ymin = imageExtent(3);
ymax = imageExtent(4) - viewSize(2);
hd = handles.moveYSlider;
setupSliderHandle(hd, ymin, ymax, ymax-ylim(1)+ymin, .01);
guidata(handles.mainFrame, handles);
function chooseCenterSlice(handles)
% max possible slice
zmax = handles.dim(3);
% setup current slice
handles.slice = ceil(zmax / 2);
% update controls
updateZControls(handles);
setSlice(handles);
function updateZControls(handles)
% update controls for changing slice
% max possible slice
zmax = handles.dim(3);
% check current slice is valid
zslice = handles.slice;
zslice = min(max(zslice, 1), zmax);
handles.slice = zslice;
% update slice slider
hd = handles.moveZSlider;
setupSliderHandle(hd, 1, zmax, zslice, 1/zmax);
% update text area
set(handles.sliceNumberText, 'String', num2str(zslice));
function extent = computeImagePhysicalExtent(handles)
dim = handles.dim;
spacing = handles.voxelSize;
origin = handles.voxelOrigin;
p0 = ([0 0 0] - .5) .* spacing + origin;
p1 = ( dim - .5) .* spacing + origin;
extent = [p0 ; p1];
extent = extent(:)';
% ------------------------------------------------
function setPosition(handles)
% change the position of top-left corner of view.
% - update axis limits
% - update X- and Y-sliders
pos = handles.cornerPosition;
% compute center of display, in physical coordinates
xlim = get(handles.imageDisplay, 'XLim');
ylim = get(handles.imageDisplay, 'YLim');
% extent of the view, in physical coord
viewSize = [xlim(2)-xlim(1) ylim(2)-ylim(1)];
% new position of upper-left corner of view port
pos2 = pos + viewSize;
set(handles.imageDisplay, 'xlim', [pos(1) pos2(1)]);
set(handles.imageDisplay, 'ylim', [pos(2) pos2(2)]);
set(handles.moveXSlider, 'Value', pos(1));
ymin = get(handles.moveYSlider, 'Min');
ymax = get(handles.moveYSlider, 'Max');
set(handles.moveYSlider, 'Value', ymax-pos(2)+ymin);
guidata(handles.mainFrame, handles);
% ===========================================================
% callback function for GUI components
% ----------------------------------------------------
%% callback functions for sliders
% --- Executes on slider movement.
function moveZSlider_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to moveZSlider (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
% compute new value from slicer position, and update textString
zslice = round(get(hObject, 'Value'));
zslice = max(get(hObject, 'Min'), min(get(hObject, 'Max'), zslice));
handles.slice = zslice;
setSlice(handles);
function moveZSlider_Callback2(hObject, eventdata, handles) %#ok<INUSD>
% compute new value from slicer position, and update textString
zslice = round(get(hObject, 'Value'));
zslice = max(get(hObject, 'Min'), min(get(hObject, 'Max'), zslice));
handles = guidata(gcbf);
handles.slice = zslice;
setSlice(handles);
% --- Executes on slider movement.
function moveXSlider_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to moveXSlider (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
% compute value inside of bounds
value = get(hObject, 'Value');
value = min(max(get(hObject, 'Min'), value), get(hObject, 'Max'));
% update GUI
handles.cornerPosition(1) = value;
setPosition(handles);
% --- Executes during object creation, after setting all properties.
function moveXSlider_CreateFcn(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to moveXSlider (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, change
% 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor',[.9 .9 .9]);
else
set(hObject,'BackgroundColor',...
get(0,'defaultUicontrolBackgroundColor')); %#ok<UNRCH>
end
% --- Executes on slider movement.
function moveYSlider_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to moveYSlider (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
% compute value inside of bounds
value = get(hObject, 'Value');
value = min(max(get(hObject, 'Min'), value), get(hObject, 'Max'));
value = get(hObject, 'Max')-value+get(hObject, 'Min');
% update GUI
handles.cornerPosition(2) = value;
setPosition(handles);
% --- Executes during object creation, after setting all properties.
function moveYSlider_CreateFcn(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to moveYSlider (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, change
% 'usewhitebg' to 0 to use default. See ISPC and COMPUTER.
usewhitebg = 1;
if usewhitebg
set(hObject,'BackgroundColor',[.9 .9 .9]);
else
set(hObject,'BackgroundColor',...
get(0,'defaultUicontrolBackgroundColor')); %#ok<UNRCH>
end
% ----------------------------------------------------
%% callback functions for text areas
% --- Executes during object creation, after setting all properties.
function sliceNumberText_CreateFcn(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to sliceNumberText (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
set(hObject,'BackgroundColor','white');
else
set(hObject,'BackgroundColor',get(0,'defaultUicontrolBackgroundColor'));
end
% --- Executes when a new text is typed in sliceNumberText
function sliceNumberText_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to sliceNumberText (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 sliceNumberText as text
% str2double(get(hObject,'String')) returns contents of sliceNumberText as a double
% get entered value for z-slice
zslice = str2double(get(hObject, 'String'));
% in case of wrong edit, set the string to current value of zslice
if isnan(zslice)
zslice = handles.slice;
end
% compute slice number, inside of image bounds
zslice = min(max(1, round(zslice)), handles.dim(3));
% update text and slider info
handles.slice = zslice;
setSlice(handles);
% ===========================================================
%% callback function for Menu components
% --------------------------------------------------------------------
function menuFiles_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to files (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% nothing to do ....
% --------------------------------------------------------------------
function itemOpen_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to itemOpen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
showLoadImageDialog(handles);
function showLoadImageDialog(handles)
% Display the dialog, determines imaeg type, and setup image accordingly
[filename, pathname] = uigetfile( ...
{'*.gif;*.jpg;*.jpeg;*.tif;*.tiff;*.bmp;*.hdr;*.dcm;*.mhd', ...
'All Image Files (*.tif, *.hdr, *.dcm, *.mhd, *.bmp, *.jpg)'; ...
'*.tif;*.tiff', 'TIF Files (*.tif, *.tiff)'; ...
'*.bmp', 'BMP Files (*.bmp)'; ...
'*.hdr', 'Mayo Analyze Files (*.hdr)'; ...
'*.dcm', 'DICOM Files (*.dcm)'; ...
'*.mhd;*.mha', 'MetaImage data files (*.mha, *.mhd)'; ...
'*.*', 'All Files (*.*)'}, ...
'Choose a stack or the first slice of a series:', ...
handles.lastPath);
if isequal(filename,0) || isequal(pathname,0)
return;
end
importImageDataFile(handles, fullfile(pathname, filename))
function importImageDataFile(handles, filename)
% Generic function to import data file
% dispatch to more specialized functions depending on file extension
[filepath basename ext] = fileparts(filename); %#ok<ASGLU>
switch lower(ext)
case {'.mhd', '.mha'}
importMetaImage(handles, filename);
case '.hdr'
importAnalyzeImage(handles, filename);
case '.dcm'
importDicomImage(handles, filename);
otherwise
readImageStack(handles, filename);
end
function readImageStack(handles, filename)
handles = resetImageData(handles);
img = readstack(filename);
set(handles.imageDisplay, 'userdata', img);
[pathname filename ext] = fileparts(filename);
handles.imgName = [filename ext];
handles.lastPath = pathname;
handles = setupImage(handles);
chooseCenterSlice(handles);
% --------------------------------------------------------------------
function menuImport_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuImport (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function itemImportDicom_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to itemImportDicom (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile( ...
{'*.dcm', 'DICOM Files (*.dcm)'; ...
'*.*', 'All Files (*.*)'}, ...
'Choose the DICOM File:', ...
handles.lastPath);
if isequal(filename,0) || isequal(pathname,0)
return;
end
importDicomImage(handles, fullfile(pathname, filename));
function importDicomImage(handles, filename)
% read image data
info = dicominfo(filename);
[img map] = dicomread(info);
img = squeeze(img);
% convert indexed image to true RGB image
if ~isempty(map)
dim = size(img);
inds = img;
img = zeros([dim(1) dim(2) 3 dim(3)]);
for i = 1:3
img(:,:,i,:) = reshape(map(inds(:), i), dim);
end
end
% update display
handles = resetImageData(handles);
set(handles.imageDisplay, 'userdata', img);
[pathname filename ext] = fileparts(filename);
handles.imgName = [filename ext];
handles.lastPath = pathname;
handles.imgInfo = info;
handles = setupImage(handles);
chooseCenterSlice(handles);
% --------------------------------------------------------------------
function itemImportAnalyze_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to itemImportAnalyze (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile( ...
{'*.hdr', 'Mayo Analyze Files (*.hdr)'; ...
'*.*', 'All Files (*.*)'}, ...
'Choose the Mayo Analyze header:', ...
handles.lastPath);
if isequal(filename,0) || isequal(pathname,0)
return;
end
importAnalyzeImage(handles, fullfile(pathname, filename));
function importAnalyzeImage(handles, filename)
info = analyze75info(filename);
handles = resetImageData(handles);
set(handles.imageDisplay, 'userdata', analyze75read(info));
% setup calibration
if isfield(info, 'PixelDimensions')
handles.voxelSize = info.('PixelDimensions');
end
if isfield(info, 'VoxelUnits')
handles.voxelSizeUnit = info.('VoxelUnits');
end
[pathname filename ext] = fileparts(filename);
handles.imgName = [filename ext];
handles.lastPath = pathname;
handles.imgInfo = info;
handles = setupImage(handles);
chooseCenterSlice(handles);
% --------------------------------------------------------------------
function itemImportInterfile_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to itemImportInterfile (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile( ...
{'*.hdr', 'Interfile header Files (*.hdr)'; ...
'*.*', 'All Files (*.*)'}, ...
'Choose the Interfile header:', ...
handles.lastPath);
if isequal(filename,0) || isequal(pathname,0)
return;
end
importInterfileImage(handles, fullfile(pathname, filename));
function importInterfileImage(handles, filename)
info = interfileinfo(filename);
handles = resetImageData(handles);
set(handles.imageDisplay, 'userdata', interfileread(info));
[pathname filename ext] = fileparts(filename);
handles.imgName = [filename ext];
handles.lastPath = pathname;
handles.imgInfo = info;
handles = setupImage(handles);
chooseCenterSlice(handles);
% --------------------------------------------------------------------
function itemImportMetaImage_Callback(hObject, eventdata, handles) %#ok<INUSL,DEFNU>
% hObject handle to itemImportMetaImage (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile( ...
{'*.mhd;*.mha', 'MetaImage data file(*.mha, *.mhd)'; ...
'*.*', 'All Files (*.*)'}, ...
'Choose the MetaImage header:', ...
handles.lastPath);
if isequal(filename,0) || isequal(pathname,0)
return;
end
importMetaImage(handles, fullfile(pathname, filename));
function importMetaImage(handles, filename)
info = metaImageInfo(filename);
handles = resetImageData(handles);
set(handles.imageDisplay, 'userdata', metaImageRead(info));
% setup calibration
if isfield(info, 'ElementSize')
handles.voxelSize = info.('ElementSize');
else
isfield(info, 'ElementSpacing')
handles.voxelSize = info.('ElementSpacing');
end
if isfield(info, 'ElementOrigin')
handles.voxelOrigin = info.('ElementOrigin');
end
% setup file infos
[pathname filename ext] = fileparts(filename);
handles.imgName = [filename ext];
handles.lastPath = pathname;
handles.imgInfo = info;
handles = setupImage(handles);
chooseCenterSlice(handles);
% --------------------------------------------------------------------
function itemImportRawData_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemImportRawData (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[filename, pathname] = uigetfile( ...
{'*.raw', 'Raw data file(*.raw)'; ...
'*.*', 'All Files (*.*)'}, ...
'Import Raw Data', ...
handles.lastPath);
if isequal(filename,0) || isequal(pathname,0)
return;
end
importRawDataImage(handles, fullfile(pathname, filename));
function importRawDataImage(handles, filename)
% dialog to choose image dimensions
answers = inputdlg(...
{'X Size (columns):', 'Y Size (rows):', 'Z Size (slices):'}, ...
'Input Image Dimensions',...
1, {'10', '10', '10'});
if isempty(answers)
return;
end
% parse dimensions
dims = [0 0 0];
for i = 1:3
num = str2num(answers{i}); %#ok<ST2NM>
if isempty(num)
errordlg(sprintf('Could not parse input number %d', i), ...
'Parsing error');
return;
end
dims(i) = num;
end
% dialog to choose data type
types = {'uint8', 'int8', 'uint16', 'int16', 'single', 'double'};
[selection, ok] = listdlg(...
'ListString', types, ...
'PromptString', 'Choose Data Type:', ...
'SelectionMode', 'single', ...
'Name', 'Data Type');
if ~ok
return;
end
% read raw stack (use correction of some bugs in 'readstack' function)
dataType = types{selection};
img = readstack(fullfile(pathname, filename), dataType, dims([2 1 3]));
img = permute(img, [2 1 3]);
handles = resetImageData(handles);
set(handles.imageDisplay, 'userdata', img);
% setup file infos
handles.imgName = filename;
handles.lastPath = pathname;
handles = setupImage(handles);
chooseCenterSlice(handles);
function handles = setupImage(handles)
% This function is called after an image has been loaded.
% Only image is valid. This function set up other fields from the
% values of current image, stored as userdata of 'imageDisplay' object.
%
% Returns the modified data structure
% get imag data
img = get(handles.imageDisplay, 'userdata');
% compute image dimension and determines if image is color or grayscale
dim = size(img);
% check image type
handles.color = false;
handles.vector = false;
if length(dim) > 3
valMin = min(img(:));
valMax = max(img(:));
% choose image nature
if dim(3) ~= 3 || valMin < 0 || (isfloat(img) && valMax > 1)
handles.vector = true;
else
handles.color = true;
end
% keep only spatial dimensions
dim = dim([1 2 4]);
end
% eventually compute grayscale extent
if ~handles.color
handles.grayscaleExtent = computeGrayScaleExtent(img);
[mini maxi] = computeGrayScaleExtent(img);
handles.grayscaleExtent = [mini maxi];
end
% conversion from Matlab convention to XYZ convention
dim = dim([2 1 3]);
handles.dim = dim;
% setup zoom
zoom = computeBestZoom(handles);
handles.zoom = zoom;
% display the new image
h_img = displayNewImage(handles);
handles.h_img = h_img;
% update gui data
guidata(handles.mainFrame, handles);
function zoom = computeBestRoundedZoom(handles)
% setup initial zoom: find best zoom, rounded to the closest power of 2.
% round zoom to closest power of 2
zoom = computeBestZoom(handles);
zoom = power(2, round(log2(zoom)));
function zoom = computeBestZoom(handles)
% find the zoom that best fit the greater dimension
% get data
dim = handles.dim;
view = handles.view;
spacing = handles.voxelSize;
% compute best zoom
zoom = min(view(1:2) ./ dim(1:2) ./ spacing(1:2));
% --------------------------------------------------------------------
function itemQuit_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemQuit (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
close(handles.mainFrame);
% --------------------------------------------------------------------
function menuImage_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuImage (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menuView_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuView (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function menuChangeLUT_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuChangeLUT (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function itemSetMatlabLut_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to itemSetMatlabLut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function setColorLut_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to setColorLut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function itemDisplayImageInfo_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemDisplayImageInfo (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
info = handles.imgInfo;
if isempty(info)
errordlg('No meta-information defined for this image', ...
'Image Error', 'modal');
return;
end
% extract field names
fields = fieldnames(info);
nFields = length(fields);
% create data table as a cell array of strings
data =cell(nFields, 2);
for i=1:nFields
data{i, 1} = fields{i};
dat = info.(fields{i});
if ischar(dat)
data{i,2} = dat;
elseif isnumeric(dat)
data{i,2} = num2str(dat);
else
data{i,2} = '...';
end
end
% create name for figure
if isempty(handles.imgName)
name = 'Image Metadata';
else
name = sprintf('MetaData for image <%s>', handles.imgName);
end
% creates and setup newfigure
f = figure('MenuBar', 'none', 'Name', name);
set(f, 'units', 'pixels');
pos = get(f, 'position');
width = pos(3);
% sum of width is not equal to 1 to avoid rounding errors.
columnWidth = {round(width * .30), round(width * .69)};
% display the data table
uitable(...
'Parent', f, ...
'Units','normalized',...
'Position', [0 0 1 1], ...
'Data', data, ...
'RowName', [], ...
'ColumnName', {'Name', 'Value'}, ...
'ColumnWidth', columnWidth, ...
'ColumnFormat', {'char', 'char'}, ...
'ColumnEditable', [false, false]);
% --------------------------------------------------------------------
function itemChangeVoxelSize_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemChangeVoxelSize (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% configure dialog
spacing = handles.voxelSize;
prompt = {...
'Size in X direction:', ...
'Size in Y direction:', ...
'Size in Z direction:', ...
'Unit name:'};
title = 'Image resolution';
defaultValues = [cellstr(num2str(spacing'))' {handles.voxelSizeUnit}];
% ask for answer
answer = inputdlg(prompt, title, 1, defaultValues);
if isempty(answer)
return;
end
for i = 1:3
spacing(i) = str2double(answer{i});
if isnan(spacing(i))
warning('slicer:parsing', 'could not parse resolution string');
return;
end
end
handles.voxelSize = spacing;
handles.voxelSizeUnit = answer{4};
% setup zoom
zoom = computeBestRoundedZoom(handles);
handles.zoom = zoom;
% display the new image
h_img = displayNewImage(handles);
handles.h_img = h_img;
% update gui data
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function menuGrayscaleRange_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuGrayscaleRange (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function itemGrayRangeImage_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemGrayRangeImage (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.color || handles.vector
return
end
% compute grayscale extent
img = get(handles.imageDisplay, 'userdata');
mini = min(img(:));
maxi = max(img(:));
% setup appropriate grayscale for image
set(get(handles.h_img, 'parent'), 'CLim', [mini maxi]);
% stores grayscale infos
handles.grayscaleExtent = [mini maxi];
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function itemGrayRangeDataType_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemGrayRangeDataType (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.color || handles.vector
return
end
img = get(handles.imageDisplay, 'userdata');
% compute grayscale extent
mini = 0;
maxi = 1;
if isinteger(img)
type = class(img);
mini = intmin(type);
maxi = intmax(type);
elseif isfloat(img)
mini = min(img(:));
maxi = max(img(:));
end
% setup appropriate grayscale for image
set(get(handles.h_img, 'parent'), 'CLim', [mini maxi]);
% stores grayscale infos
handles.grayscaleExtent = [mini maxi];
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function itemGrayRangeManual_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemGrayRangeManual (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
if handles.color || handles.vector
return
end
img = get(handles.imageDisplay, 'userdata');
% get extreme values for grayscale in image
minimg = min(img(:));
maximg = max(img(:));
% get actual value for grayscale range
ax = get(handles.h_img, 'parent');
clim = get(ax, 'CLim');
% define dialog options
if isinteger(minimg)
prompt = {...
sprintf('Min grayscale value (%d):', minimg), ...
sprintf('Max grayscale value (%d):', maximg)};
else
prompt = {...
sprintf('Min grayscale value (%f):', minimg), ...
sprintf('Max grayscale value (%f):', maximg)};
end
dlg_title = 'Input for grayscale range';
num_lines = 1;
def = {num2str(clim(1)), num2str(clim(2))};
% open the dialog
answer = inputdlg(prompt, dlg_title, num_lines, def);
% if user cancel, return
if isempty(answer)
return;
end
% convert input texts into numerical values
mini = str2double(answer{1});
maxi = str2double(answer{2});
% setup appropriate grayscale for image
set(get(handles.h_img, 'parent'), 'CLim', [mini maxi]);
% stores grayscale infos
handles.grayscaleExtent = [mini maxi];
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function menuTransform_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuTransform (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function itemRotateImageLeft_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemRotateImageLeft (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotateImage(handles, 3, -1);
% --------------------------------------------------------------------
function itemRotateImageRight_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemRotateImageRight (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotateImage(handles, 3, 1);
% --------------------------------------------------------------------
function itemRotateImageXUp_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemRotateImageXUp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotateImage(handles, 1, -1);
% --------------------------------------------------------------------
function itemRotateImageXDown_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemRotateImageXDown (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotateImage(handles, 1, 1);
% --------------------------------------------------------------------
function itemRotateImageYLeft_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemRotateImageYLeft (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotateImage(handles, 2, -1);
% --------------------------------------------------------------------
function itemRotateImageYRight_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemRotateImageYRight (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
rotateImage(handles, 2, 1);
function handles = rotateImage(handles, axis, n)
% Rotate the inner 3D image and the associated meta-information
% axis is given between 1 and 3, in XYZ convention
% n is the number of rotations (typically 1, 2, 3 or -1)
% extract image data
img = get(handles.imageDisplay, 'userdata');
% convert to ijk ordering
axis = xyz2ijk(axis);
% performs image rotation, and get axis permutation parameters
[img inds] = rotateStack90(img, axis, n);
set(handles.imageDisplay, 'userdata', img);
% permute meta info
handles.dim = handles.dim(inds);
handles.voxelSize = handles.voxelSize(inds);
handles.voxelOrigin = handles.voxelOrigin(inds);
% computes new best zoom
handles.zoom = computeBestRoundedZoom(handles);
% for rotation that imply z axis, need to change zslice
if axis ~= 3
% setup current slice in the middle of the stack
handles.slice = round(handles.dim(3)/2);
end
% display the new image
handles.h_img = displayNewImage(handles);
% need to update handles for h_img
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function itemFlipImageX_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemFlipImageX (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.imageDisplay, 'userdata', ...
flipdim(get(handles.imageDisplay, 'userdata'), 2));
% display the new image
handles.h_img = displayNewImage(handles);
% need to update handles for h_img
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function itemFlipImageY_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemFlipImageY (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set(handles.imageDisplay, 'userdata', ...
flipdim(get(handles.imageDisplay, 'userdata'), 1));
% display the new image
handles.h_img = displayNewImage(handles);
% need to update handles for h_img
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function itemFlipImageZ_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemFlipImageZ (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
dim = 3;
if handles.color || handles.vector
dim = 4;
end
set(handles.imageDisplay, 'userdata', ...
flipdim(get(handles.imageDisplay, 'userdata'), dim));
% display the new image
handles.h_img = displayNewImage(handles);
% need to update handles for h_img
guidata(handles.mainFrame, handles);
% --------------------------------------------------------------------
function itemShowOrthoSlices_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemShowOrthoSlices (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% get display data
pos = round(handles.dim / 2);
spacing = handles.voxelSize;
% create figure with 3 orthogonal slices
figure();
orthoSlices(get(handles.imageDisplay, 'userdata'), pos, spacing, ...
'DisplayRange', handles.grayscaleExtent, 'lut', handles.lut);
% --------------------------------------------------------------------
function itemShow3dOrthoSlices_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemShow3dOrthoSlices (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% get display data
pos = round(handles.dim / 2);
spacing = handles.voxelSize;
% create figure with 3 orthogonal slices
figure();
orthoSlices3d(get(handles.imageDisplay, 'userdata'), pos, spacing, ...
'DisplayRange', handles.grayscaleExtent, 'lut', handles.lut);
view(3);
% --------------------------------------------------------------------
function itemZoomIn_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemZoomIn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.zoom = handles.zoom*2;
setZoom(handles);
% --------------------------------------------------------------------
function itemZoomOut_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemZoomOut (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.zoom = handles.zoom/2;
setZoom(handles);
% --------------------------------------------------------------------
function itemZoomOne_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemZoomOne (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.zoom = 1;
setZoom(handles);
% --------------------------------------------------------------------
function itemZoomBest_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemZoomBest (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
handles.zoom = computeBestZoom(handles);
% update properties
setZoom(handles);
% --------------------------------------------------------------------
function itemViewHistogram_Callback(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% hObject handle to itemViewHistogram (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% create new figure
if isempty(handles.imgName)
name = 'Image Histogram';
else
name = ['Histogram of image ' handles.imgName];
end
figure('Name', name, 'NumberTitle', 'Off');
fprintf('Computing histogram...');
img = get(handles.imageDisplay, 'UserData');
% in the case of vector image, compute histogram of image norm
if handles.vector
img = sqrt(sum(double(img) .^ 2, 3));
end
if ~handles.color
% Process gray-scale image
[minimg maximg] = computeGrayScaleExtent(img);
x = linspace(double(minimg), double(maximg), 256);
hist(double(img(:)), x);
colormap jet;
elseif handles.color
% process RGB 3D image
% determine max value in the channels
if isinteger(img)
maxi = 255;
else
maxi = 1;
end
% compute histogram of each channel
h = zeros(256, 3);
x = linspace(0, maxi, 256);
for i = 1:3
im = img(:,:,i,:);
h(:,i) = hist(double(im(:)), x);
end
% display each color histogram as stairs, to see the 3 curves
hh = stairs(x, h);
set(hh(1), 'color', [1 0 0]); % red
set(hh(2), 'color', [0 1 0]); % green
set(hh(3), 'color', [0 0 1]); % blue
minimg = 0;
maximg = maxi;
end
fprintf(' done\n');
xlim([minimg maximg]);
% --------------------------------------------------------------------
function menuHelp_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to menuHelp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% nothing to do ....
% --------------------------------------------------------------------
function itemAbout_Callback(hObject, eventdata, handles) %#ok<INUSD,DEFNU>
% hObject handle to itemAbout (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
title = 'About Slicer';
info = dir(which('slicer'));
message = {...
' 3D Slicer for Matlab', ...
[' v ' datestr(info.datenum, 1)], ...
'', ...
' Author: David Legland', ...
'[email protected]', ...
' (c) INRA - Cepia', ...
''};
msgbox(message, title);
% --------------------------------------------------------------------
function imageDisplay_ButtonDownFcn(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% Update display of mouse coordinate and pixel value
% get axis coordinate of point, and convert to image coord
point = get(handles.imageDisplay, 'currentPoint');
displayPixelCoords(handles, point);
function imageDisplay_ButtonMotionFcn(hObject, eventdata, handles) %#ok<DEFNU,INUSL>
% Update display of mouse coordinate and pixel value
% get axis coordinate of point, and convert to image coord
point = get(handles.imageDisplay, 'currentPoint');
displayPixelCoords(handles, point);
function mouseWheelScrolled(hObject, eventdata)
handles = guidata(hObject);
newIndex = handles.slice - eventdata.VerticalScrollCount;
newIndex = min(max(newIndex, 1), handles.dim(3));
handles.slice = newIndex;
setSlice(handles);
function displayPixelCoords(handles, point)
point = point(1, 1:2);
coord = round(pointToIndex(handles, point));
% control on bounds of image
if sum(coord < 1) > 0 || sum(coord > handles.dim(1:2)) > 0
set(handles.pointValueText, 'string', '');
return;
end
% Display coordinates of clicked point
if sum(handles.voxelSize ~= 1) > 0
locString = sprintf('(x,y) = (%d,%d) px = (%5.2f,%5.2f) %s', ...
coord(1), coord(2), point(1), point(2), handles.voxelSizeUnit);
else
locString = sprintf('(x,y) = (%d,%d) px', coord(1), coord(2));
end
set(handles.pointXText, 'String', locString);
img = get(handles.imageDisplay, 'userdata');
% Display value of selected pixel
if handles.color
% case of color pixel: values are red, green and blue
rgb = img(coord(2), coord(1), :, handles.slice);
if isinteger(rgb)
pattern = 'RGB=(%d %d %d)';
else
pattern = 'RGB=(%g %g %g)';
end
valueString = sprintf(pattern, rgb(1), rgb(2), rgb(3));
elseif handles.vector
% case of vector image: compute norm of the pixel
values = img(coord(2), coord(1), :, handles.slice);
norm = sqrt(sum(double(values(:)) .^ 2));
valueString = sprintf('value=%g', norm);
else
% case of a gray-scale pixel
value = img(coord(2), coord(1), handles.slice);
if ~isfloat(value)
valueString = sprintf('value=%3d', value);
else
valueString = sprintf('value=%g', value);
end
end
set(handles.pointValueText, 'string', valueString);
function point = displayToUserPoint(handles, point) %#ok<INUSL,DEFNU>
% Converts a point in view coordinate to a point in user coordinate
function index = pointToIndex(handles, point)
% Converts coordinates of a point in physical dimension to image index
% First element is column index, second element is row index, both are
% given in floating point and no rounding is performed.
spacing = handles.voxelSize(1:2);
origin = handles.voxelOrigin(1:2);
index = (point - origin) ./ spacing + 1;
|
github
|
jacksky64/imageProcessing-master
|
find_features.m
|
.m
|
imageProcessing-master/MatlabSIFT/find_features.m
| 6,216 |
utf_8
|
094478485c587da35b2ec95a2e4059a7
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% find_features - scale space feature detector based upon difference of gaussian filters.
% selects features based upon their maximum response in scale space
%
% Usage: maxima = find_features(pyr, img, thresh, radius, radius2, min_sep, edgeratio, disp_flag, img_flag)
%
% Parameters:
% pyr : cell array of filtered image pyramid (built with build_pyramid)
% img : original image (only used for visualization)
% thresh : threshold value for maxima search (minimum filter response considered)
% radius : radius for maxima comparison within current scale
% radius2: radius for maxima comparison between neighboring scales
% disp_flag: 1- display each scale level on separate figure. 0 - display nothing
% img_flag: 1 - display filter responses. 0 - display original images.
%
% Returns:
%
% maxima - cell array of nX2 matrices of row,column coordinates of selected points on each scale level
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function maxima = find_features(pyr, img, scl, thresh, radius, radius2, disp_flag, img_flag)
% pts = find_features(pyr,img,scl,thresh,radius,radius2,disp_flag,1);
levels = size(pyr);
levels = levels(2);
mcolor = [ 0 1 0; %color array for display of features at different scales
0 1 0;
1 0 0;
.2 .5 0;
0 0 1;
1 0 1;
0 1 1;
1 .5 0
.5 1 0
0 1 .5
.5 1 .5];
[himg,wimg] = size(img); %get size of images
[h,w] = size(pyr{2});
for i=2:levels-1
[h,w] = size(pyr{i});
[h2,w2] = size(pyr{i+1});
%find maxima
mx = find_extrema(pyr{i},thresh,radius); %find maxima at current scale level
mx2 = round((mx-1)/scl) + 1; %find coords in level above
mx_above = neighbor_max(pyr{i},pyr{i+1},mx,mx2,radius2); %do neighbor comparison in scale space above
if i>1
mx2 = round((mx-1)*scl) + 1; %find coords in level below
mx_below = neighbor_max(pyr{i},pyr{i-1},mx,mx2,radius2); %do comparison in scale below
maxima{i} = plist(mx, mx_below & mx_above); %get coord list for retained maxima and minima
else
maxima{i} = plist(mx, mx_above);
end
%find minima
%if i==11,
% keyboard;
%end;
mx = find_extrema(-pyr{i},thresh,radius); %find minima at current scale level
mx2 = round((mx-1)/scl) + 1; %find coords in level above
mx_above = neighbor_max(-pyr{i},-pyr{i+1},mx,mx2,radius2); %do neighbor comparison in scale space above
if i>1
mx2 = round((mx-1)*scl) + 1; %find coords in level below
mx_below = neighbor_max(-pyr{i},-pyr{i-1},mx,mx2,radius2); %do comparison in scale below
mxtemp = plist(mx, mx_below & mx_above); %get coord list for retained maxima and minima
else
mxtemp = plist(mx, mx_above);
end
maxima{i} = [maxima{i}; mxtemp]; %combine maxima and minima into list for return
%display results if desired
if disp_flag > 0
figure
if img_flag == 0
tmp=resample_bilinear(img,himg/h);
imagesc(tmp);
colormap gray;
show_plist(maxima{i},mcolor(mod(i-1,7)+1,:),'+');
else
imagesc(pyr{i});
colormap gray;
show_plist(maxima{i},mcolor(mod(i-1,7)+1,:),'+');
end
end
end
%//////////////////////////////////////////////////////////////////////////////////////////////
%
% Compare a vector of pixels with its neighbors in another scale
%
%//////////////////////////////////////////////////////////////////////////////////////////////
function v = neighbor_max(img1,img2,i,i2,radius) % i and i2 are column vectors of r,c coords
if (size(i2,1))==0 | size(img2,1)<11 | size(img2,2)<11
v=zeros(length(i),1);
else
[h,w] = size(img1);
[h2,w2] = size(img2);
[y,x]=meshgrid(-20:20,-20:20); %create set of offsets within radius
z = (x.^2+y.^2)<=radius^2;
[y,x]=find(z);
x=x-21; y=y-21;
radius=ceil(radius);
bound = ones(size(i2,1),2)*[h2-radius 0;0 w2-radius]; %create boundary listing
i2 = i2 - ((i2 > bound).*(i2-bound+1)); %test bounds to make all points within image
i2 = i2 + ((i2 < radius+1).*(radius-i2+1));
i2 = vec(i2,h2); %create indices from x,y coords
i = vec(i,h);
p = img1(i);
res = ones(length(i),1);
for j=1:length(x) %check against all points within radius
itest = i2 + x(j) + h2*y(j);
p2 = img2(itest);
res = res & (p>=p2);
end
v = res; %store results in binary vector
end
%//////////////////////////////////////////////////////////////////////////////////////////////
function v = vec(points,h)
y = points(:,1);
x = points(:,2);
v = y + (x-1)*h; %create index vectors
%//////////////////////////////////////////////////////////////////////////////////////////////
function p = plist(points, flags)
p = points(find(flags),:);
|
github
|
jacksky64/imageProcessing-master
|
plot_matched.m
|
.m
|
imageProcessing-master/MatlabSIFT/plot_matched.m
| 718 |
utf_8
|
8f4f810fdb7b9dffc21e850731443e63
|
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [] = plot_matched(p,w,img,num_flag)
if ~exist('num_flag')
num_flag = 0;
end
figure(gcf);
imagesc(img)
hold on
colormap gray
for i=1:size(p,2)
x = p(1,i)+1;
y = p(2,i)+1;
sz = w(i);
if x>size(img,2)
x
end
if num_flag ~= 1
plot(x,y,'g+'); %draw box around real feature
else
plot(x,y,'g+'); %draw box around real feature
text(x,y,sprintf('%d',i),'color','r');
end
drawbox(0,sz,x,y,[0 1 0]);
end
|
github
|
jacksky64/imageProcessing-master
|
build_pyramid.m
|
.m
|
imageProcessing-master/MatlabSIFT/build_pyramid.m
| 2,047 |
utf_8
|
a5763817edf3ff11db24c6b7f8c8124f
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% build_pyramid - build scaled image pyramid and difference of gaussians pyramid
%
% Usage: [pyr,imp] = build_pyramid(img,levels,scl);
%
% Parameters:
%
% img : original image
% levels : number of levels in pyramid
% scl : scaling factor between pyramid levels
%
% Returns:
%
% pyr : difference of gaussians filtered image pyramid
% imp : image pyramid cell array
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [pyr,imp] = build_pyramid(img,levels,scl)
img2 = img;
img2 = resample_bilinear(img2,1/2); %expand to retain spatial frequencies
%img2 = imresize(img2,2,'bilinear'); %expand to retain spatial frequencies
sigma=1.5; %variance for laplacian filter
sigma2=1.5; %variance for downsampling
sig_delta = (1.6-.6)/levels;
for i=1:levels
if i==1
img3 = img2;
img2 = filter_gaussian(img2,7,.5); %slightly filter bottom level
end
imp{i}=img2;
A = filter_gaussian(img2,7,sigma); %calculate difference of gaussians
B = filter_gaussian(A,7,sigma);
pyr{i} = A-B; %store result in cell array
if i==1
img2 = img3;
else
B = filter_gaussian(img2,7,sigma2); %anti-alias for downsampling
B = filter_gaussian(B,7,sigma2);
end
img2 = resample_bilinear(B,scl); %downsample for next level
end
%show_pyramid(pyr) %show pyramid if desired
%///////////////////////////////////////////////////////////////////////////////
function show_pyramid(pyr)
close all
[h,w] = size(pyr);
for i=1:w
figure
imagesc(pyr{i});
colormap gray;
end
|
github
|
jacksky64/imageProcessing-master
|
construct_key.m
|
.m
|
imageProcessing-master/MatlabSIFT/construct_key.m
| 817 |
utf_8
|
4f74405436aafff224bcd89245dd5d5b
|
function key = construct_key(px, py, img, sz)
pct = .75;
[h,w] = size(img);
[yoff,xoff] = meshgrid(-1:1,-1:1);
yoff = yoff(:)*pct;
xoff = xoff(:)*pct;
for i = 1:size(yoff,1)
ctrx = px + xoff(i)*sz*2; %method using interpolated values
ctry = py + yoff(i)*sz*2;
[y,x] = meshgrid(ctry-sz:sz/3:ctry+sz,ctrx-sz:sz/3:ctrx+sz);
y=y(:);
x=x(:);
t = 0;
c = 0;
for k=1:size(y,1)
if x(k)<w-1 & x(k)>1 & y(k)<h-1 & y(k)>1
t = t + interp(img,x(k),y(k));
c=c+1;
end
end
if c==0
c
end
t = t/c;
key(i) = t;
end
key = key/sum(key);
|
github
|
jacksky64/imageProcessing-master
|
motion_corr2.m
|
.m
|
imageProcessing-master/MatlabSIFT/motion_corr2.m
| 4,570 |
utf_8
|
f87063db26fa6fcececf205f713cac11
|
% MOTION_CORR - Computes a set of interest point correspondences
% between two successive frames in an image
% sequence. First, a Harris corner detector is used
% to choose interest points. Then, CORR is used to
% obtain a matching, using both geometric constraints
% and local similarity of the points' intensity
% neighborhoods.
%
% Usage: [p1, p2, a, F] = motion_corr(im1, im2[, OPTIONS])
%
% Arguments:
% im1 - an image
% im2 - another image
% Options:
% 'p1' - an m x 3 matrix whose rows are
% (homogeneous) coordinates of interest
% points in im1; if supplied,
% this matrix will be returned as p1; it can be
% the empty matrix [] (in which case it is as if
% they were not supplied)
% 'smoothing' - pre-smoothing before corner detection
% (default: 2.0)
% 'nmsrad' - radius for non-maximal suppression of Harris
% response matrix (default: 2)
% 'rthresh' - relative threshold for Harris response
% matrix (default: 0.3)
% 'rthresh2' - smaller relative threshold used to
% search for matches in the second image
% (default: rthresh / 2.0)
% 'sdthresh' - a distance threshold; no matches will be
% accepted such that the Sampson distance
% is greater than the threshold (default: 1.0)
% 'dthresh' - a distance threshold; no matches will be
% accepted such that the Euclidean
% distance between the matched points is
% greater than dthresh (default: 30)
%
% This function also accepts options for CORR.
%
% Returns:
%
% a - an m x 1 assignment vector. a(i) is the index of
% the feature of the second image that was matched
% to feature i of the first image. For example,
% p1(i, :) is matched to p2(a(i), :). If feature i
% (of the first image) was not matched to any
% feature in the second image, then a(i) is zero.
% F - the fundamental matrix used to compute the matching.
%
% See also CORR and HARRIS_PTS.
% Copyright (C) 2002 Mark A. Paskin
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [p1, p2 , a, F] = motion_corr2(f1,k1,f2,k2,im1,im2, varargin)
% STEP 0: Process options
[p1, ...
smoothing, ...
nmsrad, ...
rthresh, ...
rthresh2, ...
sdthresh, ...
dthresh, ...
corr_opts] = process_options(varargin, 'p1', [], ...
'smoothing', 2, ...
'nmsrad', 2, ...
'rthresh', 0.3, ...
'rthresh2', nan, ...
'sdthresh', 1e-2, ...
'dthresh', 30);
if (isnan(rthresh2)) rthresh2 = rthresh / 2.0; end
% STEP 2: Form a cost matrix based upon local properties of the
% interest points. The cost metric we use here is the sum of
% squared differences of intensity values in a square
% neighborhood around the pixels; a hard Euclidean distance
% threshold is implemented so all point pairs that are too far
% apart are given infinite cost.
C = make_cost(k1,k2);
p1 = f1(:,1:2); %create homogeneous coordinates
p2 = f2(:,1:2);
p1(:,3) = 1;
p2(:,3) = 1;
% STEP 3: Compute the correspondence.
[a, F] = corr(p1, p2, C, 'sdthresh', sdthresh, corr_opts{:});
|
github
|
jacksky64/imageProcessing-master
|
getpts.m
|
.m
|
imageProcessing-master/MatlabSIFT/getpts.m
| 6,081 |
utf_8
|
e4c6a997168907b5b857ddf6c8d0fbac
|
%display features with sub-pixel and sub-scale accuracy
%Scott Ettinger
function [features] = getpts(img, pyr, scl,imp,pts,hood_size,radius,min_separation,edgeratio)
mcolor = [ 0 1 0; %color array for display of features at different scales
0 1 0;
1 0 0;
.2 .5 0;
0 0 1;
1 0 1;
0 1 1;
1 .5 0
.5 1 0
0 1 .5
.5 1 .5];
[ho,wo]=size(img);
[h2,w2]=size(imp{2});
hood_size = hood_size + ~mod(hood_size, 2); % ensure neighborhood size is odd
w = (hood_size+1)/2;
%create offset list for ring of pixels
[ry2,rx2]=meshgrid(-20:20,-20:20);
z = (rx2.^2+ry2.^2)<=(radius)^2 & (rx2.^2+ry2.^2)>(radius-1)^2;
[ry2,rx2]=find(z);
rx2=rx2-21; ry2=ry2-21;
F = fspecial('gaussian', hood_size, 2);
ndx = 1;
for j=2:length(imp)-1
p=pts{j};
img=imp{j};
[dh,dw]=size(img);
np = 1;
min_sep = min_separation*max(max(pyr{j}));
for i=1:size(p,1)
ptx = p(i,2);
pty = p(i,1);
if p(i,1) < radius+3 %ensure neighborhood is not outside of image
p(i,1) = radius+3;
end
if p(i,1) > dh-radius-3
p(i,1) = dh-radius-3;
end
if p(i,2) < radius+3
p(i,2) = radius+3;
end
if p(i,2) > dw-radius-3
p(i,2) = dw-radius-3;
end
%adjust to sub pixel maxima location
r = [pyr{j}(pty-1,ptx-1:ptx+1) ;pyr{j}(pty,ptx-1:ptx+1) ;pyr{j}(pty+1,ptx-1:ptx+1)];
[pcy,pcx] = fit_paraboloid(r); %find center of paraboloid
if abs(pcy)>1 %ignore extreme offsets due to singularities in parabola fitting
pcy=0;
pcx=0;
end
if abs(pcx)>1
pcx=0;
pcy=0;
end
p(i,1) = p(i,1) + pcy; %adjust center
p(i,2) = p(i,2) + pcx;
ptx = p(i,2);
pty = p(i,1);
px=(pts{j}(i,2)+pcx - 1)*scl^(j-2) + 1; %calculate point locations at pyramid level 2
py=(pts{j}(i,1)+pcy - 1)*scl^(j-2) + 1;
y1 = interp(pyr{j-1},(p(i,2)-1)*scl+1, (p(i,1)-1)*scl+1); %get response on surrounding scale levels using interpolation
y3 = interp(pyr{j+1},(p(i,2)-1)/scl+1, (p(i,1)-1)/scl+1);
y2 = interp(pyr{j},p(i,2),p(i,1));
coef = fit_parabola(0,1,2,y1,y2,y3); % fit 3 scale points to parabola
scale_ctr = -coef(2)/2/coef(1); %find max in scale space
if abs(scale_ctr-1)>1 %ignore extreme values due to singularities in parabola fitting
scale_ctr=0;
end
%eliminate edge points and enforce minimum separation
rad2 = radius * scl^(scale_ctr-1); %adust radius size for scale space
o=0:pi/8:2*pi-pi/8; %create ring of points at radius around test point
rx = (rad2)*cos(o);
ry = (rad2)*sin(o);
rmax = 1e-9;
rmin = 1e9;
gp_flag = 1;
pval = interp(pyr{j},ptx,pty);
rtst = [];
%check points on ring around feature point
for k=1:length(rx)
rtst(k) = interp(pyr{j},ptx+rx(k),pty+ry(k)); %get value with bilinear interpolation
if pval> 0 %calculate distance from feature point response for each point
rtst(k) = pval - rtst(k);
else
rtst(k) = rtst(k) - pval;
end
gp_flag = gp_flag * rtst(k)>min_sep; %test for valid maxima above noise floor
if rtst(k)>rmax %find min and max
rmax = rtst(k);
end
if rtst(k)<rmin
rmin = rtst(k);
end
end
fac = scl/(wo*2/size(pyr{2},2));
[cl,or] = f_class(rtst);
if rmax/rmin > edgeratio
gp_flag=0;
if cl ~= 2 %keep all edge intersections
gp_flag = 1;
else
ang = min(abs([(or(1)-or(2)) (or(1)-(or(2)-2*pi))]));
if ang < 6.5*pi/8; %keep edges with angles more acute than 145 deg.
gp_flag = 1;
end
end
end
%save info
features(ndx,1) = (px-1)*wo/w2*fac +1; %save x and y position (sub pixel adjusted)
features(ndx,2) = (py-1)*wo/w2*fac +1;
features(ndx,3) = j+scale_ctr-1; %save scale value (sub scale adjusted in units of pyramid level)
features(ndx,4) = ((hood_size-4)*scl^(j-2+scale_ctr-1))*wo/w2*fac; %save size of feature on original image
features(ndx,5) = gp_flag; %save edge flag
features(ndx,6) = or(1); %save edge orientation angle
features(ndx,7) = coef(1); %save curvature of response through scale space
ndx = ndx + 1;
end
end
function v = interp(img,xc,yc) %bilinear interpolation between points
px = floor(xc);
py = floor(yc);
alpha = xc-px;
beta = yc-py;
nw = img(py,px);
ne = img(py,px+1);
sw = img(py+1,px);
se = img(py+1,px+1);
v = (1-alpha)*(1-beta)*nw + ... %interpolate
(1-alpha)*beta*sw + ...
alpha*(1-beta)*ne + ...
alpha*beta*se;
function f = gauss1d(order,sig)
f=0;
i=0;
j=0;
%generate gaussian coefficients
for x = -fix(order/2):1:fix(order/2)
i = i + 1;
f(i) = 1/2/pi*exp(-((x^2)/(2*sig^2)));
end
f = f / sum(sum(f)); %normalize filter
|
github
|
jacksky64/imageProcessing-master
|
resample_bilinear.m
|
.m
|
imageProcessing-master/MatlabSIFT/resample_bilinear.m
| 1,248 |
utf_8
|
2b3be967a23972ebbdbcdb98673578f1
|
%/////////////////////////////////////////////////////////////////////////////////////////////
% Author : Scott Ettinger
%
% resample_bilinear(img, ratio)
%
% resamples a 2d matrix by the ratio given by the ratio parameter using bilinear interpolation
% the 1,1 entry of the matrix is always duplicated.
%/////////////////////////////////////////////////////////////////////////////////////////////
function img2 = resample_bilinear(img, ratio)
img=double(img);
[h,w]=size(img); %get size of image
[y,x]=meshgrid( 1:ratio:h-1, 1:ratio:w-1 ); %create vectors of X and Y values for new image
[h2,w2] = size(x); %get dimensions of new image
x = x(:); %convert to vectors
y = y(:);
alpha = x - floor(x); %calculate alphas and betas for each point
beta = y - floor(y);
fx = floor(x); fy = floor(y);
inw = fy + (fx-1)*h; %create index for neighboring pixels
ine = fy + fx*h;
isw = fy+1 + (fx-1)*h;
ise = fy+1 + fx*h;
img2 = (1-alpha).*(1-beta).*img(inw) + ... %interpolate
(1-alpha).*beta.*img(isw) + ...
alpha.*(1-beta).*img(ine) + ...
alpha.*beta.*img(ise);
img2 = reshape(img2,h2,w2); %turn back into 2d
img2 = img2';
|
github
|
jacksky64/imageProcessing-master
|
filter_laplacian.m
|
.m
|
imageProcessing-master/MatlabSIFT/filter_laplacian.m
| 1,803 |
utf_8
|
8cca88c2df0ef869c1bc3dbd496262e3
|
%/////////////////////////////////////////////////////////////////////////////////////////////
% Author : Scott Ettinger
%
% filter_gaussian(img, order, sig)
%
% The image is first padded with the outer image data enough times to allow for the size of the
% filter used.
function image_out = filter_gaussian(img,order,sig)
h1 = gauss1d(order,sig); %create filter coefficient matrix
h2 = conv2(h1, [.5 0 -.5]);
h3 = conv2(h2,h2);
h3 = h3/sum(abs(h3));
order = length(h3);
img2 = img;
for i=1:floor(order/2) %pad image borders with enough for filter order
[h,w] = size(img2);
img2 = [img2(1,1) img2(1,:) img2(1,w);
img2(:,1) img2 img2(:,w);
img2(h,1) img2(h,:) img2(h,w)];
end
image_out = conv2(img2,h3','valid'); % do the filtering
image_out = image_out(:,floor(order/2)+1:end-floor(order/2));
image_out2 = conv2(img2,h3,'valid'); % do the filtering
image_out2 = image_out2(floor(order/2)+1:end-floor(order/2),:);
image_out = -image_out-image_out2;
%/////////////////////////////////////////////////////////////////////////////////////////
function f = gauss1d(order,sig)
f=0;
i=0;
j=0;
%generate gaussian coefficients
for x = -fix(order/2):1:fix(order/2)
i = i + 1;
f(i) = 1/2/pi*exp(-((x^2)/(2*sig^2)));
end
f = f / sum(sum(f)); %normalize filter
%/////////////////////////////////////////////////////////////////////////////////////////
function f = gauss2d(order,sig)
f=0;
i=0;
j=0;
%generate gaussian coefficients
for x = -fix(order/2):1:fix(order/2)
j=j+1;
i=0;
for y = -fix(order/2):1:fix(order/2)
i=i+1;
f(i,j) = 1/2/pi*exp(-((x^2+y^2)/(2*sig^2)));
end
end
f = f / sum(sum(f)); %normalize filter
|
github
|
jacksky64/imageProcessing-master
|
match_dv_odometry.m
|
.m
|
imageProcessing-master/MatlabSIFT/match_dv_odometry.m
| 392 |
utf_8
|
e49b9238207c097440046bded7eddc6f
|
function od_out = match_dv_odometry(od_in,dv)
c = 1;
i = 1;
while i<size(dv,1) & c<size(od_in,1)
while od_in(c,1)<dv(i) & c<size(od_in,1) %find matching odometry measurement
c = c+1;
end
od_out(i,:) = od_in(c,:);
i=i+1;
end
for k=i:size(dv,1)
od_out(k,:)=od_in(c,:);
end
|
github
|
jacksky64/imageProcessing-master
|
detect_features.m
|
.m
|
imageProcessing-master/MatlabSIFT/detect_features.m
| 3,146 |
utf_8
|
daa7ae4ed1d013fbbe23f8bd824affde
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% detect_features - scale space feature detector based upon difference of gaussian filters.
% selects features based upon their maximum response in scale space
%
% Usage: [features,pyr,imp,keys] = detect_features(img, scl, disp_flag, thresh, radius, radius2, radius3, min_sep, edgeratio)
%
% Parameters:
%
% img : original image
% scl : scaling factor between levels of the image pyramid
% thresh : threshold value for maxima search (minimum filter response considered)
% radius : radius for maxima comparison within current scale
% radius2: radius for maxima comparison between neighboring scales
% radius3: radius for edge rejection test
% min_sep : minimum separation for maxima selection.
% edgeratio: maximum ratio of eigenvalues of feature curvature for edge rejection.
% disp_flag: 1- display each scale level on separate figure. 0 - no display
%
% Returns:
%
% features - matrix with one row for each feature consisting of the following:
% [x position, y position, scale(sub-level), size of feature on image, edge flag,
% edge orientation, curvature of response through scale space ]
%
% pyr, imp - filter response and image pyramids
% keys - key values generated for each feature by construct_key.m
%
% Notes:
% recommended parameter values are:
% scl = 1.5; thresh = 3; radius = 4; radius2 = 4; radius3 = 4; min_sep = .04; edgeratio = 5;
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [features,pyr,imp,keys] = detect_features(img, scl, disp_flag, thresh, radius, radius2, radius3, min_sep, edgeratio)
if ~exist('scl')
scl = 1.5;
end
if ~exist('thresh')
thresh = 3;
end
if ~exist('radius')
radius = 4;
end
if ~exist('radius2')
radius2 = 4;
end
if ~exist('radius3')
radius3 = 4;
end
if ~exist('min_sep')
min_sep = .04;
end
if ~exist('edgeratio')
edgeratio = 5;
end
if ~exist('disp_flag')
disp_flag = 0;
end
if size(img,3) > 1
img = rgb2gray(img);
end
% Computation of the maximum number of levels:
Lmax = floor(min(log(2*size(img)/12)/log(scl)));
%build image pyramid and difference of gaussians filter response pyramid
[pyr,imp] = build_pyramid(img,Lmax,scl);
%get the feature points
pts = find_features(pyr,img,scl,thresh,radius,radius2,disp_flag,1);
%classify points and create sub-pixel and sub-scale adjustments
[features,keys] = refine_features(img,pyr,scl,imp,pts,radius3,min_sep,edgeratio);
|
github
|
jacksky64/imageProcessing-master
|
find_extrema.m
|
.m
|
imageProcessing-master/MatlabSIFT/find_extrema.m
| 2,761 |
utf_8
|
63c3ac08500a3e375157d034a61ccc11
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% find_extrema - finds local maxima within a grayscale image. Each point is
% checked against all of the pixels within a given radius to be a local max/min.
% The magnitude of pixel values must be above the given threshold to be picked
% as a valid maxima or minima.
%
% Usage: m = find_extrema(img,thresh,radius,min_separation)
%
% Parameters:
% img : image matrix
% thresh : threshold value
% radius : pixel radius
%
% Returns:
%
% m - an nX2 matrix of row,column coordinates of selected points
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [mx] = find_extrema(img,thresh,radius)
%img = abs(img);
[h,w] = size(img);
% get interior image subtracting radius pixels from border
p = img(radius+1:h-radius, radius+1:w-radius);
%get pixels above threshold
[yp,xp] = find(p>thresh);
yp=yp+radius; xp=xp+radius;
pts = yp+(xp-1)*h;
%create offset list for immediate neighborhood
z=ones(3,3);
z(2,2)=0;
[y,x]=find(z);
y=y-2; x=x-2;
if size(pts,2)>size(pts,1)
pts = pts';
end
%test for max within immediate neighborhood
if size(pts,1)>0
maxima=ones(length(pts),1);
for i=1:length(x)
pts2 = pts + y(i) + x(i)*h;
maxima = maxima & img(pts)>img(pts2);
end
xp = xp(find(maxima)); %save maxima
yp = yp(find(maxima));
pts = yp+(xp-1)*h; %create new index list of good points
end
%create offset list for radius of pixels
[y,x]=meshgrid(-20:20,-20:20);
z = (x.^2+y.^2)<=radius^2 & (x.^2+y.^2)>(1.5)^2; %include points within radius without immediate neighborhood
[y,x]=find(z);
x=x-21; y=y-21;
%create offset list for ring of pixels
[y2,x2]=meshgrid(-20:20,-20:20);
z = (x2.^2+y2.^2)<=(radius)^2 & (x2.^2+y2.^2)>(radius-1)^2;
[y2,x2]=find(z);
x2=x2-21; y2=y2-21;
maxima = ones(length(pts),1);
%test within radius of pixels (done after first test for slight speed increase)
if size(pts,1)>0
for i = 1:length(x)
pts2 = pts + y(i) + x(i)*h;
maxima = maxima & img(pts)>img(pts2); %test points
end
xp = xp(find(maxima)); %save maxima from immediate neighborhood
yp = yp(find(maxima));
pts = yp+(xp-1)*h; %create new index list
mx = [yp xp];
else
mx = [];
end
|
github
|
jacksky64/imageProcessing-master
|
filter_gaussian.m
|
.m
|
imageProcessing-master/MatlabSIFT/filter_gaussian.m
| 1,539 |
utf_8
|
8c018c4d76363cdb193b6ee5e49ca6a8
|
%/////////////////////////////////////////////////////////////////////////////////////////////
% Author : Scott Ettinger
%
% filter_gaussian(img, order, sig)
%
% The image is first padded with the outer image data enough times to allow for the size of the
% filter used.
function image_out = filter_gaussian(img,order,sig)
img2 = img;
for i=1:floor(order/2) %pad image borders with enough for filter order
[h,w] = size(img2);
img2 = [img2(1,1) img2(1,:) img2(1,w);
img2(:,1) img2 img2(:,w);
img2(h,1) img2(h,:) img2(h,w)];
end
f = gauss1d(order,sig); %create filter coefficient matrix
image_out = conv2(img2,f,'valid'); % do the filtering
image_out = conv2(image_out,f','valid'); % do the filtering
%/////////////////////////////////////////////////////////////////////////////////////////
function f = gauss1d(order,sig)
f=0;
i=0;
j=0;
%generate gaussian coefficients
for x = -fix(order/2):1:fix(order/2)
i = i + 1;
f(i) = 1/2/pi*exp(-((x^2)/(2*sig^2)));
end
f = f / sum(sum(f)); %normalize filter
%/////////////////////////////////////////////////////////////////////////////////////////
function f = gauss2d(order,sig)
f=0;
i=0;
j=0;
%generate gaussian coefficients
for x = -fix(order/2):1:fix(order/2)
j=j+1;
i=0;
for y = -fix(order/2):1:fix(order/2)
i=i+1;
f(i,j) = 1/2/pi*exp(-((x^2+y^2)/(2*sig^2)));
end
end
f = f / sum(sum(f)); %normalize filter
|
github
|
jacksky64/imageProcessing-master
|
gauss2dx.m
|
.m
|
imageProcessing-master/MatlabSIFT/gauss2dx.m
| 573 |
utf_8
|
852c8ed3ce8569434a4da1e70ad4ee40
|
%Author : Scott Ettinger
%Details:
%
%gauss2d(order, sig)
%
%Generates a normalized 2d matrix to use as a gaussian convolution filter
% order - size of filter matrix. Returns an order X order matrix
% sig - sigma value in gaussian equation
function f = gauss2dx(order,sig)
f=0;
i=0;
j=0;
%generate gaussian coefficients
for x = -fix(order/2):1:fix(order/2)
j=j+1;
i=0;
for y = -fix(order/2):1:fix(order/2)
i=i+1;
f(i,j) = 1/2/pi*exp(-((x^2+y^2)/(2*sig^2)));
end
end
f = f / sum(sum(f)); %normalize filter
|
github
|
jacksky64/imageProcessing-master
|
refine_features.m
|
.m
|
imageProcessing-master/MatlabSIFT/refine_features.m
| 8,711 |
utf_8
|
bcf05884bf144765d706ddf4d1c707b2
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% refine_features - scale space feature detector based upon difference of gaussian filters.
% selects features based upon their maximum response in scale space
%
% Usage: features = refine_features(img, pyr, scl, imp, pts, radius, min_separation, edgeratio)
%
% Parameters:
%
% img : original image
% pyr : cell array of filtered image pyramid
% scl : scaling factor between levels of the image pyramid
% imp : image pyramid cell array
% pts : cell array of selected points on each pyramid level
% radius : radius for edge rejection test
% min_separation : minimum separation distance for maxima rejection.
% edgeratio: maximum ratio of eigenvalues of feature curvature for edge rejection.
%
% Returns:
%
% features - matrix with one row for each feature consisting of the following:
% [x loc, y loc, scale value, size, edge flag, edge orientation, scale space curvature]
%
% where:
% x loc and y loc are the x and y positions on the original image
% scale value is the sub level adjusted scale value
% size is the size of the feature in pixels on the original image
% edge flag is zero if the feature is classified as an edge
% edge orientation is the angle made by the edge through the feature point
% scale space curvature is a rough confidence measure of feature prominence
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [features,keys] = refine_features(img, pyr, scl, imp,pts, radius, min_separation, edgeratio)
[ho,wo]=size(img);
[h2,w2]=size(imp{2});
%create offset list for ring of pixels
[ry2,rx2]=meshgrid(-20:20,-20:20);
z = (rx2.^2+ry2.^2)<=(radius)^2 & (rx2.^2+ry2.^2)>(radius-1)^2;
[ry2,rx2]=find(z);
rx2=rx2-21; ry2=ry2-21;
ndx = 1;
%loop through each level of pyramid
for j=2:length(imp)-1
p=pts{j}; %get current level filter response
img=imp{j}; %get current level image
[dh,dw]=size(img);
np = 1;
min_sep = min_separation*max(max(pyr{j})); %calculate minimum separation for valid maximum
for i=1:size(p,1)
ptx = p(i,2);
pty = p(i,1);
if p(i,1) < radius+3 %ensure neighborhood is not outside of image
p(i,1) = radius+3;
end
if p(i,1) > dh-radius-3
p(i,1) = dh-radius-3;
end
if p(i,2) < radius+3
p(i,2) = radius+3;
end
if p(i,2) > dw-radius-3
p(i,2) = dw-radius-3;
end
%adjust to sub pixel maxima location
r = pyr{j}(pty-1:pty+1,ptx-1:ptx+1); %get 3X3 neighborhood of pixels
[pcy,pcx] = fit_paraboloid(r); %find center of paraboloid fit to points
if abs(pcy)>1 %ignore extreme offsets due to singularities in parabola fitting
pcy=0;
pcx=0;
end
if abs(pcx)>1
pcx=0;
pcy=0;
end
p(i,1) = p(i,1) + pcy; %adjust center
p(i,2) = p(i,2) + pcx;
ptx = p(i,2);
pty = p(i,1);
px=(pts{j}(i,2)+pcx - 1)*scl^(j-2) + 1; %calculate point locations at pyramid level 2
py=(pts{j}(i,1)+pcy - 1)*scl^(j-2) + 1;
%calculate Sub-Scale level adjustment
y1 = interp(pyr{j-1},(p(i,2)-1)*scl+1, (p(i,1)-1)*scl+1); %get response on surrounding scale levels using interpolation
y3 = interp(pyr{j+1},(p(i,2)-1)/scl+1, (p(i,1)-1)/scl+1);
y2 = interp(pyr{j},p(i,2),p(i,1));
coef = fit_parabola(0,1,2,y1,y2,y3); % fit neighborhood of 3 scale points to parabola
scale_ctr = -coef(2)/2/coef(1); %find max in scale space
if abs(scale_ctr-1)>1 %ignore extreme values due to singularities in parabola fitting
scale_ctr=0;
end
%eliminate edge points and enforce minimum separation
rad2 = radius * scl^(scale_ctr-1); %adust radius size to account for new scale value
o=0:pi/8:2*pi-pi/8; %create ring of points at radius around test point
rx = (rad2)*cos(o);
ry = (rad2)*sin(o);
rmax = 1e-9; %init max and min values
rmin = 1e9;
gp_flag = 1;
pval = interp(pyr{j},ptx,pty); %get response at feature center
rtst = [];
%check points on ring around feature point
for k=1:length(rx)
rtst(k) = interp(pyr{j},ptx+rx(k),pty+ry(k)); %get ring point value with bilinear interpolation
if pval> 0 %calculate distance from feature point for each point in ring
rtst(k) = pval - rtst(k);
else
rtst(k) = rtst(k) - pval;
end
gp_flag = gp_flag * rtst(k)>min_sep; %test for valid maxima above noise floor
if rtst(k)>rmax %find min and max
rmax = rtst(k);
end
if rtst(k)<rmin
rmin = rtst(k);
end
end
fac = scl/(wo*2/size(pyr{2},2)); %calculate size offset due to edge effects of downsampling
[cl,or] = f_class(rtst); %classify features and get orientations
if rmax/rmin > edgeratio %test for edge criterion
gp_flag=0;
if cl ~= 2 %keep all intersections (# ridges > 2)
gp_flag = 1;
else
ang = min(abs([(or(1)-or(2)) (or(1)-(or(2)-2*pi))]));
if ang < 6.5*pi/8; %keep edges with angles more acute than 145 deg.
gp_flag = 1;
end
end
end
%save info
features(ndx,1) = (px-1)*wo/w2*fac +1; %save x and y position (sub pixel adjusted)
features(ndx,2) = (py-1)*wo/w2*fac +1;
features(ndx,3) = j+scale_ctr-1; %save scale value (sub scale adjusted in units of pyramid level)
features(ndx,4) = ((7-4)*scl^(j-2+scale_ctr-1))*wo/w2*fac; %save size of feature on original image
features(ndx,5) = gp_flag; %save edge flag
features(ndx,6) = or(1); %save edge orientation angle
features(ndx,7) = coef(1); %save curvature of response through scale space
if features(ndx,1) > wo
px
end
keys(ndx,:) = construct_key(ptx,pty,imp{j},3 * scl^(scale_ctr-1));
ndx = ndx + 1;
end
end
function v = interp(img,xc,yc) %bilinear interpolation between points
px = floor(xc);
py = floor(yc);
alpha = xc-px;
beta = yc-py;
nw = img(py,px);
ne = img(py,px+1);
sw = img(py+1,px);
se = img(py+1,px+1);
v = (1-alpha)*(1-beta)*nw + ... %interpolate
(1-alpha)*beta*sw + ...
alpha*(1-beta)*ne + ...
alpha*beta*se;
|
github
|
jacksky64/imageProcessing-master
|
plotpoints.m
|
.m
|
imageProcessing-master/MatlabSIFT/plotpoints.m
| 1,035 |
utf_8
|
d4872923af1d87538633d8cac8642041
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% plotpoints - visualize features generated by detect_features
% Usage: plotpoints(p,img,num_flag)
%
% Parameters:
%
% img : original image
% p: vector of points
% numflag : 0 - plot with crosshairs 1-plot with number index
%
% Returns: nothing, generates figure
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [] = plotpoints(p,img,num_flag)
if ~exist('num_flag')
num_flag = 0;
end
figure(gcf)
imagesc(img)
hold on
colormap gray
for i=1:size(p,1)
x = p(i,1);
y = p(i,2);
if num_flag ~= 1
plot(x,y,'g+'); %draw box around real feature
else
plot(x,y,'g+');
text(x,y,sprintf('%d',i),'color','m');
end
end
hold off;
|
github
|
jacksky64/imageProcessing-master
|
showfeatures.m
|
.m
|
imageProcessing-master/MatlabSIFT/showfeatures.m
| 1,487 |
utf_8
|
b04b890bdf153576182207d6307c2af1
|
%/////////////////////////////////////////////////////////////////////////////////////////////
%
% showfeatures - visualize features generated by detect_features
% Usage: showfeatures(features,img)
%
% Parameters:
%
% img : original image
% features: matrix generated by detect_features
%
% Returns: nothing, generates figure
%
% Author:
% Scott Ettinger
% [email protected]
%
% May 2002
%/////////////////////////////////////////////////////////////////////////////////////////////
function [] = showfeatures(features,img,num_flag)
if ~exist('num_flag')
num_flag = 0;
end
figure(gcf);
imagesc(img)
hold on
colormap gray
for i=1:size(features,1)
x = features(i,1);
y = features(i,2);
sz = features(i,4);
if x>size(img,2)
x
end
if features(i,5) > 0 %check edge flag
if num_flag ~= 1
plot(x,y,'g+'); %draw box around real feature
else
text(x,y,sprintf('%d',i),'color','m');
end
if abs(features(i,7))>1.8
drawbox(0,sz,x,y,[0 0 1]);
else
drawbox(0,sz,x,y,[0 .9 .2]);
end
else %draw as edge
ang = features(i,6);
px = [x-sz*cos(ang) x+sz*cos(ang)];
py = [y-sz*sin(ang) y+sz*sin(ang)];
plot(px,py,'r');
end
end
hold off;
|
github
|
jacksky64/imageProcessing-master
|
make_cost.m
|
.m
|
imageProcessing-master/MatlabSIFT/make_cost.m
| 227 |
utf_8
|
d6ebc15f2e3ae829983736bf8d34646b
|
function c = make_cost(k1, k2)
for i=1:size(k1,1)
for k=1:size(k2,1)
c(i,k) = sum((k1(i,:) - k2(k,:)).^2);
end
end
|
github
|
jacksky64/imageProcessing-master
|
motion_corr.m
|
.m
|
imageProcessing-master/MatlabSIFT/motion_corr.m
| 6,466 |
utf_8
|
2e27a037d9c354cc545b0c88be7a7648
|
% MOTION_CORR - Computes a set of interest point correspondences
% between two successive frames in an image
% sequence. First, a Harris corner detector is used
% to choose interest points. Then, CORR is used to
% obtain a matching, using both geometric constraints
% and local similarity of the points' intensity
% neighborhoods.
%
% Usage: [p1, p2, a, F] = motion_corr(im1, im2[, OPTIONS])
%
% Arguments:
% im1 - an image
% im2 - another image
% Options:
% 'p1' - an m x 3 matrix whose rows are
% (homogeneous) coordinates of interest
% points in im1; if supplied,
% this matrix will be returned as p1; it can be
% the empty matrix [] (in which case it is as if
% they were not supplied)
% 'smoothing' - pre-smoothing before corner detection
% (default: 2.0)
% 'nmsrad' - radius for non-maximal suppression of Harris
% response matrix (default: 2)
% 'rthresh' - relative threshold for Harris response
% matrix (default: 0.3)
% 'rthresh2' - smaller relative threshold used to
% search for matches in the second image
% (default: rthresh / 2.0)
% 'sdthresh' - a distance threshold; no matches will be
% accepted such that the Sampson distance
% is greater than the threshold (default: 1.0)
% 'dthresh' - a distance threshold; no matches will be
% accepted such that the Euclidean
% distance between the matched points is
% greater than dthresh (default: 30)
%
% This function also accepts options for CORR.
%
% Returns:
% p1 - an m x 3 matrix whose rows are the
% (homogeneous) coordinates of interest points
% in im1 (this will be the value given to the 'p1'
% option, if it is supplied)
% p2 - an n x 3 matrix whose rows are the
% (homogeneous) coordinates of interest points
% in im2
% a - an m x 1 assignment vector. a(i) is the index of
% the feature of the second image that was matched
% to feature i of the first image. For example,
% p1(i, :) is matched to p2(a(i), :). If feature i
% (of the first image) was not matched to any
% feature in the second image, then a(i) is zero.
% F - the fundamental matrix used to compute the matching.
%
% See also CORR and HARRIS_PTS.
% Copyright (C) 2002 Mark A. Paskin
%
% 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
% (at your option) 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 Place, Suite 330, Boston, MA 02111-1307
% USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [p1, p2, a, F] = motion_corr(im1, im2, varargin)
% STEP 0: Process options
[p1, ...
smoothing, ...
nmsrad, ...
rthresh, ...
rthresh2, ...
sdthresh, ...
dthresh, ...
corr_opts] = process_options(varargin, 'p1', [], ...
'smoothing', 2, ...
'nmsrad', 2, ...
'rthresh', 0.3, ...
'rthresh2', nan, ...
'sdthresh', 1.0, ...
'dthresh', 30);
if (isnan(rthresh2)) rthresh2 = rthresh / 2.0; end
'yes this is the right file...'
% STEP 1: Extract interest points in the second image. Note that
% this is done with the smaller (or more forgiving)
% relative threshold. Later, we will re-threshold to
% remove those points in im2 that remain unmatched and do
% not satisfy rthresh (the more selective threshold).
[p2, z2] = harris_pts(im2, 'smoothing', smoothing, ...
'nmsrad', nmsrad, 'rthresh', rthresh2);
% If no interest points were provided for the first image, compute them
if (isempty(p1))
p1 = harris_pts(im1, 'smoothing', smoothing, 'nmsrad', nmsrad, ...
'rthresh', rthresh);
else
% Ensure the final coordinates are unity
p1 = p1 ./ p1(:, [3 3 3]);
end
% STEP 2: Form a cost matrix based upon local properties of the
% interest points. The cost metric we use here is the sum of
% squared differences of intensity values in a square
% neighborhood around the pixels; a hard Euclidean distance
% threshold is implemented so all point pairs that are too far
% apart are given infinite cost.
D = disteusq(p1(:, 1:2), p2(:, 1:2), 'xs');
N1 = nbhds(im1, round(p1(:, 2)), round(p1(:, 1)), 5, 5);
N2 = nbhds(im2, round(p2(:, 2)), round(p2(:, 1)), 5, 5);
C = disteusq(double(N1), double(N2), 'x');
C(find(D > dthresh)) = Inf;
% STEP 3: Compute the correspondence.
[a, F] = corr(p1, p2, C, 'sdthresh', sdthresh, corr_opts{:});
% STEP 4: Enforce thresholds. Keep only those points in the second
% image that (a) obey the primary relative threshold or (b)
% are matched with points in the first image.
i = find(a);
k = setdiff(find(z2 >= rthresh * max(z2)), a(i));
p2 = p2([a(i); k], :);
a(i) = 1:length(i);
figure
imagesc(im1);
colormap gray
hold on
for i=1:size(p1,1)
plot(p1(i,1),p1(i,2),'g+');
end
for i=1:size(p1,1)
x = p1(i,1);
y = p1(i,2);
if a(i)~=0
u = p2(a(i),1)-p1(i,1);
v = p2(a(i),2)-p1(i,2);
plot([x x+u],[y y+v],'y');
end
end
figure
imagesc(im2);
colormap gray
hold on
for i=1:size(p2,1)
plot(p2(i,1),p2(i,2),'g+');
end
|
github
|
jacksky64/imageProcessing-master
|
skeleton.m
|
.m
|
imageProcessing-master/FastMarching_version3b/skeleton.m
| 6,068 |
utf_8
|
bc89aea0d0615547c269a6f02eb57787
|
function S=skeleton(I,verbose)
% This function Skeleton will calculate an accurate skeleton (centerlines)
% of an object represented by an binary image / volume using the fastmarching
% distance transform.
%
% S=skeleton(I,verbose)
%
% inputs,
% I : A 2D or 3D binary image
% verbose : Boolean, set to true (default) for debug information
%
% outputs
% S : Cell array with the centerline coordinates of the skeleton branches
%
% Literature
% Robert van Uitert and Ingmar Bitter : "Subvoxel precise skeletons of volumetric
% data base on fast marching methods", 2007.
%
% Example 2D,
%
% % Read Blood vessel image
% I=im2double(rgb2gray(imread('images/vessels2d.png')));
%
% % Convert double image to logical
% Ibin=I<0.5;
%
% % Use fastmarching to find the skeleton
% S=skeleton(Ibin);
% % Display the skeleton
% figure, imshow(Ibin); hold on;
% for i=1:length(S)
% L=S{i};
% plot(L(:,2),L(:,1),'-','Color',rand(1,3));
% end
%
%
% Example 3D,
%
% % Read Blood vessel image
% load('images/vessels3d');
% % Note, this data is pre-processed from Dicom ConeBeam-CT with
% % V = imfill(Vraw > 30000,'holes');
%
% % Use fastmarching to find the skeleton
% S=skeleton(V);
%
%
% % Show the iso-surface of the vessels
% figure,
% FV = isosurface(V,0.5)
% patch(FV,'facecolor',[1 0 0],'facealpha',0.3,'edgecolor','none');
% view(3)
% camlight
% % Display the skeleton
% hold on;
% for i=1:length(S)
% L=S{i};
% plot3(L(:,2),L(:,1),L(:,3),'-','Color',rand(1,3));
% end
if(nargin<2), verbose=true; end
if(size(I,3)>1), IS3D=true; else IS3D=false; end
% Distance to vessel boundary
BoundaryDistance=getBoundaryDistance(I,IS3D);
if(verbose),
disp('Distance Map Constructed');
end
% Get maximum distance value, which is used as starting point of the
% first skeleton branch
[SourcePoint,maxD]=maxDistancePoint(BoundaryDistance,I,IS3D);
% Make a fastmarching speed image from the distance image
SpeedImage=(BoundaryDistance/maxD).^4;
SpeedImage(SpeedImage==0)=1e-10;
% Skeleton segments found by fastmarching
SkeletonSegments=cell(1,1000);
% Number of skeleton iterations
itt=0;
while(true)
if(verbose),
disp(['Find Branches Iterations : ' num2str(itt)]);
end
% Do fast marching using the maximum distance value in the image
% and the points describing all found branches are sourcepoints.
[T,Y] = msfm(SpeedImage, SourcePoint, false, false);
% Trace a branch back to the used sourcepoints
StartPoint=maxDistancePoint(Y,I,IS3D);
ShortestLine=shortestpath(T,StartPoint,SourcePoint,1,'rk4');
% Calculate the length of the new skeleton segment
linelength=GetLineLength(ShortestLine,IS3D);
% Stop finding branches, if the lenght of the new branch is smaller
% then the diameter of the largest vessel
if(linelength<maxD*2), break; end;
% Store the found branch skeleton
itt=itt+1;
SkeletonSegments{itt}=ShortestLine;
% Add found branche to the list of fastmarching SourcePoints
SourcePoint=[SourcePoint ShortestLine'];
end
SkeletonSegments(itt+1:end)=[];
S=OrganizeSkeleton(SkeletonSegments,IS3D);
if(verbose),
disp(['Skeleton Branches Found : ' num2str(length(S))]);
end
function ll=GetLineLength(L,IS3D)
if(IS3D)
dist=sqrt((L(2:end,1)-L(1:end-1,1)).^2+ ...
(L(2:end,2)-L(1:end-1,2)).^2+ ...
(L(2:end,3)-L(1:end-1,3)).^2);
else
dist=sqrt((L(2:end,1)-L(1:end-1,1)).^2+ ...
(L(2:end,2)-L(1:end-1,2)).^2);
end
ll=sum(dist);
function S=OrganizeSkeleton(SkeletonSegments,IS3D)
n=length(SkeletonSegments);
if(IS3D)
Endpoints=zeros(n*2,3);
else
Endpoints=zeros(n*2,2);
end
l=1;
for w=1:n
ss=SkeletonSegments{w};
l=max(l,length(ss));
Endpoints(w*2-1,:)=ss(1,:);
Endpoints(w*2,:) =ss(end,:);
end
CutSkel=spalloc(size(Endpoints,1),l,10000);
ConnectDistance=2^2;
for w=1:n
ss=SkeletonSegments{w};
ex=repmat(Endpoints(:,1),1,size(ss,1));
sx=repmat(ss(:,1)',size(Endpoints,1),1);
ey=repmat(Endpoints(:,2),1,size(ss,1));
sy=repmat(ss(:,2)',size(Endpoints,1),1);
if(IS3D)
ez=repmat(Endpoints(:,3),1,size(ss,1));
sz=repmat(ss(:,3)',size(Endpoints,1),1);
end
if(IS3D)
D=(ex-sx).^2+(ey-sy).^2+(ez-sz).^2;
else
D=(ex-sx).^2+(ey-sy).^2;
end
check=min(D,[],2)<ConnectDistance;
check(w*2-1)=false; check(w*2)=false;
if(any(check))
j=find(check);
for i=1:length(j)
line=D(j(i),:);
[foo,k]=min(line);
if((k>2)&&(k<(length(line)-2))), CutSkel(w,k)=1; end
end
end
end
pp=0;
for w=1:n
ss=SkeletonSegments{w};
r=[1 find(CutSkel(w,:)) length(ss)];
for i=1:length(r)-1
pp=pp+1;
S{pp}=ss(r(i):r(i+1),:);
end
end
function BoundaryDistance=getBoundaryDistance(I,IS3D)
% Calculate Distance to vessel boundary
% Set all boundary pixels as fastmarching source-points (distance = 0)
if(IS3D),S=ones(3,3,3); else S=ones(3,3); end
B=xor(I,imdilate(I,S));
ind=find(B(:));
if(IS3D)
[x,y,z]=ind2sub(size(B),ind);
SourcePoint=[x(:) y(:) z(:)]';
else
[x,y]=ind2sub(size(B),ind);
SourcePoint=[x(:) y(:)]';
end
% Calculate Distance to boundarypixels for every voxel in the volume
SpeedImage=ones(size(I));
BoundaryDistance = msfm(SpeedImage, SourcePoint, false, true);
% Mask the result by the binary input image
BoundaryDistance(~I)=0;
function [posD,maxD]=maxDistancePoint(BoundaryDistance,I,IS3D)
% Mask the result by the binary input image
BoundaryDistance(~I)=0;
% Find the maximum distance voxel
[maxD,ind] = max(BoundaryDistance(:));
if(~isfinite(maxD))
error('Skeleton:Maximum','Maximum from MSFM is infinite !');
end
if(IS3D)
[x,y,z]=ind2sub(size(I),ind); posD=[x;y;z];
else
[x,y]=ind2sub(size(I),ind); posD=[x;y];
end
|
github
|
jacksky64/imageProcessing-master
|
msfm.m
|
.m
|
imageProcessing-master/FastMarching_version3b/msfm.m
| 5,104 |
utf_8
|
8166322eef83fa858c709f64c52df7ba
|
function [T,Y]=msfm(F, SourcePoints, UseSecond, UseCross)
% This function MSFM calculates the shortest distance from a list of
% points to all other pixels in an image volume, using the
% Multistencil Fast Marching Method (MSFM). This method gives more accurate
% distances by using second order derivatives and cross neighbours.
%
% [T,Y]=msfm(F, SourcePoints, UseSecond, UseCross)
%
% inputs,
% F: The 2D or 3D speed image. The speed function must always be larger
% than zero (min value 1e-8), otherwise some regions will
% never be reached because the time will go to infinity.
% SourcePoints : A list of starting points [2 x N ] or [3 x N] (distance zero)
% UseSecond : Boolean Set to true if not only first but also second
% order derivatives are used (default)
% UseCross : Boolean Set to true if also cross neighbours
% are used (default)
% outputs,
% T : Image with distance from SourcePoints to all pixels
% Y : Image for augmented fastmarching with, euclidian distance from
% SourcePoints to all pixels. (Used by skeletonize method)
%
% Note:
% Run compile_c_files.m to allow 3D fast marching and for cpu-effective
% registration of 2D fast marching.
%
% Note(2):
% Accuracy of this method is enhanced by just summing the coefficients
% of the cross and normal terms as suggested by Olivier Roy.
%
% Literature : M. Sabry Hassouna et Al. Multistencils Fast Marching
% Methods: A Highly Accurate Solution to the Eikonal Equation on
% Cartesian Domains
%
%
% Example 2D,
% SourcePoint = [51; 51];
% SpeedImage = ones([101 101]);
% [X Y] = ndgrid(1:101, 1:101);
% T1 = sqrt((X-SourcePoint(1)).^2 + (Y-SourcePoint(2)).^2);
%
% % Run fast marching 1th order, 1th order multi stencil
% % and 2th orde and 2th orde multi stencil
%
% tic; T1_FMM1 = msfm(SpeedImage, SourcePoint, false, false); toc;
% tic; T1_MSFM1 = msfm(SpeedImage, SourcePoint, false, true); toc;
% tic; T1_FMM2 = msfm(SpeedImage, SourcePoint, true, false); toc;
% tic; T1_MSFM2 = msfm(SpeedImage, SourcePoint, true, true); toc;
%
% % Show results
% fprintf('\nResults with T1 (Matlab)\n');
% fprintf('Method L1 L2 Linf\n');
% Results = cellfun(@(x)([mean(abs(T1(:)-x(:))) mean((T1(:)-x(:)).^2) max(abs(T1(:)-x(:)))]), {T1_FMM1(:) T1_MSFM1(:) T1_FMM2(:) T1_MSFM2(:)}, 'UniformOutput',false);
% fprintf('FMM1: %9.5f %9.5f %9.5f\n', Results{1}(1), Results{1}(2), Results{1}(3));
% fprintf('MSFM1: %9.5f %9.5f %9.5f\n', Results{2}(1), Results{2}(2), Results{2}(3));
% fprintf('FMM2: %9.5f %9.5f %9.5f\n', Results{3}(1), Results{3}(2), Results{3}(3));
% fprintf('MSFM2: %9.5f %9.5f %9.5f\n', Results{4}(1), Results{4}(2), Results{4}(3));
%
%
% Example 2D, multiple starting points,
%
% SourcePoint=rand(2,100)*255+1;
% SpeedImage = ones([256 256]);
% tic; T1_MSFM2 = msfm(SpeedImage, SourcePoint, true, true); toc;
% figure, imshow(T1_MSFM2,[]); colormap(hot(256));
%
%
% Example 3D,
% SourcePoint = [21; 21; 21];
% SpeedImage = ones([41 41 41]);
% [X,Y,Z] = ndgrid(1:41, 1:41, 1:41);
% T1 = sqrt((X-SourcePoint(1)).^2 + (Y-SourcePoint(2)).^2 + (Z-SourcePoint(3)).^2);
%
% % Run fast marching 1th order, 1th order multi stencil
% % and 2th orde and 2th orde multi stencil
%
% tic; T1_FMM1 = msfm(SpeedImage, SourcePoint, false, false); toc;
% tic; T1_MSFM1 = msfm(SpeedImage, SourcePoint, false, true); toc;
% tic; T1_FMM2 = msfm(SpeedImage, SourcePoint, true, false); toc;
% tic; T1_MSFM2 = msfm(SpeedImage, SourcePoint, true, true); toc;
%
% % Show results
% fprintf('\nResults with T1 (Matlab)\n');
% fprintf('Method L1 L2 Linf\n');
% Results = cellfun(@(x)([mean(abs(T1(:)-x(:))) mean((T1(:)-x(:)).^2) max(abs(T1(:)-x(:)))]), {T1_FMM1(:) T1_MSFM1(:) T1_FMM2(:) T1_MSFM2(:)}, 'UniformOutput',false);
% fprintf('FMM1: %9.5f %9.5f %9.5f\n', Results{1}(1), Results{1}(2), Results{1}(3));
% fprintf('MSFM1: %9.5f %9.5f %9.5f\n', Results{2}(1), Results{2}(2), Results{2}(3));
% fprintf('FMM2: %9.5f %9.5f %9.5f\n', Results{3}(1), Results{3}(2), Results{3}(3));
% fprintf('MSFM2: %9.5f %9.5f %9.5f\n', Results{4}(1), Results{4}(2), Results{4}(3));
%
% Function is written by D.Kroon University of Twente (Oct 2010)
add_function_paths();
if(nargin<3), UseSecond=false; end
if(nargin<4), UseCross=false; end
if(nargout>1)
if(size(F,3)>1)
[T,Y]=msfm3d(F, SourcePoints, UseSecond, UseCross);
else
[T,Y]=msfm2d(F, SourcePoints, UseSecond, UseCross);
end
else
if(size(F,3)>1)
T=msfm3d(F, SourcePoints, UseSecond, UseCross);
else
T=msfm2d(F, SourcePoints, UseSecond, UseCross);
end
end
function add_function_paths()
try
functionname='msfm.m';
functiondir=which(functionname);
functiondir=functiondir(1:end-length(functionname));
addpath([functiondir '/functions'])
addpath([functiondir '/shortestpath'])
catch me
disp(me.message);
end
|
github
|
jacksky64/imageProcessing-master
|
msfm2d.m
|
.m
|
imageProcessing-master/FastMarching_version3b/functions/msfm2d.m
| 11,010 |
utf_8
|
f96cf4a042008f8a5e6c2c2f847e3a67
|
function [T,Y]=msfm2d(F, SourcePoints, usesecond, usecross)
% This function MSFM2D calculates the shortest distance from a list of
% points to all other pixels in an image, using the
% Multistencil Fast Marching Method (MSFM). This method gives more accurate
% distances by using second order derivatives and cross neighbours.
%
% T=msfm2d(F, SourcePoints, UseSecond, UseCross)
%
% inputs,
% F: The speed image. The speed function must always be larger
% than zero (min value 1e-8), otherwise some regions will
% never be reached because the time will go to infinity.
% SourcePoints : A list of starting points [2 x N] (distance zero)
% UseSecond : Boolean Set to true if not only first but also second
% order derivatives are used (default)
% UseCross : Boolean Set to true if also cross neighbours
% are used (default)
% outputs,
% T : Image with distance from SourcePoints to all pixels
%
% Note:
% Compile the c file "mex msfm2d.c" for cpu-effective registration
%
% Literature : M. Sabry Hassouna et Al. Multistencils Fast Marching
% Methods: A Highly Accurate Solution to the Eikonal Equation on
% Cartesian Domains
%
% Example,
% SourcePoint = [51; 51];
% SpeedImage = ones([101 101]);
% [X Y] = ndgrid(1:101, 1:101);
% T1 = sqrt((X-SourcePoint(1)).^2 + (Y-SourcePoint(2)).^2);
%
% % Run fast marching 1th order, 1th order multi stencil
% % and 2th orde and 2th orde multi stencil
%
% tic; T1_FMM1 = msfm2d(SpeedImage, SourcePoint, false, false); toc;
% tic; T1_MSFM1 = msfm2d(SpeedImage, SourcePoint, false, true); toc;
% tic; T1_FMM2 = msfm2d(SpeedImage, SourcePoint, true, false); toc;
% tic; T1_MSFM2 = msfm2d(SpeedImage, SourcePoint, true, true); toc;
%
% % Show results
% fprintf('\nResults with T1 (Matlab)\n');
% fprintf('Method L1 L2 Linf\n');
% Results = cellfun(@(x)([mean(abs(T1(:)-x(:))) mean((T1(:)-x(:)).^2) max(abs(T1(:)-x(:)))]), {T1_FMM1(:) T1_MSFM1(:) T1_FMM2(:) T1_MSFM2(:)}, 'UniformOutput',false);
% fprintf('FMM1: %9.5f %9.5f %9.5f\n', Results{1}(1), Results{1}(2), Results{1}(3));
% fprintf('MSFM1: %9.5f %9.5f %9.5f\n', Results{2}(1), Results{2}(2), Results{2}(3));
% fprintf('FMM2: %9.5f %9.5f %9.5f\n', Results{3}(1), Results{3}(2), Results{3}(3));
% fprintf('MSFM2: %9.5f %9.5f %9.5f\n', Results{4}(1), Results{4}(2), Results{4}(3));
%
% Example multiple starting points,
% SourcePoint=rand(2,100)*255+1;
% SpeedImage = ones([256 256]);
% tic; T1_MSFM2 = msfm2d(SpeedImage, SourcePoint, true, true); toc;
% figure, imshow(T1_MSFM2,[]); colormap(hot(256));
%
% Function is written by D.Kroon University of Twente (June 2009)
% Distance image, also used to store the index of narrowband pixels
% during marching process
T = zeros(size(F))-1;
% Augmented Fast Marching (For skeletonize)
Ed=nargout>1;
% Euclidian distance image
if(Ed), Y = zeros(size(F)); end
% Pixels which are processed and have a final distance are frozen
Frozen = zeros(size(F));
% Free memory to store neighbours of the (segmented) region
neg_free = 100000;
neg_pos=0;
if(Ed),
neg_list = zeros(4,neg_free);
else
neg_list = zeros(3,neg_free);
end
% (There are 3 pixel classes:
% - frozen (processed)
% - narrow band (boundary) (in list to check for the next pixel with smallest distance)
% - far (not yet used)
% Neighbours
ne =[-1 0;
1 0;
0 -1;
0 1];
SourcePoints=int32(floor(SourcePoints));
% set all starting points to distance zero and frozen
for z=1:size(SourcePoints,2)
% starting point
x= SourcePoints(1,z); y=SourcePoints(2,z);
% Set starting point to frozen and distance to zero
Frozen(x,y)=1; T(x,y)=0;
end
% Add all neighbours of the starting points to narrow list
for z=1:size(SourcePoints,2)
% starting point
x=SourcePoints(1,z);
y=SourcePoints(2,z);
for k=1:4,
% Location of neighbour
i=x+ne(k,1); j=y+ne(k,2);
% Check if current neighbour is not yet frozen and inside the
% picture
if((i>0)&&(j>0)&&(i<=size(F,1))&&(j<=size(F,2))&&(Frozen(i,j)==0))
Tt=1/max(F(i,j),eps);
Ty=1;
% Update distance in neigbour list or add to neigbour list
if(T(i,j)>0)
if(neg_list(1,T(i,j))>Tt)
neg_list(1,T(i,j))=Tt;
end
if(Ed)
neg_list(4,T(i,j))=min(Ty,neg_list(4,T(i,j)));
end
else
neg_pos=neg_pos+1;
% If running out of memory at a new block
if(neg_pos>neg_free), neg_free = neg_free +100000; neg_list(1,neg_free)=0; end
if(Ed)
neg_list(:,neg_pos)=[Tt;i;j;Ty];
else
neg_list(:,neg_pos)=[Tt;i;j];
end
T(i,j)=neg_pos;
end
end
end
end
% Loop through all pixels of the image
for itt=1:numel(F)
% Get the pixel from narrow list (boundary list) with smallest
% distance value and set it to current pixel location
[t,index]=min(neg_list(1,1:neg_pos));
if(neg_pos==0), break; end
x=neg_list(2,index); y=neg_list(3,index);
Frozen(x,y)=1;
T(x,y)=neg_list(1,index);
if(Ed), Y(x,y)=neg_list(4,index); end
% Remove min value by replacing it with the last value in the array
if(index<neg_pos),
neg_list(:,index)=neg_list(:,neg_pos);
x2=neg_list(2,index); y2=neg_list(3,index);
T(x2,y2)=index;
end
neg_pos =neg_pos-1;
% Loop through all 4 neighbours of current pixel
for k=1:4,
% Location of neighbour
i=x+ne(k,1); j=y+ne(k,2);
% Check if current neighbour is not yet frozen and inside the
% picture
if((i>0)&&(j>0)&&(i<=size(F,1))&&(j<=size(F,2))&&(Frozen(i,j)==0))
Tt=CalculateDistance(T,F(i,j),size(F),i,j,usesecond,usecross,Frozen);
if(Ed)
Ty=CalculateDistance(Y,1,size(F),i,j,usesecond,usecross,Frozen);
end
% Update distance in neigbour list or add to neigbour list
if(T(i,j)>0)
neg_list(1,T(i,j))=min(Tt,neg_list(1,T(i,j)));
if(Ed)
neg_list(4,T(i,j))=min(Ty,neg_list(4,T(i,j)));
end
else
neg_pos=neg_pos+1;
% If running out of memory at a new block
if(neg_pos>neg_free), neg_free = neg_free +100000; neg_list(1,neg_free)=0; end
if(Ed)
neg_list(:,neg_pos)=[Tt;i;j;Ty];
else
neg_list(:,neg_pos)=[Tt;i;j];
end
T(i,j)=neg_pos;
end
end
end
end
function Tt=CalculateDistance(T,Fij,sizeF,i,j,usesecond,usecross,Frozen)
% Boundary and frozen check -> current patch
Tpatch=inf(5,5);
for nx=-2:2
for ny=-2:2
in=i+nx; jn=j+ny;
if((in>0)&&(jn>0)&&(in<=sizeF(1))&&(jn<=sizeF(2))&&(Frozen(in,jn)==1))
Tpatch(nx+3,ny+3)=T(in,jn);
end
end
end
% The values in order is 0 if no neighbours in that direction
% 1 if 1e order derivatives is used and 2 if second order
% derivatives are used
Order=zeros(1,4);
% Make 1e order derivatives in x and y direction
Tm(1) = min( Tpatch(2,3) , Tpatch(4,3)); if(isfinite(Tm(1))), Order(1)=1; end
Tm(2) = min( Tpatch(3,2) , Tpatch(3,4)); if(isfinite(Tm(2))), Order(2)=1; end
% Make 1e order derivatives in cross directions
if(usecross)
Tm(3) = min( Tpatch(2,2) , Tpatch(4,4)); if(isfinite(Tm(3))), Order(3)=1; end
Tm(4) = min( Tpatch(2,4) , Tpatch(4,2)); if(isfinite(Tm(4))), Order(4)=1; end
end
% Make 2e order derivatives
if(usesecond)
Tm2=zeros(1,4);
% pixels with a pixeldistance 2 from the center must be
% lower in value otherwise use other side or first order
ch1=(Tpatch(1,3)<Tpatch(2,3))&&isfinite(Tpatch(2,3)); ch2=(Tpatch(5,3)<Tpatch(4,3))&&isfinite(Tpatch(4,3));
if(ch1&&ch2),Tm2(1) =min( (4*Tpatch(2,3)-Tpatch(1,3))/3 , (4*Tpatch(4,3)-Tpatch(5,3))/3); Order(1)=2;
elseif(ch1), Tm2(1) =(4*Tpatch(2,3)-Tpatch(1,3))/3; Order(1)=2;
elseif(ch2), Tm2(1) =(4*Tpatch(4,3)-Tpatch(5,3))/3; Order(1)=2;
end
ch1=(Tpatch(3,1)<Tpatch(3,2))&&isfinite(Tpatch(3,2)); ch2=(Tpatch(3,5)<Tpatch(3,4))&&isfinite(Tpatch(3,4));
if(ch1&&ch2),Tm2(2) =min( (4*Tpatch(3,2)-Tpatch(3,1))/3 , (4*Tpatch(3,4)-Tpatch(3,5))/3); Order(2)=2;
elseif(ch1), Tm2(2)=(4*Tpatch(3,2)-Tpatch(3,1))/3; Order(2)=2;
elseif(ch2), Tm2(2)=(4*Tpatch(3,4)-Tpatch(3,5))/3; Order(2)=2;
end
if(usecross)
ch1=(Tpatch(1,1)<Tpatch(2,2))&&isfinite(Tpatch(2,2)); ch2=(Tpatch(5,5)<Tpatch(4,4))&&isfinite(Tpatch(4,4));
if(ch1&&ch2),Tm2(3) =min( (4*Tpatch(2,2)-Tpatch(1,1))/3 , (4*Tpatch(4,4)-Tpatch(5,5))/3); Order(3)=2;
elseif(ch1), Tm2(3)=(4*Tpatch(2,2)-Tpatch(1,1))/3; Order(3)=2;
elseif(ch2), Tm2(3)=(4*Tpatch(4,4)-Tpatch(5,5))/3; Order(3)=2;
end
ch1=(Tpatch(1,5)<Tpatch(2,4))&&isfinite(Tpatch(2,4)); ch2=(Tpatch(5,1)<Tpatch(4,2))&&isfinite(Tpatch(4,2));
if(ch1&&ch2),Tm2(4) =min( (4*Tpatch(2,4)-Tpatch(1,5))/3 , (4*Tpatch(4,2)-Tpatch(5,1))/3); Order(4)=2;
elseif(ch1), Tm2(4)=(4*Tpatch(2,4)-Tpatch(1,5))/3; Order(4)=2;
elseif(ch2), Tm2(4)=(4*Tpatch(4,2)-Tpatch(5,1))/3; Order(4)=2;
end
end
else
Tm2=zeros(1,4);
end
% Calculate the distance using x and y direction
Coeff = [0 0 -1/(max(Fij^2,eps))];
for t=1:2;
switch(Order(t))
case 1,
Coeff=Coeff+[1 -2*Tm(t) Tm(t)^2];
case 2,
Coeff=Coeff+[1 -2*Tm2(t) Tm2(t)^2]*(2.2500);
end
end
Tt=roots(Coeff); Tt=max(Tt);
% Calculate the distance using the cross directions
if(usecross)
Coeff = Coeff + [0 0 -1/(max(Fij^2,eps))];
for t=3:4;
switch(Order(t))
case 1,
Coeff=Coeff+0.5*[1 -2*Tm(t) Tm(t)^2];
case 2,
Coeff=Coeff+0.5*[1 -2*Tm2(t) Tm2(t)^2]*(2.2500);
end
end
Tt2=roots(Coeff); Tt2=max(Tt2);
% Select minimum distance value of both stensils
if(~isempty(Tt2)), Tt=min(Tt,Tt2); end
end
% Upwind condition check, current distance must be larger
% then direct neighbours used in solution
DirectNeigbInSol=Tm(isfinite(Tm));
if(nnz(DirectNeigbInSol>=Tt)>0) % Will this ever happen?
Tt=min(DirectNeigbInSol)+(1/(max(Fij,eps)));
end
function z=roots(Coeff)
a=Coeff(1); b=Coeff(2); c=Coeff(3); d=max((b*b)-4.0*a*c,0);
if(a~=0)
z(1)= (-b - sqrt(d)) / (2.0*a);
z(2)= (-b + sqrt(d)) / (2.0*a);
else
z(1)= (2.0*c)/(-b - sqrt(d));
z(2)= (2.0*c)/(-b + sqrt(d));
end
|
github
|
jacksky64/imageProcessing-master
|
region_measurement.m
|
.m
|
imageProcessing-master/3dViewer/region_measurement.m
| 10,315 |
utf_8
|
3281727018491aae4fe7dcd5a14fe172
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright:
% Jun Tan
% University of Texas Southwestern Medical Center
% Department of Radiation Oncology
% Last edited: 08/19/2014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = region_measurement(varargin)
% REGION_MEASUREMENT MATLAB code for region_measurement.fig
% REGION_MEASUREMENT, by itself, creates a new REGION_MEASUREMENT or raises the existing
% singleton*.
%
% H = REGION_MEASUREMENT returns the handle to a new REGION_MEASUREMENT or the handle to
% the existing singleton*.
%
% REGION_MEASUREMENT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in REGION_MEASUREMENT.M with the given input arguments.
%
% REGION_MEASUREMENT('Property','Value',...) creates a new REGION_MEASUREMENT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before region_measurement_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to region_measurement_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 region_measurement
% Last Modified by GUIDE v2.5 19-Aug-2014 22:40:16
% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @region_measurement_OpeningFcn, ...
'gui_OutputFcn', @region_measurement_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 region_measurement is made visible.
function region_measurement_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 region_measurement (see VARARGIN)
% Choose default command line output for region_measurement
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
parse_args(hObject, varargin);
setappdata(hObject, 'entry_update_data', @parse_args);
set(hObject, 'Visible', getappdata(hObject, 'initialVisible'));
% -------------------------------------------------------------------
function parse_args(hFig, args)
handles = guidata(hFig);
numArgs = length(args);
assert(1 == numArgs || 2 == numArgs || 3 == numArgs, 'Must have 1, 2, or 3 arguments');
setappdata(handles.figure_rs, 'regionType', 1); % 1: rectangle, 2: disc.
setappdata(handles.figure_rs, 'mainFigHandle', []);
setappdata(handles.figure_rs, 'initialVisible', 'on');
if 1 == numArgs
if is_handle(args{1})
setappdata(handles.figure_rs, 'mainFigHandle', args{1});
setappdata(handles.figure_rs, 'initialVisible', 'off');
else
parse_region_data(handles, args{1});
end
elseif 2 == numArgs
if is_handle(args{2})
setappdata(handles.figure_rs, 'mainFigHandle', args{2});
else
assert(strcmpi('Rectangle', args{2}) || strcmpi('Disc', args{2}) || strcmpi('Drawn', args{2}), ...
'Region shape must be disc or rectangle or user-drawn.');
if strcmpi('Disc', args{2})
setappdata(handles.figure_rs, 'regionType', 2);
elseif strcmpi('Drawn', args{2})
setappdata(handles.figure_rs, 'regionType', 3);
end
end
parse_region_data(handles, args{1});
else % if 3 == numArgs
assert(strcmpi('Disc', args{2}) || strcmpi('Rectangle', args{2}) || strcmpi('Drawn', args{2}), ...
'Region shape must be disc or rectangle or user-drawn.');
if strcmpi('Disc', args{2})
setappdata(handles.figure_rs, 'regionType', 2);
elseif strcmpi('Drawn', args{2})
setappdata(handles.figure_rs, 'regionType', 3);
end
assert(is_handle(args{3}), 'The third argument must be a valid GUI handle.');
setappdata(handles.figure_rs, 'mainFigHandle', args{3});
parse_region_data(handles, args{1});
end
update_measurement(handles);
% -------------------------------------------------------------------
function parse_region_data(handles, regionData)
regionType = getappdata(handles.figure_rs, 'regionType');
if 1 == regionType || 2 == regionType
assert((isnumeric(regionData) || islogical(regionData)) && ismatrix(regionData), ...
'Data must be gray or binary 2D image.');
setappdata(handles.figure_rs, 'regionData', double(regionData));
else %3 == regionType
assert(isa(regionData, 'cell') && isa(regionData{1}, 'double') && isa(regionData{2}, 'logical') ....
&& isequal(size(regionData{1}), size(regionData{2})));
setappdata(handles.figure_rs, 'regionData', regionData{1});
setappdata(handles.figure_rs, 'regionMask', regionData{2});
end
% -------------------------------------------------------------------
function update_measurement(handles)
regionData = getappdata(handles.figure_rs, 'regionData');
regionType = getappdata(handles.figure_rs, 'regionType');
pixels = [];
if 1 == regionType || 2 == regionType
data = cell(6, 2);
data{1, 1} = ' Shape';
data{2, 1} = ' #Points';
data{3, 1} = ' Area';
data{4, 1} = ' Width';
data{5, 1} = ' Height';
data{6, 1} = ' Max';
data{7, 1} = ' Min';
data{8, 1} = ' Mean';
data{9, 1} = ' SD';
if 1 == regionType
data{1, 2} = ' Rectangle';
pixels = regionData(:);
elseif 2 == regionType
data{1, 2} = ' Disc';
h = size(regionData, 1);
w = size(regionData, 2);
cy = h / 2.0 + 0.5;
cx = w / 2.0 + 0.5;
[x, y] = meshgrid(1:w, 1:h);
dx = abs(x - cx);
dy = abs(y - cy);
c = ((dx .^ 2) / (cx .^ 2) + (dy .^ 2) ./ (cy .^ 2)) <= 1;
pixels = regionData(c);
end
data{2, 2} = numel(pixels);
if data{2, 2} > 0
data{3, 2} = numel(pixels);
data{4, 2} = size(regionData, 2);
data{5, 2} = size(regionData, 1);
data{6, 2} = max(pixels);
data{7, 2} = min(pixels);
data{8, 2} = mean(pixels);
data{9, 2} = std(pixels);
end
else %if 3 == regionType
data = cell(16, 2);
data{1, 1} = ' Shape';
data{2, 1} = ' Area';
data{3, 1} = ' Centroid.X';
data{4, 1} = ' Centroid.Y';
data{5, 1} = ' W.Cent.X';
data{6, 1} = ' W.Cent.Y';
data{7, 1} = ' Orientation';
data{8, 1} = ' Major Axis';
data{9, 1} = ' Minor Axis';
data{10, 1} = ' Equiv Diam';
data{11, 1} = ' Perimeter';
data{12, 1} = ' Solidity';
data{13, 1} = ' Max';
data{14, 1} = ' Min';
data{15, 1} = ' Mean';
data{16, 1} = ' SD';
img = getappdata(handles.figure_rs, 'regionData');
mask = getappdata(handles.figure_rs, 'regionMask');
stats = regionprops(mask, img, ...
{'Area', 'Centroid', 'Orientation', 'MajorAxisLength', 'MinorAxisLength', ...
'EquivDiameter', 'Perimeter', 'Solidity', 'MaxIntensity', 'MinIntensity', ...
'MeanIntensity', 'WeightedCentroid'});
if length(stats) >= 1
stats = stats(1);
pixels = img(mask);
data{1, 2} = 'User-Drawn';
data{2, 2} = stats.Area;
data{3, 2} = stats.Centroid(1);
data{4, 2} = stats.Centroid(2);
data{5, 2} = stats.WeightedCentroid(1);
data{6, 2} = stats.WeightedCentroid(2);
data{7, 2} = stats.Orientation;
data{8, 2} = stats.MajorAxisLength;
data{9, 2} = stats.MinorAxisLength;
data{10, 2} = stats.EquivDiameter;
data{11, 2} = stats.Perimeter;
data{12, 2} = stats.Solidity;
data{13, 2} = stats.MaxIntensity;
data{14, 2} = stats.MinIntensity;
data{15, 2} = stats.MeanIntensity;
data{16, 2} = std(pixels);
end
end
set(handles.uitable_stats, 'Data', data);
if ~isempty(pixels)
hist(handles.axes_hist, pixels, 100);
box(handles.axes_hist, 'off');
xlabel(handles.axes_hist, 'Pixel value');
ylabel(handles.axes_hist, 'Counts');
end
check_grid(handles);
% -------------------------------------------------------------------
function check_grid(handles)
if 1 == get(handles.checkbox_grid, 'Value')
grid(handles.axes_hist, 'on');
else
grid(handles.axes_hist, 'off');
end
% --- Outputs from this function are returned to the command line.
function varargout = region_measurement_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 checkbox_grid.
function checkbox_grid_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_grid (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_grid
check_grid(handles);
% --- Executes when user attempts to close figure_rs.
function figure_rs_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure_rs (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mainFigHandle = getappdata(handles.figure_rs, 'mainFigHandle');
if is_handle(mainFigHandle)
hFun = getappdata(mainFigHandle, 'hFunCallbackRegionMeasurementClosed');
if isa(hFun, 'function_handle')
feval(hFun, mainFigHandle);
end
else
delete(hObject);
end
|
github
|
jacksky64/imageProcessing-master
|
vi_isoline.m
|
.m
|
imageProcessing-master/3dViewer/vi_isoline.m
| 7,864 |
utf_8
|
57f608cd389b82381976ee8981ad3aee
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright:
% Jun Tan
% University of Texas Southwestern Medical Center
% Department of Radiation Oncology
% Last edited: 08/19/2014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = vi_isoline(varargin)
% VI_ISOLINE MATLAB code for vi_isoline.fig
% VI_ISOLINE, by itself, creates a new VI_ISOLINE or raises the existing
% singleton*.
%
% H = VI_ISOLINE returns the handle to a new VI_ISOLINE or the handle to
% the existing singleton*.
%
% VI_ISOLINE('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in VI_ISOLINE.M with the given input arguments.
%
% VI_ISOLINE('Property','Value',...) creates a new VI_ISOLINE or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before vi_isoline_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to vi_isoline_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 vi_isoline
% Last Modified by GUIDE v2.5 25-Aug-2014 11:57:32
% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @vi_isoline_OpeningFcn, ...
'gui_OutputFcn', @vi_isoline_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 vi_isoline is made visible.
function vi_isoline_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 vi_isoline (see VARARGIN)
% Choose default command line output for vi_isoline
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
numArgs = length(varargin);
assert(1 == numArgs && is_handle(varargin{1}), 'Only allow main GUI handle as argument.');
setappdata(handles.figure_isoline, 'mainFigHandle', varargin{1});
data = cell(20, 2);
data(:, 2) = {false};
set(handles.uitable_isovalues, 'Data', data);
set(hObject, 'Visible', 'off');
% -------------------------------------------------------------------
function send_isovalues_to_main_gui(handles)
mainFigHandle = getappdata(handles.figure_isoline, 'mainFigHandle');
if is_handle(mainFigHandle)
hFun = getappdata(mainFigHandle, 'hFunCallbackIsolineUpdate');
if isa(hFun, 'function_handle')
data = get(handles.uitable_isovalues, 'Data');
isovalues = [data{:, 1}];
shown = [data{1:length(isovalues), 2}];
isovalues = isovalues(shown);
showCLabel = 1 == get(handles.checkbox_clabel, 'Value');
feval(hFun, mainFigHandle, isovalues, showCLabel);
end
end
% --- Outputs from this function are returned to the command line.
function varargout = vi_isoline_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 when entered data in editable cell(s) in uitable_isovalues.
function uitable_isovalues_CellEditCallback(hObject, eventdata, handles)
% hObject handle to uitable_isovalues (see GCBO)
% eventdata structure with the following fields (see UITABLE)
% Indices: row and column indices of the cell(s) edited
% PreviousData: previous data for the cell(s) edited
% EditData: string(s) entered by the user
% NewData: EditData or its converted form set on the Data property. Empty if Data was not changed
% Error: error string when failed to convert EditData to appropriate value for Data
% handles structure with handles and user data (see GUIDATA)
data = get(handles.uitable_isovalues, 'Data');
if 1 == eventdata.Indices(2) % Only need to check data for column 1.
if isempty(eventdata.EditData) % Delete cell content to delete a value.
data{eventdata.Indices(1), eventdata.Indices(2)} = [];
elseif isnan(eventdata.NewData) % Entered a non-numeric string. Revert change.
data{eventdata.Indices(1), eventdata.Indices(2)} = eventdata.PreviousData;
disp('Must enter a number.');
set(handles.uitable_isovalues, 'Data', data);
return;
elseif length(find([data{:, 1}] == eventdata.NewData)) > 1 % Entered a existing value. Revert change.
data{eventdata.Indices(1), eventdata.Indices(2)} = eventdata.PreviousData;
disp('Must enter a value that did not exist.');
set(handles.uitable_isovalues, 'Data', data);
return;
else % Show by default if entered a new value.
data(eventdata.Indices(1), 2) = {true};
set(handles.uitable_isovalues, 'Data', data);
end
end
data = data(~cellfun(@isempty, data(:, 1)), :);
[~, idx] = sort(cell2mat(data(:, 1)));
data = data(idx, :);
data((size(data, 1)+1):20, 2) = {false};
set(handles.uitable_isovalues, 'Data', data);
send_isovalues_to_main_gui(handles);
% --- Executes when user attempts to close figure_isoline.
function figure_isoline_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure_isoline (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mainFigHandle = getappdata(handles.figure_isoline, 'mainFigHandle');
if is_handle(mainFigHandle)
hFun = getappdata(mainFigHandle, 'hFunCallbackIsolineClosed');
if isa(hFun, 'function_handle')
feval(hFun, mainFigHandle);
end
else
delete(hObject);
end
% --- Executes on button press in checkbox_clabel.
function checkbox_clabel_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_clabel (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_clabel
send_isovalues_to_main_gui(handles);
% --- Executes on button press in pushbutton_showAll.
function pushbutton_showAll_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_showAll (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data = get(handles.uitable_isovalues, 'Data');
numVals = length([data{:, 1}]);
data(1:numVals, 2) = {true};
set(handles.uitable_isovalues, 'Data', data);
send_isovalues_to_main_gui(handles);
% --- Executes on button press in pushbutton_hideAll.
function pushbutton_hideAll_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_hideAll (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
data = get(handles.uitable_isovalues, 'Data');
numVals = length([data{:, 1}]);
data(1:numVals, 2) = {false};
set(handles.uitable_isovalues, 'Data', data);
send_isovalues_to_main_gui(handles);
|
github
|
jacksky64/imageProcessing-master
|
vi.m
|
.m
|
imageProcessing-master/3dViewer/vi.m
| 78,447 |
utf_8
|
d16920fc5fbdbfde1720a0708614b1fb
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright:
% Jun Tan
% University of Texas Southwestern Medical Center
% Department of Radiation Oncology
% Last edited: 08/19/2014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = vi(varargin)
% VI MATLAB code for vi.fig
% VI, by itself, creates a new VI or raises the existing
% singleton*.
%
% H = VI returns the handle to a new VI or the handle to
% the existing singleton*.
%
% VI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in VI.M with the given input arguments.
%
% VI('Property','Value',...) creates a new VI or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before vi_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to vi_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 vi
% Last Modified by GUIDE v2.5 19-Aug-2014 13:59:42
% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @vi_OpeningFcn, ...
'gui_OutputFcn', @vi_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 vi is made visible.
function vi_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 vi (see VARARGIN)
% Choose default command line output for vi
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
% UIWAIT makes vi wait for user response (see UIRESUME)
% uiwait(handles.figure_vi);
if nargin <= 3
img = flipud(phantom('Modified Shepp-Logan', 512)); % Generate a phantom image if no input is given.
img = int32(1000 * (img - 0.2) / 0.2);
else
img = varargin{1};
end
assert(isnumeric(img) || islogical(img), 'First argument must be numeric.');
img = squeeze(img); % Remove singleton dimensions.
maxPixelVal = max(img(:));
minPixelVal = min(img(:));
assert(maxPixelVal ~= minPixelVal, 'Image must contain at least 2 different values.');
numDims = ndims(img);
assert((2 == numDims || 3 == numDims) && all(size(img) > 1), 'Image must be either 2D or 3D.');
options = varargin(2:end);
assert(0 == mod(length(options), 2), 'Argument must be name and value pairs.');
argCheckMap = containers.Map;
argCheckMap('clim') = false;
argCheckMap('aspect') = false;
setappdata(handles.figure_vi, 'argCheckMap', argCheckMap);
while ~isempty(options) && length(options) >= 2
check_arg(handles, options{1}, options{2});
options = options(3:end);
end
argCheckMap = getappdata(handles.figure_vi, 'argCheckMap');
imgSize = size(img);
if 2 == numDims % 2D images don't need these uicontrols.
set([ ...
handles.radiobutton_sagittalView, ...
handles.radiobutton_coronalView, ...
handles.radiobutton_3dSlice, ...
handles.togglebutton_light, ...
handles.togglebutton_rotate, ...
handles.slider_xSliceNo, ...
handles.slider_ySliceNo, ...
handles.slider_zSliceNo, ...
handles.edit_sliceNo, ...
handles.slider_sliceNo], ...
'Enable', 'off');
set(handles.slider_sliceNo, 'Max', 1, 'Min', 0, 'SliderStep', [0.1 0.1]);
elseif 3 == numDims % 3D images need multiple views, rotation, etc.
set([ ...
handles.radiobutton_sagittalView, ...
handles.radiobutton_coronalView, ...
handles.radiobutton_3dSlice, ...
handles.togglebutton_light, ...
handles.togglebutton_rotate, ...
handles.slider_xSliceNo, ...
handles.slider_ySliceNo, ...
handles.slider_zSliceNo, ...
handles.edit_sliceNo, ...
handles.slider_sliceNo], ...
'Enable', 'on');
set(handles.slider_xSliceNo, 'Max', imgSize(2), 'Min', 1, 'SliderStep', [1/(imgSize(2)-1) 10/(imgSize(2)-1)]);
set(handles.slider_ySliceNo, 'Max', imgSize(1), 'Min', 1, 'SliderStep', [1/(imgSize(1)-1) 10/(imgSize(1)-1)]);
set(handles.slider_zSliceNo, 'Max', imgSize(3), 'Min', 1, 'SliderStep', [1/(imgSize(3)-1) 10/(imgSize(3)-1)]);
sliceNo3d = ceil(imgSize / 2); % Initially display center slices.
sliceNo3d = sliceNo3d([2 1 3]); % Reorder as [x y z].
setappdata(handles.figure_vi, 'sliceNo3d', sliceNo3d);
set(handles.slider_xSliceNo, 'Value', sliceNo3d(1));
set(handles.slider_ySliceNo, 'Value', sliceNo3d(2));
set(handles.slider_zSliceNo, 'Value', sliceNo3d(3));
set(handles.slider_sliceNo, 'Min', 1);
end
setappdata(handles.figure_vi, 'imgData', img);
setappdata(handles.figure_vi, 'imgSize', imgSize);
setappdata(handles.figure_vi, 'numDims', numDims);
cb = colorbar('peer', handles.axes_colorBar, 'location', 'west');
setappdata(handles.figure_vi, 'colorBar', cb);
% Get number string format.
if isinteger(img) || islogical(img)
dataFormat = '%.0f';
else % if isfloat(img)
maxVal = max(abs(maxPixelVal), abs(minPixelVal));
if maxVal > 1e5 || maxVal < 1e-1
dataFormat = '%.3e';
else
dataFormat = '%.3f';
end
end
setappdata(handles.figure_vi, 'dataFormat', dataFormat);
set(handles.text_maxPixelVal, 'String', num2str(maxPixelVal, dataFormat));
set(handles.text_minPixelVal, 'String', num2str(minPixelVal, dataFormat));
set(handles.axes_2dViewer, 'CLimMode', 'manual');
if ~argCheckMap('clim')
set_clims(handles, minPixelVal, maxPixelVal);
end
if ~argCheckMap('aspect')
setappdata(handles.figure_vi, 'aspectRatio', [1 1 1]);
end
setappdata(handles.figure_vi, 'buttonDown', false);
setappdata(handles.figure_vi, 'ptOnAxesBtnDown', [1 1]);
setappdata(handles.figure_vi, 'regionType', 'Rectangle');
setup_ui_menus(handles.figure_vi);
update_window_info(handles);
plot_resize_arrow(handles.axes_resizeArrow);
update_view_type(handles);
% -------------------------------------------------------------------
function setup_ui_menus(hFig)
uiMenus = struct;
guiChildren = get(hFig, 'Children');
for i = 1 : length(guiChildren)
child = guiChildren(i);
childTag = get(child, 'Tag');
if strcmpi('menu_moreWindowSettings', childTag)
uiMenus.menu_moreWindowSettings = child;
elseif strcmpi('menu_selectRegionType', childTag)
uiMenus.menu_selectRegionType = child;
end
end
setappdata(hFig, 'uiMenus', uiMenus);
% -------------------------------------------------------------------
function plot_resize_arrow(hAxes)
hold(hAxes, 'on');
setappdata(hAxes, 'resizeArrow', [ ...
plot(hAxes, [9 15], [9 15], 'b'), ...
plot(hAxes, [15 15], [15 1], 'b'), ...
plot(hAxes, [15 1], [15 15], 'b')]);
set(getappdata(hAxes, 'resizeArrow'), 'HitTest', 'off');
hold(hAxes, 'off');
axis(hAxes, 'off');
% -------------------------------------------------------------------
function check_arg(handles, argName, argVal)
assert(ischar(argName), 'Argument name must be characters.');
argCheckMap = getappdata(handles.figure_vi, 'argCheckMap');
if strcmpi('window', argName) && isnumeric(argVal) && 2 == length(argVal)
set_clims(handles, argVal(2) - argVal(1) / 2, argVal(2) + argVal(1) / 2);
argCheckMap('clim') = true;
elseif strcmpi('range', argName) && isnumeric(argVal) && 2 == length(argVal)
set_clims(handles, argVal(1), argVal(2));
argCheckMap('clim') = true;
elseif strcmpi('aspect', argName) && isnumeric(argVal) && 3 == length(argVal)
setappdata(handles.figure_vi, 'aspectRatio', argVal);
argCheckMap('aspect') = true;
else
error([argName ' is not a valid argument name.']);
end
setappdata(handles.figure_vi, 'argCheckMap', argCheckMap);
% -------------------------------------------------------------------
function update_window_info(handles)
dataFormat = getappdata(handles.figure_vi, 'dataFormat');
cLim = get(handles.axes_2dViewer, 'CLim');
set(handles.edit_windowMax, 'String', num2str(cLim(2), dataFormat));
set(handles.edit_windowMin, 'String', num2str(cLim(1), dataFormat));
set(handles.edit_windowWidth, 'String', num2str(range(cLim), dataFormat));
set(handles.edit_windowLevel, 'String', num2str(mean(cLim), dataFormat));
% -------------------------------------------------------------------
function update_view_type(handles)
sliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
viewType = get_view_type(handles);
if viewType == 4
set(handles.uipanel_2dViewer, 'Visible', 'off');
set(handles.uipanel_3dSlicer, 'Visible', 'on');
set([ ...
handles.togglebutton_light, ...
handles.togglebutton_rotate, ...
handles.slider_xSliceNo, ...
handles.slider_ySliceNo, ...
handles.slider_zSliceNo], ...
'Enable', 'on');
update_slice_3d(handles, sliceNo3d(1), sliceNo3d(2), sliceNo3d(3), true);
else
rotate3d(handles.axes_3dSlicer, 'off'); % If in 3D rotating status, turn it off.
set(handles.uipanel_2dViewer, 'Visible', 'on');
set(handles.uipanel_3dSlicer, 'Visible', 'off');
set([ ...
handles.togglebutton_light, ...
handles.togglebutton_rotate, ...
handles.slider_xSliceNo, ...
handles.slider_ySliceNo, ...
handles.slider_zSliceNo], ...
'Enable', 'off');
imgSize = getappdata(handles.figure_vi, 'imgSize');
switch viewType
case 1
sliceSize = imgSize([1 2]);
if 2 == getappdata(handles.figure_vi, 'numDims')
numSlices = 1;
sliceNo = 1;
else
numSlices = imgSize(3);
sliceNo = sliceNo3d(3);
end
case 2
sliceSize = imgSize([3 1]);
numSlices = imgSize(2);
sliceNo = sliceNo3d(1);
case 3
sliceSize = imgSize([3 2]);
numSlices = imgSize(1);
sliceNo = sliceNo3d(2);
otherwise
error('Invalid view type!');
end
setappdata(handles.figure_vi, 'sliceSize', sliceSize);
setappdata(handles.figure_vi, 'numSlices', numSlices);
set(handles.text_numSlices, 'String', ['/ ' num2str(numSlices)]);
if numSlices > 1
set(handles.slider_sliceNo, ...
'Max', numSlices, ...
'SliderStep', [1/(numSlices-1) 10/(numSlices-1)]);
end
update_slice_2d(handles, sliceNo, true);
end
% -------------------------------------------------------------------
function update_slice_3d(handles, xSliceNo, ySliceNo, zSliceNo, newView)
oldSliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
imgSize = getappdata(handles.figure_vi, 'imgSize');
xSliceNo = max(min(round(xSliceNo), imgSize(2)), 1);
ySliceNo = max(min(round(ySliceNo), imgSize(1)), 1);
zSliceNo = max(min(round(zSliceNo), imgSize(3)), 1);
setappdata(handles.figure_vi, 'sliceNo3d', [xSliceNo ySliceNo zSliceNo]);
set(handles.slider_xSliceNo, 'Value', xSliceNo);
set(handles.slider_ySliceNo, 'Value', ySliceNo);
set(handles.slider_zSliceNo, 'Value', zSliceNo);
img = getappdata(handles.figure_vi, 'imgData');
hSlices = getappdata(handles.figure_vi, 'hSlices');
if newView && isempty(hSlices)
hSlices = slice(handles.axes_3dSlicer, double(img), xSliceNo, ySliceNo, zSliceNo);
setappdata(handles.figure_vi, 'hSlices', hSlices);
xlabel(handles.axes_3dSlicer, 'x - L/R');
ylabel(handles.axes_3dSlicer, 'y - A/P');
zlabel(handles.axes_3dSlicer, 'z - I/S');
set(handles.axes_3dSlicer, ...
'XLim', [1 imgSize(2)], 'YLim', [1 imgSize(1)], 'ZLim', [1 imgSize(3)]);
cLim = get(handles.axes_2dViewer, 'CLim');
set_clims(handles, cLim(1), cLim(2));
shading(handles.axes_3dSlicer, 'flat');
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
daspect(handles.axes_3dSlicer, 1 ./ [aspectRatio(1) aspectRatio(2) aspectRatio(3)]);
set_colormap(handles);
% Create light source at camera position.
hLight = light('Parent', handles.axes_3dSlicer, ...
'Position', get(handles.axes_3dSlicer, 'CameraPosition'));
setappdata(handles.figure_vi, 'hLight', hLight);
set_light(handles);
else
if oldSliceNo3d(1) ~= xSliceNo
set(hSlices(1), ...
'CData', double(squeeze(img(:, xSliceNo, :))), ...
'XData', ones(imgSize(1), imgSize(3)) * xSliceNo);
end
if oldSliceNo3d(2) ~= ySliceNo
set(hSlices(2), ...
'CData', double(squeeze(img(ySliceNo, :, :))), ...
'YData', ones(imgSize(2), imgSize(3)) * ySliceNo);
end
if oldSliceNo3d(3) ~= zSliceNo
set(hSlices(3), ...
'CData', double(squeeze(img(:, :, zSliceNo))), ...
'ZData', ones(imgSize(1), imgSize(2)) * zSliceNo);
end
end
check_rotate(handles);
% -------------------------------------------------------------------
function set_light(handles)
axes(handles.axes_3dSlicer); % Must make axes_3dSlicer current for lighting.
if 1 == get(handles.togglebutton_light, 'Value')
lighting phong;
else
lighting none;
end
% -------------------------------------------------------------------
function rotate_pre_callback(obj, evd)
setappdata(obj, 'rotating', true);
% -------------------------------------------------------------------
function rotate_post_callback(obj, evd)
setappdata(obj, 'rotating', false);
% -------------------------------------------------------------------
function check_rotate(handles)
if 1 == get(handles.togglebutton_rotate, 'Value')
rotate3d(handles.axes_3dSlicer, 'on');
h = rotate3d(handles.figure_vi);
set(h, ...
'ActionPreCallback', @rotate_pre_callback, ...
'ActionPostCallback', @rotate_post_callback, ...
'Enable', 'on');
else
rotate3d(handles.axes_3dSlicer, 'off');
end
% -------------------------------------------------------------------
function update_slice_2d(handles, sliceNo, newView)
numSlices = getappdata(handles.figure_vi, 'numSlices');
sliceNo = max(min(round(sliceNo), numSlices), 1);
sliceNoEdit = round(str2double(get(handles.edit_sliceNo, 'String')));
if sliceNo ~= sliceNoEdit
set(handles.edit_sliceNo, 'String', num2str(sliceNo));
end
sliceNoSlider = round(get(handles.slider_sliceNo, 'Value'));
if sliceNo ~= sliceNoSlider
set(handles.slider_sliceNo, 'Value', sliceNo);
end
setappdata(handles.figure_vi, 'sliceNo', sliceNo);
set(handles.edit_sliceNo, 'String', num2str(sliceNo));
img = getappdata(handles.figure_vi, 'imgData');
sliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
viewType = get_view_type(handles);
switch viewType
case 1
sliceImage = squeeze(img(:, :, sliceNo));
sliceNo3d(3) = sliceNo;
case 2
sliceImage = squeeze(img(:, sliceNo, :))';
sliceNo3d(1) = sliceNo;
case 3
sliceImage = squeeze(img(sliceNo, :, :))';
sliceNo3d(2) = sliceNo;
otherwise
error('Invalid view type!');
end
setappdata(handles.figure_vi, 'sliceNo3d', sliceNo3d);
setappdata(handles.figure_vi, 'sliceImage', sliceImage);
if newView
cLim = get(handles.axes_2dViewer, 'CLim');
hSliceImage = imshow(flipud(sliceImage), cLim, 'Parent', handles.axes_2dViewer);
set_colormap(handles);
setappdata(handles.figure_vi, 'hSliceImage', hSliceImage);
else
hSliceImage = getappdata(handles.figure_vi, 'hSliceImage');
set(hSliceImage, 'CData', flipud(sliceImage));
end
update_aspect_ratio(handles);
hFigSliceStats = getappdata(handles.figure_vi, 'hFigSliceStats');
if is_handle(hFigSliceStats)
feval(getappdata(hFigSliceStats, 'entry_update_data'), ...
hFigSliceStats, {sliceImage, handles.figure_vi});
end
hDrawRegion = getappdata(handles.figure_vi, 'hDrawRegion');
hFigRegionMeasurement = getappdata(handles.figure_vi, 'hFigRegionMeasurement');
if is_handle(hFigRegionMeasurement) && is_handle(hDrawRegion)
if strcmpi('Drawn', getappdata(handles.figure_vi, 'regionType'))
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
hFigRegionMeasurement = getappdata(handles.figure_vi, 'hFigRegionMeasurement');
if is_handle(hFigRegionMeasurement) && is_handle(hDrawRegionAdd)
update_user_drawn_region_data(handles);
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
if is_handle(hDrawRegionAdd) && strcmpi('on', get(hDrawRegionAdd, 'Visible'))
set(hDrawRegionAdd, 'LineStyle', '-', 'Color', 'r');
end
end
else
update_region_data(handles);
end
end
hDrawLine = getappdata(handles.figure_vi, 'hDrawLine');
hFigLineMeasurement = getappdata(handles.figure_vi, 'hFigLineMeasurement');
if is_handle(hFigLineMeasurement) && is_handle(hDrawLine)
update_line_data(handles);
end
if 1 == get(handles.togglebutton_isoline, 'Value')
update_isolines(handles);
end
% -------------------------------------------------------------------
function set_clims(handles, loLim, hiLim)
set(handles.axes_2dViewer, 'CLim', [loLim hiLim]);
set(handles.axes_3dSlicer, 'CLim', [loLim hiLim]);
set(handles.axes_colorBar, 'CLim', [loLim hiLim]);
% -------------------------------------------------------------------
function set_colormap(handles)
cm = getappdata(handles.figure_vi, 'pixelCMap');
if isempty(cm)
setappdata(handles.figure_vi, 'pixelCMap', colormap(handles.axes_2dViewer));
else
cmInd = get(handles.listbox_colorMaps,'Value');
switch cmInd
case 1
cm = getappdata(handles.figure_vi, 'pixelCMap');
colormap(handles.axes_2dViewer, cm);
otherwise
contents = cellstr(get(handles.listbox_colorMaps,'String'));
cmapFun = lower(contents{cmInd});
colormap(handles.axes_2dViewer, feval(cmapFun, 256));
end
end
% -------------------------------------------------------------------
function update_aspect_ratio(handles)
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
switch get_view_type(handles)
case 1
set(handles.axes_2dViewer, 'DataAspectRatio', aspectRatio([1 2 3]));
case 2
set(handles.axes_2dViewer, 'DataAspectRatio', aspectRatio([3 2 1]));
case 3
set(handles.axes_2dViewer, 'DataAspectRatio', aspectRatio([3 1 2]));
otherwise
end
daspect(handles.axes_3dSlicer, 1 ./ [aspectRatio(1) aspectRatio(2) aspectRatio(3)]);
set(handles.edit_xAspectRatio, 'String', num2str(aspectRatio(1), '%.1f'));
set(handles.edit_yAspectRatio, 'String', num2str(aspectRatio(2), '%.1f'));
set(handles.edit_zAspectRatio, 'String', num2str(aspectRatio(3), '%.1f'));
% -------------------------------------------------------------------
function viewType = get_view_type(handles)
viewType = find(get(handles.uipanel_viewType, 'SelectedObject') == ...
[handles.radiobutton_transverseView ...
handles.radiobutton_sagittalView ...
handles.radiobutton_coronalView ...
handles.radiobutton_3dSlice]);
% -------------------------------------------------------------------
function set_obj_pos(hObj, x, top, width, height)
parentPos = get(get(hObj, 'Parent'), 'Position');
y = parentPos(4) - top - height + 1;
set(hObj, 'Position', [x y width height]);
% -------------------------------------------------------------------
function [minWidth, minHeight] = get_min_gui_size(hFig)
uicontrolTypes = ...
{'checkbox', 'edit', 'listbox', 'pushbutton', ....
'radiobutton', 'slider', 'text', 'togglebutton', ...
'axes', 'uitable', 'uipanel', 'uibuttongroup'};
children = get(hFig, 'Children');
children(~ismember(get(children, 'Type'), uicontrolTypes)) = [];
children(strcmpi(get(children, 'Visible'), 'off')) = [];
children(strcmpi(get(children, 'Tag'), 'uipanel_resizeArrow')) = [];
numChildren = length(children);
width = zeros(numChildren, 1);
top = zeros(numChildren, 1);
bottom = zeros(numChildren, 1) + 999;
for i = 1 : numChildren
child = children(i);
pos = get(child, 'Position');
width(i) = pos(1) + pos(3);
top(i) = pos(2) + pos(4);
bottom(i) = pos(2);
if isprop(child, 'TightInset')
ti = get(child, 'TightInset');
width(i) = width(i) + ti(3);
top(i) = top(i) + ti(4);
bottom(i) = bottom(i) - ti(2);
end
end
minWidth = max(width);
minHeight = max(top) - min(bottom);
% -------------------------------------------------------------------
function auto_layout(handles)
guiPos = get(handles.figure_vi, 'Position');
viewSize = getappdata(handles.figure_vi, 'sliceSize');
set(handles.axes_top, 'XLim', [1 viewSize(2)]);
set(handles.axes_bottom, 'XLim', [1 viewSize(2)]);
set(handles.axes_left, 'YLim', [1 viewSize(1)]);
set(handles.axes_right, 'YLim', [1 viewSize(1)]);
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
viewType = get_view_type(handles);
switch viewType
case 1
viewSize(1) = viewSize(1) * aspectRatio(1);
viewSize(2) = viewSize(2) * aspectRatio(2);
case 2
viewSize(1) = viewSize(1) * aspectRatio(3);
viewSize(2) = viewSize(2) * aspectRatio(1);
case 3
viewSize(1) = viewSize(1) * aspectRatio(3);
viewSize(2) = viewSize(2) * aspectRatio(2);
otherwise
end
leftPanelPos = get(handles.uipanel_leftControls, 'Position');
controlPanelPos2d = get(handles.uipanel_2dControls, 'Position');
tiT = get(handles.axes_top, 'TightInset');
tiTHeight = tiT(4) + 10 + tiT(2);
tiB = get(handles.axes_bottom, 'TightInset');
tiBHeight = tiB(4) + 10 + tiB(2);
tiL = get(handles.axes_left, 'TightInset');
tiLWidth = tiL(1) + 10 + tiL(3);
tiR = get(handles.axes_right, 'TightInset');
tiRWidth = tiR(1) + 10 + tiR(3);
viewerX = leftPanelPos(3) + 5;
viewerY = 1;
viewerWidth = max(controlPanelPos2d(3), tiLWidth + 2 + viewSize(2) + 2 + tiRWidth);
viewerHeight = controlPanelPos2d(4) + 2 + tiTHeight + 2 + viewSize(1) + 2 + tiBHeight;
controlPanelPos3d = get(handles.uipanel_3dControls, 'Position');
imgSize = getappdata(handles.figure_vi, 'imgSize');
if 2 == length(imgSize)
imgSize(3) = 1;
end
slicerX = leftPanelPos(3) + 5;
slicerY = 1;
slicerWidth = ceil(max(controlPanelPos3d(3), max(imgSize .* aspectRatio) * 1.4));
slicerHeight = controlPanelPos3d(4) + slicerWidth;
set_obj_pos(handles.uipanel_leftControls, leftPanelPos(1), 1, leftPanelPos(3), leftPanelPos(4));
set_obj_pos(handles.uipanel_2dViewer, viewerX, viewerY, viewerWidth, viewerHeight);
set_obj_pos(handles.uipanel_2dControls, 1, 1, controlPanelPos2d(3), controlPanelPos2d(4));
set_obj_pos(handles.axes_top, ...
tiLWidth+2, ...
controlPanelPos2d(4) + 2 + tiT(4)+2, ...
viewSize(2), 10);
set_obj_pos(handles.axes_bottom, ...
tiLWidth+2, ...
controlPanelPos2d(4) + 2 + tiTHeight + 2 + viewSize(1) + 2, ...
viewSize(2), 10);
set_obj_pos(handles.axes_left, ...
tiL(1) + 2, ...
controlPanelPos2d(4) + 2 + tiTHeight + 2, ...
10, viewSize(1));
set_obj_pos(handles.axes_right, ...
tiLWidth + 2 + viewSize(2) + 2, ...
controlPanelPos2d(4) + 2 + tiTHeight + 2, ...
10, viewSize(1));
set_obj_pos(handles.axes_2dViewer, ...
tiLWidth + 2, ...
controlPanelPos2d(4) + 2 + tiTHeight + 2, ...
viewSize(2), viewSize(1));
set_obj_pos(handles.uipanel_3dSlicer, slicerX, slicerY, slicerWidth, slicerHeight);
set_obj_pos(handles.uipanel_3dControls, 1, 1, controlPanelPos3d(3), controlPanelPos3d(4));
set_obj_pos(handles.axes_3dSlicer, 70, 80, slicerWidth - 120, slicerHeight - 130);
cb = getappdata(handles.figure_vi, 'colorBar');
if 4 == viewType
colorBarX = slicerX + slicerWidth + 10;
else
colorBarX = viewerX + viewerWidth + 10;
end
colorBarY = max(controlPanelPos2d(4), controlPanelPos3d(4)) + 30;
colorBarHeight = max(256, min(512, guiPos(4) - colorBarY - 30));
set_obj_pos(handles.axes_colorBar, colorBarX, colorBarY, 20, colorBarHeight);
set(cb, 'Units', 'pixels');
set_obj_pos(cb, colorBarX, colorBarY, 20, colorBarHeight);
[minWidth, minHeight] = get_min_gui_size(handles.figure_vi);
if minWidth > guiPos(3) || minHeight > guiPos(4)
set(handles.uipanel_resizeArrow, ...
'Position', [guiPos(3)-20 5 17 17], ...
'Visible', 'on');
else
set(handles.uipanel_resizeArrow, 'Visible', 'off');
end
% -------------------------------------------------------------------
function [ptOnAxesCurrent, onImage] = get_pointer_pos(handles)
if 4 == get_view_type(handles)
imgSize = getappdata(handles.figure_vi, 'imgSize');
ptOnAxesCurrent = round(get(handles.axes_3dSlicer, 'CurrentPoint'));
onImage = all(ptOnAxesCurrent(:) >= 1) ...
&& ptOnAxesCurrent(1, 1) <= imgSize(2) ...
&& ptOnAxesCurrent(1, 2) <= imgSize(1) ...
&& ptOnAxesCurrent(1, 3) <= imgSize(3) ...
&& ptOnAxesCurrent(2, 1) <= imgSize(2) ...
&& ptOnAxesCurrent(2, 2) <= imgSize(1) ...
&& ptOnAxesCurrent(2, 3) <= imgSize(3);
else
sliceSize = getappdata(handles.figure_vi, 'sliceSize');
ptOnAxesCurrent = get(handles.axes_2dViewer, 'CurrentPoint');
ptOnAxesCurrent = round(ptOnAxesCurrent(1, 1:2));
ptOnAxesCurrent(2) = sliceSize(1) - ptOnAxesCurrent(2) + 1;
onImage = ptOnAxesCurrent(1) >= 1 && ptOnAxesCurrent(1) <= sliceSize(2) ...
&& ptOnAxesCurrent(2) >= 1 && ptOnAxesCurrent(2) <= sliceSize(1);
end
% -------------------------------------------------------------------
function event_image_stats_closed(hGui)
assert(is_handle(hGui));
handles = guidata(hGui);
set(handles.togglebutton_sliceStats, 'Value', 0);
set_image_stats(handles, 0);
% -------------------------------------------------------------------
function event_region_measurement_closed(hGui)
assert(is_handle(hGui));
handles = guidata(hGui);
set(handles.togglebutton_regionMeasure, 'Value', 0);
set_region_measure(handles, 0);
% -------------------------------------------------------------------
function event_line_measurement_closed(hGui)
assert(is_handle(hGui));
handles = guidata(hGui);
set(handles.togglebutton_lineMeasure, 'Value', 0);
set_line_measure(handles, 0);
% -------------------------------------------------------------------
function event_isoline_closed(hGui)
assert(is_handle(hGui));
handles = guidata(hGui);
set(handles.togglebutton_isoline, 'Value', 0);
set_isoline(handles, 0);
% -------------------------------------------------------------------
function msg_map_isoline_update(hGui, isovalues, showCLabel)
assert(is_handle(hGui));
handles = guidata(hGui);
setappdata(handles.figure_vi, 'isovalues', isovalues);
setappdata(handles.figure_vi, 'showCLabel', showCLabel);
update_isolines(handles);
% -------------------------------------------------------------------
function update_isolines(handles)
if 0 == get(handles.togglebutton_isoline, 'Value')
return;
end
hIsolines = getappdata(handles.figure_vi, 'hIsolines');
if is_handle(hIsolines)
delete(hIsolines);
end
isovalues = getappdata(handles.figure_vi, 'isovalues');
if 1 == numel(isovalues)
isovalues = [isovalues isovalues];
end
sliceImage = getappdata(handles.figure_vi, 'sliceImage');
hold(handles.axes_2dViewer, 'on');
[c, hIsolines] = contour(handles.axes_2dViewer, flipud(sliceImage), isovalues, 'color', 'r');
showCLabel = getappdata(handles.figure_vi, 'showCLabel');
if showCLabel
clabel(c, hIsolines);
end
hold(handles.axes_2dViewer, 'off');
setappdata(handles.figure_vi, 'hIsolines', hIsolines);
% -------------------------------------------------------------------
function set_image_stats(handles, showTool)
hFigSliceStats = getappdata(handles.figure_vi, 'hFigSliceStats');
if 1 == showTool
if ~is_handle(hFigSliceStats)
sliceImage = getappdata(handles.figure_vi, 'sliceImage');
hFigSliceStats = image_stats(sliceImage, handles.figure_vi);
setappdata(handles.figure_vi, 'hFigSliceStats', hFigSliceStats);
setappdata(handles.figure_vi, 'hFunCallbackSliceStatsClosed', @event_image_stats_closed);
pos1 = get(handles.figure_vi, 'Position');
pos2 = get(hFigSliceStats, 'Position');
set(hFigSliceStats, 'Position', [pos1(1)+pos1(3)+16 pos1(2) pos2(3) pos2(4)]);
end
set(hFigSliceStats, 'Visible', 'on');
figure(handles.figure_vi);
else
if is_handle(hFigSliceStats)
set(hFigSliceStats, 'Visible', 'off');
end
end
% -------------------------------------------------------------------
function set_region_measure(handles, showTool)
% Delete region plot on image.
hDrawRegion = getappdata(handles.figure_vi, 'hDrawRegion');
if is_handle(hDrawRegion)
delete(hDrawRegion);
end
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
if is_handle(hDrawRegionAdd)
delete(hDrawRegionAdd);
end
hFigRegionMeasurement = getappdata(handles.figure_vi, 'hFigRegionMeasurement');
if 1 == showTool
if ~is_handle(hFigRegionMeasurement)
hFigRegionMeasurement = region_measurement(handles.figure_vi);
setappdata(handles.figure_vi, 'hFigRegionMeasurement', hFigRegionMeasurement);
setappdata(handles.figure_vi, 'hFunCallbackRegionMeasurementClosed', @event_region_measurement_closed);
pos1 = get(handles.figure_vi, 'Position');
pos2 = get(hFigRegionMeasurement, 'Position');
set(hFigRegionMeasurement, 'Position', [pos1(1)+pos1(3)+16 pos1(2) pos2(3) pos2(4)]);
end
set(hFigRegionMeasurement, 'Visible', 'on');
figure(handles.figure_vi);
if strcmpi('Drawn', getappdata(handles.figure_vi, 'regionType'))
update_user_drawn_region_data(handles);
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
if is_handle(hDrawRegionAdd) && strcmpi('on', get(hDrawRegionAdd, 'Visible'))
set(hDrawRegionAdd, 'LineStyle', '-', 'Color', 'r');
end
else
update_region_data(handles);
end
else
if is_handle(hFigRegionMeasurement)
set(hFigRegionMeasurement, 'Visible', 'off');
end
end
% -------------------------------------------------------------------
function set_line_measure(handles, showTool)
% Delete line plot on image.
hDrawLine = getappdata(handles.figure_vi, 'hDrawLine');
if is_handle(hDrawLine)
delete(hDrawLine);
end
hFigLineMeasurement = getappdata(handles.figure_vi, 'hFigLineMeasurement');
if 1 == showTool
if ~is_handle(hFigLineMeasurement) % Open a new line measurement GUI next to main GUI.
hFigLineMeasurement = line_measurement(handles.figure_vi);
setappdata(handles.figure_vi, 'hFigLineMeasurement', hFigLineMeasurement);
setappdata(handles.figure_vi, 'hFunCallbackLineMeasurementClosed', @event_line_measurement_closed);
pos1 = get(handles.figure_vi, 'Position');
pos2 = get(hFigLineMeasurement, 'Position');
set(hFigLineMeasurement, 'Position', [pos1(1)+pos1(3)+16 pos1(2) pos2(3) pos2(4)]);
end
set(hFigLineMeasurement, 'Visible', 'on');
figure(handles.figure_vi);
update_line_data(handles);
else
if is_handle(hFigLineMeasurement)
set(hFigLineMeasurement, 'Visible', 'off');
end
end
% -------------------------------------------------------------------
function set_isoline(handles, showTool)
hIsolines = getappdata(handles.figure_vi, 'hIsolines');
if is_handle(hIsolines)
delete(hIsolines);
end
hFigIsoline = getappdata(handles.figure_vi, 'hFigIsoline');
if 1 == showTool
if ~is_handle(hFigIsoline) % Open a new isoline GUI next to main GUI.
hFigIsoline = vi_isoline(handles.figure_vi);
setappdata(handles.figure_vi, 'hFigIsoline', hFigIsoline);
setappdata(handles.figure_vi, 'hFunCallbackIsolineClosed', @event_isoline_closed);
setappdata(handles.figure_vi, 'hFunCallbackIsolineUpdate', @msg_map_isoline_update);
pos1 = get(handles.figure_vi, 'Position');
pos2 = get(hFigIsoline, 'Position');
set(hFigIsoline, 'Position', [pos1(1)+pos1(3)+16 pos1(2) pos2(3) pos2(4)]);
end
set(hFigIsoline, 'Visible', 'on');
figure(handles.figure_vi);
update_isolines(handles);
else
if is_handle(hFigIsoline)
set(hFigIsoline, 'Visible', 'off');
end
end
% -------------------------------------------------------------------
function update_user_drawn_region_data(handles)
userDrawRegionVertices = getappdata(handles.figure_vi, 'userDrawRegionVertices');
if isempty(userDrawRegionVertices)
return;
end
hDrawRegion = getappdata(handles.figure_vi, 'hDrawRegion');
if ishandle(hDrawRegion)
delete(hDrawRegion);
setappdata(handles.figure_vi, 'hDrawRegion', []);
end
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
if ishandle(hDrawRegionAdd)
delete(hDrawRegionAdd);
setappdata(handles.figure_vi, 'hDrawRegionAdd', []);
end
viewSize = getappdata(handles.figure_vi, 'sliceSize');
x = userDrawRegionVertices(:, 1);
y = userDrawRegionVertices(:, 2);
sliceImage = getappdata(handles.figure_vi, 'sliceImage');
hold(handles.axes_2dViewer, 'on');
hDrawRegion = plot(handles.axes_2dViewer, x, viewSize(1) - y, 'r');
hDrawRegionAdd = plot(handles.axes_2dViewer, x([end 1]), viewSize(1) - y([end 1]), ':y');
hold(handles.axes_2dViewer, 'off');
setappdata(handles.figure_vi, 'hDrawRegion', hDrawRegion);
setappdata(handles.figure_vi, 'hDrawRegionAdd', hDrawRegionAdd);
hFigRegionMeasurement = getappdata(handles.figure_vi, 'hFigRegionMeasurement');
if is_handle(hFigRegionMeasurement)
mask = poly2mask(x, y, viewSize(1), viewSize(2));
feval(getappdata(hFigRegionMeasurement, 'entry_update_data'), ...
hFigRegionMeasurement, ...
{{double(sliceImage), mask}, getappdata(handles.figure_vi, 'regionType'), handles.figure_vi});
end
% -------------------------------------------------------------------
function update_region_data(handles)
posRegion = getappdata(handles.figure_vi, 'posRegion');
if isempty(posRegion)
return;
end
x1 = posRegion(1);
x2 = posRegion(2);
y1 = posRegion(3);
y2 = posRegion(4);
hDrawRegion = getappdata(handles.figure_vi, 'hDrawRegion');
viewSize = getappdata(handles.figure_vi, 'sliceSize');
rectX = min(x1, x2);
rectY = min(viewSize(1) - [y1 y2]) + 1;
rectWidth = range([x1, x2]);
rectHeight = range([y1, y2]);
if rectWidth > 0 && rectHeight > 0
if is_handle(hDrawRegion)
set(hDrawRegion, 'Position', [rectX, rectY, rectWidth, rectHeight]);
else
if strcmpi('Rectangle', getappdata(handles.figure_vi, 'regionType'))
curvature = [0 0];
else
curvature = [1 1];
end
hDrawRegion = rectangle( ...
'Position', [rectX, rectY, rectWidth, rectHeight], ...
'Parent', handles.axes_2dViewer, ...
'EdgeColor', 'r', ...
'Curvature', curvature);
setappdata(handles.figure_vi, 'hDrawRegion', hDrawRegion);
end
end
sliceImage = getappdata(handles.figure_vi, 'sliceImage');
hFigRegionMeasurement = getappdata(handles.figure_vi, 'hFigRegionMeasurement');
if is_handle(hFigRegionMeasurement)
feval(getappdata(hFigRegionMeasurement, 'entry_update_data'), ...
hFigRegionMeasurement, ...
{sliceImage(min(y1, y2) : max(y1, y2), min(x1, x2) : max(x1, x2)), ...
getappdata(handles.figure_vi, 'regionType'), handles.figure_vi});
end
% -------------------------------------------------------------------
function update_line_data(handles)
posLine = getappdata(handles.figure_vi, 'posLine');
if isempty(posLine)
return;
end
x1 = posLine(1);
x2 = posLine(2);
y1 = posLine(3);
y2 = posLine(4);
lineLen = ceil(sqrt((x1 - x2) ^ 2 + (y1 - y2) ^ 2));
if lineLen < 2
return;
end
hDrawLine = getappdata(handles.figure_vi, 'hDrawLine');
viewSize = getappdata(handles.figure_vi, 'sliceSize');
if is_handle(hDrawLine)
set(hDrawLine, ...
'XData', [x1 x2], ...
'YData', viewSize(1) - [y1 y2] + 1);
else
hDrawLine = line( ...
[x1 x2], viewSize(1) - [y1 y2] + 1, ...
'Parent', handles.axes_2dViewer, ...
'Color', 'r');
setappdata(handles.figure_vi, 'hDrawLine', hDrawLine);
end
sliceImage = getappdata(handles.figure_vi, 'sliceImage');
viewSize = getappdata(handles.figure_vi, 'sliceSize');
if ~isfloat(sliceImage)
sliceImage = double(sliceImage);
end
[cx, cy, c] = improfile(sliceImage, [x1 x2], [y1 y2], lineLen);
hFigLineMeasurement = getappdata(handles.figure_vi, 'hFigLineMeasurement');
if is_handle(hFigLineMeasurement)
feval(getappdata(hFigLineMeasurement, 'entry_update_data'), ...
hFigLineMeasurement, {[c cx cy], [1 viewSize(2) 1 viewSize(1)], handles.figure_vi});
end
% -------------------------------------------------------------------
function [pt, nPlane] = pick_3d_point(handles)
assert(4 == get_view_type(handles));
ptOnAxesCurrent = round(get(handles.axes_3dSlicer, 'CurrentPoint'));
hSlices = getappdata(handles.figure_vi, 'hSlices');
xdata = get(hSlices(1), 'XData');
ydata = get(hSlices(2), 'YData');
zdata = get(hSlices(3), 'ZData');
ptPos = zeros(3, 3);
ptPos(1, 1) = xdata(1);
ptPos(1, 2) = interp1nosort(ptOnAxesCurrent(:, 1), ptOnAxesCurrent(:, 2), xdata(1));
ptPos(1, 3) = interp1nosort(ptOnAxesCurrent(:, 1), ptOnAxesCurrent(:, 3), xdata(1));
ptPos(2, 1) = interp1nosort(ptOnAxesCurrent(:, 2), ptOnAxesCurrent(:, 1), ydata(1));
ptPos(2, 2) = ydata(1);
ptPos(2, 3) = interp1nosort(ptOnAxesCurrent(:, 2), ptOnAxesCurrent(:, 3), ydata(1));
ptPos(3, 1) = interp1nosort(ptOnAxesCurrent(:, 3), ptOnAxesCurrent(:, 1), zdata(1));
ptPos(3, 2) = interp1nosort(ptOnAxesCurrent(:, 3), ptOnAxesCurrent(:, 2), zdata(1));
ptPos(3, 3) = zdata(1);
ptPos = round(ptPos);
d2 = zeros(3, 1);
if any(isnan(ptPos(1, :)))
d2(1) = inf;
else
d2(1) = sum((ptOnAxesCurrent(1, :) - ptPos(1, :)) .^ 2);
end
if any(isnan(ptPos(2, :)))
d2(2) = inf;
else
d2(2) = sum((ptOnAxesCurrent(1, :) - ptPos(2, :)) .^ 2);
end
if any(isnan(ptPos(3, :)))
d2(3) = inf;
else
d2(3) = sum((ptOnAxesCurrent(1, :) - ptPos(3, :)) .^ 2);
end
if ~all(isinf(d2))
[~, nPlane] = min(d2);
pt = ptPos(nPlane, :);
else
nPlane = 0;
pt = [];
end
% --- Outputs from this function are returned to the command line.
function varargout = vi_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 mouse motion over figure - except title and menu.
function figure_vi_WindowButtonMotionFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
[ptOnAxesCurrent, onImage] = get_pointer_pos(handles);
is2d = 4 ~= get_view_type(handles);
cursorType = get(handles.figure_vi, 'Pointer');
if is2d && onImage && ~strcmpi(cursorType, 'cross')
set(handles.figure_vi, 'Pointer', 'crosshair');
elseif ~onImage && ~strcmpi(cursorType, 'arrow')
set(handles.figure_vi, 'Pointer', 'arrow');
end
if ~onImage
set(handles.text_pixelInfo, 'String', '');
set(handles.text_voxelInfo, 'String', '');
return;
end
buttonDown = getappdata(handles.figure_vi, 'buttonDown');
selectionType = get(handles.figure_vi, 'SelectionType');
leftButtonDown = buttonDown && strcmpi(selectionType, 'normal');
rightButtonDown = buttonDown && strcmpi(selectionType, 'alt');
ptOnAxesBtnDown = getappdata(handles.figure_vi, 'ptOnAxesBtnDown');
dataFormat = getappdata(handles.figure_vi, 'dataFormat');
if is2d
sliceImage = getappdata(handles.figure_vi, 'sliceImage');
set(handles.text_pixelInfo, 'String', ...
['(' num2str(round(ptOnAxesCurrent(1))) ', ' num2str(round(ptOnAxesCurrent(2))) ') '...
num2str(sliceImage(ptOnAxesCurrent(2), ptOnAxesCurrent(1)), dataFormat)]);
else
[pt, nPlane] = pick_3d_point(handles);
if 0 == nPlane
set(handles.text_voxelInfo, 'String', '');
else
hSlices = getappdata(handles.figure_vi, 'hSlices');
sliceImage = get(hSlices(nPlane), 'CData');
if 1 == nPlane
v = sliceImage(pt(2), pt(3));
elseif 2 == nPlane
v = sliceImage(pt(1), pt(3));
elseif 3 == nPlane
v = sliceImage(pt(2), pt(1));
end
set(handles.text_voxelInfo, 'String', ...
['(' num2str(pt(1)) ', ' num2str(pt(2)) ', ' num2str(pt(3)) ') '...
num2str(v, dataFormat)]);
end
end
ptOnFigCurrent = get(handles.figure_vi, 'CurrentPoint');
if buttonDown
ptOnFigBtnDown = getappdata(handles.figure_vi, 'ptOnFigBtnDown');
ptShift = ptOnFigCurrent - ptOnFigBtnDown;
end
measuringLine = 1 == get(handles.togglebutton_lineMeasure, 'Value');
measuringRegion = 1 == get(handles.togglebutton_regionMeasure, 'Value');
if leftButtonDown && ~measuringLine && ~measuringRegion % Change window.
% Move mouse down to INCREASE level to DECREASE the brightness.
% Move mouse left and right to change width.
referenceCLim = getappdata(handles.figure_vi, 'referenceCLim');
windowLevel = mean(referenceCLim);
windowWidth = range(referenceCLim);
windowLevel = windowLevel - windowWidth * ptShift(2) / 1000;
windowWidth = max(eps('single'), windowWidth + windowWidth * ptShift(1) / 500);
windowMax = windowLevel + windowWidth / 2;
windowMin = windowLevel - windowWidth / 2;
set_clims(handles, windowMin, windowMax);
update_window_info(handles);
elseif is2d && leftButtonDown && measuringLine && ~measuringRegion % Line measurement.
setappdata(handles.figure_vi, 'posLine', ...
[ptOnAxesBtnDown(1), ptOnAxesCurrent(1), ptOnAxesBtnDown(2), ptOnAxesCurrent(2)]);
update_line_data(handles);
elseif is2d && leftButtonDown && ~measuringLine && measuringRegion % Region measurement.
if strcmpi('Drawn', getappdata(handles.figure_vi, 'regionType'))
userDrawRegionVertices = getappdata(handles.figure_vi, 'userDrawRegionVertices');
assert(~isempty(userDrawRegionVertices));
userDrawRegionVertices = [userDrawRegionVertices; ptOnAxesCurrent];
setappdata(handles.figure_vi, 'userDrawRegionVertices', userDrawRegionVertices);
update_user_drawn_region_data(handles);
else
setappdata(handles.figure_vi, ...
'posRegion', [ptOnAxesBtnDown(1), ptOnAxesCurrent(1), ptOnAxesBtnDown(2), ptOnAxesCurrent(2)]);
update_region_data(handles);
end
elseif ~is2d && 1 == get(handles.togglebutton_rotate, 'Value')
hLight = getappdata(handles.figure_vi, 'hLight');
set(hLight, 'Position', get(handles.axes_3dSlicer, 'CameraPosition'));
elseif ~is2d && rightButtonDown
referenceNPlane = getappdata(handles.figure_vi, 'referenceNPlane');
referenceSliceNo3d = getappdata(handles.figure_vi, 'referenceSliceNo3d');
if referenceNPlane == 1
update_slice_3d(handles, referenceSliceNo3d(1) + ptShift(2), referenceSliceNo3d(2), referenceSliceNo3d(3), false);
elseif referenceNPlane == 2
update_slice_3d(handles, referenceSliceNo3d(1), referenceSliceNo3d(2) + ptShift(2), referenceSliceNo3d(3), false);
elseif referenceNPlane == 3
update_slice_3d(handles, referenceSliceNo3d(1), referenceSliceNo3d(2), referenceSliceNo3d(3) + ptShift(2), false);
else
end
end
% --- Executes on scroll wheel click while the figure is in focus.
function figure_vi_WindowScrollWheelFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata structure with the following fields (see FIGURE)
% VerticalScrollCount: signed integer indicating direction and number of clicks
% VerticalScrollAmount: number of lines scrolled for each click
% handles structure with handles and user data (see GUIDATA)
if 4 == get_view_type(handles)
return;
end
[~, onImage] = get_pointer_pos(handles);
if ~onImage
return;
end
numSlices = getappdata(handles.figure_vi, 'numSlices');
sliceNo = getappdata(handles.figure_vi, 'sliceNo');
sliceNo = sliceNo - eventdata.VerticalScrollCount(1);
sliceNo = max(min(sliceNo, numSlices), 1);
setappdata(handles.figure_vi, 'sliceNo', sliceNo);
set(handles.edit_sliceNo, 'String', num2str(sliceNo));
update_slice_2d(handles, sliceNo, false);
function edit_windowMax_Callback(hObject, eventdata, handles)
% hObject handle to edit_windowMax (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_windowMax as text
% str2double(get(hObject,'String')) returns contents of edit_windowMax as a double
cLim = get(handles.axes_2dViewer, 'CLim');
windowMin = cLim(1);
windowMax = str2double(get(hObject,'String'));
if windowMax < windowMin
windowMax = windowMin;
end
set_clims(handles, windowMin, windowMax);
update_window_info(handles);
% --- Executes during object creation, after setting all properties.
function edit_windowMax_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_windowMax (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_windowMin_Callback(hObject, eventdata, handles)
% hObject handle to edit_windowMin (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_windowMin as text
% str2double(get(hObject,'String')) returns contents of edit_windowMin as a double
cLim = get(handles.axes_2dViewer, 'CLim');
windowMax = cLim(2);
windowMin = str2double(get(hObject,'String'));
if windowMin > windowMax
windowMin = windowMax;
end
set_clims(handles, windowMin, windowMax);
update_window_info(handles);
% --- Executes during object creation, after setting all properties.
function edit_windowMin_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_windowMin (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_windowWidth_Callback(hObject, eventdata, handles)
% hObject handle to edit_windowWidth (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_windowWidth as text
% str2double(get(hObject,'String')) returns contents of edit_windowWidth as a double
windowWidth = str2double(get(hObject,'String'));
if windowWidth < 1
windowWidth = 1;
end
cLim = get(handles.axes_2dViewer, 'CLim');
windowLevel = mean(cLim);
windowMax = windowLevel + windowWidth / 2;
windowMin = windowLevel - windowWidth / 2;
set_clims(handles, windowMin, windowMax);
update_window_info(handles);
% --- Executes during object creation, after setting all properties.
function edit_windowWidth_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_windowWidth (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_windowLevel_Callback(hObject, eventdata, handles)
% hObject handle to edit_windowLevel (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_windowLevel as text
% str2double(get(hObject,'String')) returns contents of edit_windowLevel as a double
windowLevel = str2double(get(hObject,'String'));
cLim = get(handles.axes_2dViewer, 'CLim');
windowWidth = range(cLim);
windowMax = windowLevel + windowWidth / 2;
windowMin = windowLevel - windowWidth / 2;
set_clims(handles, windowMin, windowMax);
update_window_info(handles);
% --- Executes during object creation, after setting all properties.
function edit_windowLevel_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_windowLevel (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_sliceNo_Callback(hObject, eventdata, handles)
% hObject handle to edit_sliceNo (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_sliceNo as text
% str2double(get(hObject,'String')) returns contents of edit_sliceNo as a double
update_slice_2d(handles, round(str2double(get(hObject,'String'))), false);
% --- Executes during object creation, after setting all properties.
function edit_sliceNo_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_sliceNo (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
% --- Executes on slider movement.
function slider_sliceNo_Callback(hObject, eventdata, handles)
% hObject handle to slider_sliceNo (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
update_slice_2d(handles, get(hObject, 'Value'), false);
% --- Executes during object creation, after setting all properties.
function slider_sliceNo_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider_sliceNo (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 when selected object is changed in uipanel_viewType.
function uipanel_viewType_SelectionChangeFcn(hObject, eventdata, handles)
% hObject handle to the selected object in uipanel_viewType
% eventdata structure with the following fields (see UIBUTTONGROUP)
% EventName: string 'SelectionChanged' (read only)
% OldValue: handle of the previously selected object or empty if none was selected
% NewValue: handle of the currently selected object
% handles structure with handles and user data (see GUIDATA)
update_view_type(handles);
auto_layout(handles);
% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure_vi_WindowButtonDownFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
setappdata(handles.figure_vi, 'buttonDown', true);
setappdata(handles.figure_vi, 'ptOnFigBtnDown', get(handles.figure_vi, 'CurrentPoint'));
[ptOnAxesCurrent, onImage] = get_pointer_pos(handles);
if ~onImage
return;
end
setappdata(handles.figure_vi, 'ptOnAxesBtnDown', ptOnAxesCurrent);
selectionType = get(handles.figure_vi, 'SelectionType');
if strcmpi(selectionType, 'normal')
hDrawRegion = getappdata(handles.figure_vi, 'hDrawRegion');
if is_handle(hDrawRegion)
delete(hDrawRegion);
setappdata(handles.figure_vi, 'hDrawRegion', []);
end
hDrawLine = getappdata(handles.figure_vi, 'hDrawLine');
if is_handle(hDrawLine)
delete(hDrawLine);
setappdata(handles.figure_vi, 'hDrawLine', []);
end
hDrawRegion = getappdata(handles.figure_vi, 'hDrawRegion');
if ishandle(hDrawRegion)
delete(hDrawRegion);
setappdata(handles.figure_vi, 'hDrawRegion', []);
end
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
if ishandle(hDrawRegionAdd)
delete(hDrawRegionAdd);
setappdata(handles.figure_vi, 'hDrawRegionAdd', []);
end
cLim = get(handles.axes_2dViewer, 'CLim');
setappdata(handles.figure_vi, 'referenceCLim', cLim);
if strcmpi('Drawn', getappdata(handles.figure_vi, 'regionType')) ...
&& 1 == get(handles.togglebutton_regionMeasure, 'Value')
setappdata(handles.figure_vi, 'userDrawRegionVertices', ptOnAxesCurrent);
end
elseif strcmpi(selectionType, 'alt')
[~, nPlane] = pick_3d_point(handles);
setappdata(handles.figure_vi, 'referenceNPlane', nPlane);
sliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
setappdata(handles.figure_vi, 'referenceSliceNo3d', sliceNo3d);
end
% --- Executes on mouse press over figure background, over a disabled or
% --- inactive control, or over an axes background.
function figure_vi_WindowButtonUpFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
setappdata(handles.figure_vi, 'buttonDown', false);
hDrawRegionAdd = getappdata(handles.figure_vi, 'hDrawRegionAdd');
if is_handle(hDrawRegionAdd) && strcmpi('on', get(hDrawRegionAdd, 'Visible'))
set(hDrawRegionAdd, 'LineStyle', '-', 'Color', 'r');
end
function edit_zAspectRatio_Callback(hObject, eventdata, handles)
% hObject handle to edit_zAspectRatio (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_zAspectRatio as text
% str2double(get(hObject,'String')) returns contents of edit_zAspectRatio as a double
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
aspectRatio(3) = str2double(get(hObject, 'String'));
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
% --- Executes during object creation, after setting all properties.
function edit_zAspectRatio_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_zAspectRatio (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_yAspectRatio_Callback(hObject, eventdata, handles)
% hObject handle to edit_yAspectRatio (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_yAspectRatio as text
% str2double(get(hObject,'String')) returns contents of edit_yAspectRatio as a double
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
aspectRatio(2) = str2double(get(hObject, 'String'));
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
% --- Executes during object creation, after setting all properties.
function edit_yAspectRatio_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_yAspectRatio (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_xAspectRatio_Callback(hObject, eventdata, handles)
% hObject handle to edit_xAspectRatio (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_xAspectRatio as text
% str2double(get(hObject,'String')) returns contents of edit_xAspectRatio as a double
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
aspectRatio(1) = str2double(get(hObject, 'String'));
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
% --- Executes during object creation, after setting all properties.
function edit_xAspectRatio_CreateFcn(hObject, eventdata, handles)
% hObject handle to edit_xAspectRatio (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
% --- Executes on button press in pushbutton_resetAspectRatio.
function pushbutton_resetAspectRatio_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_resetAspectRatio (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
aspectRatio = [1 1 1];
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
% --- Executes on button press in pushbutton_moreWindows.
function pushbutton_moreWindows_Callback(hObject, eventdata, handles)
% hObject handle to pushbutton_moreWindows (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
uiMenus = getappdata(handles.figure_vi, 'uiMenus');
pos1 = get(handles.pushbutton_moreWindows, 'Position');
pos2 = get(handles.uipanel_windowSetting, 'Position');
pos3 = get(handles.uipanel_leftControls, 'Position');
set(uiMenus.menu_moreWindowSettings, 'Position', pos1(1:2)+pos2(1:2)+pos3(1:2), 'Visible', 'on');
% --- Executes on key press with focus on figure_vi and none of its controls.
function figure_vi_KeyPressFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata structure with the following fields (see FIGURE)
% 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)
if strcmpi(eventdata.Character, '+')
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
if isempty(eventdata.Modifier)
aspectRatio = aspectRatio * 1.1;
elseif strcmpi(eventdata.Modifier{1}, 'control')
aspectRatio = aspectRatio * 1.5;
end
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
elseif strcmpi(eventdata.Character, '-')
aspectRatio = getappdata(handles.figure_vi, 'aspectRatio');
if isempty(eventdata.Modifier)
aspectRatio = aspectRatio / 1.1;
elseif strcmpi(eventdata.Modifier{1}, 'control')
aspectRatio = aspectRatio / 1.5;
end
if all(aspectRatio > 0.2)
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
end
elseif strcmpi(eventdata.Character, '*')
aspectRatio = [1 1 1];
setappdata(handles.figure_vi, 'aspectRatio', aspectRatio);
update_aspect_ratio(handles);
auto_layout(handles);
else
end
% --- Executes on selection change in listbox_colorMaps.
function listbox_colorMaps_Callback(hObject, eventdata, handles)
% hObject handle to listbox_colorMaps (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hints: contents = cellstr(get(hObject,'String')) returns listbox_colorMaps contents as cell array
% contents{get(hObject,'Value')} returns selected item from listbox_colorMaps
set_colormap(handles);
% --- Executes during object creation, after setting all properties.
function listbox_colorMaps_CreateFcn(hObject, eventdata, handles)
% hObject handle to listbox_colorMaps (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles empty - handles not created until after all CreateFcns called
% Hint: listbox 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
% --- Executes on slider movement.
function slider_xSliceNo_Callback(hObject, eventdata, handles)
% hObject handle to slider_xSliceNo (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
sliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
update_slice_3d(handles, get(hObject, 'Value'), sliceNo3d(2), sliceNo3d(3), false);
% --- Executes during object creation, after setting all properties.
function slider_xSliceNo_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider_xSliceNo (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_ySliceNo_Callback(hObject, eventdata, handles)
% hObject handle to slider_ySliceNo (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
sliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
update_slice_3d(handles, sliceNo3d(1), get(hObject, 'Value'), sliceNo3d(3), false);
% --- Executes during object creation, after setting all properties.
function slider_ySliceNo_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider_ySliceNo (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_zSliceNo_Callback(hObject, eventdata, handles)
% hObject handle to slider_zSliceNo (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
sliceNo3d = getappdata(handles.figure_vi, 'sliceNo3d');
update_slice_3d(handles, sliceNo3d(1), sliceNo3d(2), get(hObject, 'Value'), false);
% --- Executes during object creation, after setting all properties.
function slider_zSliceNo_CreateFcn(hObject, eventdata, handles)
% hObject handle to slider_zSliceNo (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
% --------------------------------------------------------------------
function mi_windowPelvis_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowPelvis (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -160, 240);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowBone_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowBone (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -750, 1750);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowBreast_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowBreast (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -250, 150);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowAbdomen_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowAbdomen (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -125, 225);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowLung_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowLung (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -1000, 250);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowLiver_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowLiver (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -25, 125);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowCerebellum_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowCerebellum (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -20, 100);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowReset_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowReset (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
img = getappdata(handles.figure_vi, 'imgData');
maxPixelVal = max(img(:));
minPixelVal = min(img(:));
set_clims(handles, minPixelVal, maxPixelVal);
update_window_info(handles);
% --------------------------------------------------------------------
function menu_moreWindowSettings_Callback(hObject, eventdata, handles)
% hObject handle to menu_moreWindowSettings (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --------------------------------------------------------------------
function mi_windowCustom1_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowCustom1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -1000, 1000);
update_window_info(handles);
% --------------------------------------------------------------------
function mi_windowCustom2_Callback(hObject, eventdata, handles)
% hObject handle to mi_windowCustom2 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
set_clims(handles, -1500, 1500);
update_window_info(handles);
% --- Executes on button press in togglebutton_rotate.
function togglebutton_rotate_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton_rotate (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton_rotate
check_rotate(handles);
% --- Executes on button press in togglebutton_light.
function togglebutton_light_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton_light (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton_light
set_light(handles);
% --- Executes on button press in togglebutton_sliceStats.
function togglebutton_sliceStats_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton_sliceStats (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton_sliceStats
if 1 == get(hObject, 'Value')
set([ ...
handles.togglebutton_regionMeasure, ...
handles.togglebutton_lineMeasure, ...
handles.togglebutton_isoline], 'Value', 0);
set_region_measure(handles, 0);
set_line_measure(handles, 0);
set_isoline(handles, 0);
set_image_stats(handles, 1);
else
set_image_stats(handles, 0);
end
% --- Executes on button press in togglebutton_regionMeasure.
function togglebutton_regionMeasure_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton_regionMeasure (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton_regionMeasure
if 1 == get(hObject, 'Value')
set([ ...
handles.togglebutton_sliceStats, ...
handles.togglebutton_lineMeasure, ...
handles.togglebutton_isoline], 'Value', 0);
set_image_stats(handles, 0);
set_line_measure(handles, 0);
set_isoline(handles, 0);
set_region_measure(handles, 1);
else
set_region_measure(handles, 0);
end
% --- Executes on button press in togglebutton_lineMeasure.
function togglebutton_lineMeasure_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton_lineMeasure (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton_lineMeasure
if 1 == get(hObject, 'Value')
set([ ...
handles.togglebutton_sliceStats, ...
handles.togglebutton_regionMeasure, ...
handles.togglebutton_isoline], 'Value', 0);
set_image_stats(handles, 0);
set_region_measure(handles, 0);
set_isoline(handles, 0);
set_line_measure(handles, 1);
else
set_line_measure(handles, 0);
end
% --- Executes on button press in togglebutton_isoline.
function togglebutton_isoline_Callback(hObject, eventdata, handles)
% hObject handle to togglebutton_isoline (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of togglebutton_isoline
if 1 == get(hObject, 'Value')
set([ ...
handles.togglebutton_sliceStats, ...
handles.togglebutton_regionMeasure, ...
handles.togglebutton_lineMeasure], 'Value', 0);
set_image_stats(handles, 0);
set_region_measure(handles, 0);
set_line_measure(handles, 0);
set_isoline(handles, 1);
else
set_isoline(handles, 0);
end
% --- Executes when figure_vi is resized.
function figure_vi_ResizeFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
auto_layout(handles);
% --- Executes when user attempts to close figure_vi.
function figure_vi_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure_vi (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hFigSliceStats = getappdata(handles.figure_vi, 'hFigSliceStats');
if is_handle(hFigSliceStats)
delete(hFigSliceStats);
setappdata(handles.figure_vi, 'hFigSliceStats', []);
end
hFigRegionMeasurement = getappdata(handles.figure_vi, 'hFigRegionMeasurement');
if is_handle(hFigRegionMeasurement)
delete(hFigRegionMeasurement);
setappdata(handles.figure_vi, 'hFigRegionMeasurement', []);
end
hFigLineMeasurement = getappdata(handles.figure_vi, 'hFigLineMeasurement');
if is_handle(hFigLineMeasurement)
delete(hFigLineMeasurement);
setappdata(handles.figure_vi, 'hFigLineMeasurement', []);
end
hFigIsoline = getappdata(handles.figure_vi, 'hFigIsoline');
if is_handle(hFigIsoline)
delete(hFigIsoline);
setappdata(handles.figure_vi, 'hFigIsoline', []);
end
delete(hObject);
% --------------------------------------------------------------------
function mi_regionRect_Callback(hObject, eventdata, handles)
% hObject handle to mi_regionRect (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
select_region_type(handles, 'Rectangle');
% --------------------------------------------------------------------
function mi_regionDisc_Callback(hObject, eventdata, handles)
% hObject handle to mi_regionDisc (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
select_region_type(handles, 'Disc');
% -------------------------------------------------------------------
function select_region_type(handles, regionType)
uiMenus = getappdata(handles.figure_vi, 'uiMenus');
menuItems = get(uiMenus.menu_selectRegionType, 'Children');
for i = 1 : length(menuItems)
mi = menuItems(i);
miLabel = get(mi, 'Label');
if strcmpi(regionType, miLabel) || strcmpi(regionType, 'Drawn') && strcmpi(miLabel, 'User Drawn')
set(mi, 'Checked', 'on');
setappdata(handles.figure_vi, 'regionType', regionType);
else
set(mi, 'Checked', 'off');
end
end
% --------------------------------------------------------------------
function menu_selectRegionType_Callback(hObject, eventdata, handles)
% hObject handle to menu_selectRegionType (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% --- If Enable == 'on', executes on mouse press in 5 pixel border.
% --- Otherwise, executes on mouse press in 5 pixel border or over togglebutton_regionMeasure.
function togglebutton_regionMeasure_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to togglebutton_regionMeasure (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
uiMenus = getappdata(handles.figure_vi, 'uiMenus');
pos1 = get(handles.togglebutton_regionMeasure, 'Position');
pos2 = get(handles.uipanel_2dControls, 'Position');
pos3 = get(handles.uipanel_2dViewer, 'Position');
set(uiMenus.menu_selectRegionType, 'Position', pos1(1:2)+pos2(1:2)+pos3(1:2), 'Visible', 'on');
% --------------------------------------------------------------------
function mi_regionDrawn_Callback(hObject, eventdata, handles)
% hObject handle to mi_regionDrawn (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
select_region_type(handles, 'Drawn');
|
github
|
jacksky64/imageProcessing-master
|
line_measurement.m
|
.m
|
imageProcessing-master/3dViewer/line_measurement.m
| 15,958 |
utf_8
|
9c31465f555fe9cfba04eb2e0626fca9
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright:
% Jun Tan
% University of Texas Southwestern Medical Center
% Department of Radiation Oncology
% Last edited: 08/19/2014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = line_measurement(varargin)
% LINE_MEASUREMENT MATLAB code for line_measurement.fig
% LINE_MEASUREMENT, by itself, creates a new LINE_MEASUREMENT or raises the existing
% singleton*.
%
% H = LINE_MEASUREMENT returns the handle to a new LINE_MEASUREMENT or the handle to
% the existing singleton*.
%
% LINE_MEASUREMENT('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in LINE_MEASUREMENT.M with the given input arguments.
%
% LINE_MEASUREMENT('Property','Value',...) creates a new LINE_MEASUREMENT or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before line_measurement_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to line_measurement_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 line_measurement
% Last Modified by GUIDE v2.5 16-Aug-2014 00:56:14
% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @line_measurement_OpeningFcn, ...
'gui_OutputFcn', @line_measurement_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 line_measurement is made visible.
function line_measurement_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 line_measurement (see VARARGIN)
% Choose default command line output for line_measurement
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
parse_args(hObject, varargin);
setappdata(hObject, 'entry_update_data', @parse_args);
set(hObject, 'Visible', getappdata(hObject, 'initialVisible'));
% -------------------------------------------------------------------
function parse_args(hFig, args)
handles = guidata(hFig);
numArgs = length(args);
assert(1 == numArgs || 2 == numArgs || 3 == numArgs, 'Must have 1, 2, or 3 arguments');
setappdata(handles.figure_lp, 'xyLims', []);
setappdata(handles.figure_lp, 'mainFigHandle', []);
setappdata(handles.figure_lp, 'initialVisible', 'on');
if 1 == numArgs
if is_handle(args{1})
setappdata(handles.figure_lp, 'mainFigHandle', args{1});
setappdata(handles.figure_lp, 'initialVisible', 'off');
else
parse_line_data(handles, args{1});
end
elseif 2 == numArgs
parse_line_data(handles, args{1})
if is_handle(args{2})
setappdata(handles.figure_lp, 'mainFigHandle', args{2});
else
parse_lim_data(handles, args{2});
end
else % if 3 == numArgs
parse_line_data(handles, args{1})
parse_lim_data(handles, args{2});
assert(is_handle(args{3}), 'The third argument must be a valid GUI handle.');
setappdata(handles.figure_lp, 'mainFigHandle', args{3});
end
hSel = getappdata(handles.figure_lp, 'hSelectedPoint');
if ~isempty(hSel)
delete(hSel);
setappdata(handles.figure_lp, 'hSelectedPoint', []);
end
update_measurement(handles);
% -------------------------------------------------------------------
function parse_line_data(handles, lineData)
% lineData: Each row is 1 point. First number is value.
% lineType:
% 1: coordinate is row number.
% 2: coordinate is 1D (x).
% 3: coordinate is 2D (x, y).
assert(isnumeric(lineData) || islogical(lineData), 'Data type must be numeric or logical.');
pointValues = lineData(:, 1);
pointPos = lineData(:, 2:end);
numPoints = numel(pointValues);
assert(numPoints > 1, 'Must have at least 2 points.');
numPosDims = size(pointPos, 2);
assert(numPosDims <= 2, 'Dimenson ust be 1D or 2D.');
if 0 == numPosDims
pointPos = (1 : numPoints)';
lineType = 1;
elseif 1 == numPosDims
lineType = 1;
else
lineType = 2;
end
assert(2 == lineType || 1 == lineType && all(diff(pointPos) > 0), ...
'Coordinates must be monotonically increasing.');
setappdata(handles.figure_lp, 'lineType', lineType);
setappdata(handles.figure_lp, 'pointValues', pointValues);
setappdata(handles.figure_lp, 'pointPos', pointPos);
get_data_format(handles, pointValues, pointPos);
% -------------------------------------------------------------------
function parse_lim_data(handles, xyLims)
assert(isnumeric(xyLims), 'Coordinate limits must be numeric.');
assert(4 == numel(xyLims) && numel(xyLims) == length(xyLims) ...
&& xyLims(2) > xyLims(1) && xyLims(4) > xyLims(3), ...
'X and Y lims must be [xLower xUpper yLower yUpper] for .');
setappdata(handles.figure_lp, 'xyLims', xyLims);
% -------------------------------------------------------------------
function get_data_format(handles, pointValues, pointPos)
if all(0 == rem(pointValues, 1))
valueFormat = '%.0f';
valueMaxExp = 0;
else
[valueFormat, valueMaxExp] = find_float_text_format(max(abs(pointValues(:))));
end
if all(0 == rem(pointPos(:), 1))
posFormat = '%.0f';
posMaxExp = 0;
else
[posFormat, posMaxExp] = find_float_text_format(max(abs(pointPos(:))));
end
setappdata(handles.figure_lp, 'valueFormat', valueFormat);
setappdata(handles.figure_lp, 'valueMaxExp', valueMaxExp);
setappdata(handles.figure_lp, 'posFormat', posFormat);
setappdata(handles.figure_lp, 'posMaxExp', posMaxExp);
% -------------------------------------------------------------------
function [fmt, maxExp] = find_float_text_format(v)
v = abs(v); % Force v to be >= 0, though not always necessary.
if v >= 1e3 || v <= 0
fmt = '%.3e';
maxExp = floor(log10(v));
elseif v >= 1e2
fmt = '%.1f';
maxExp = 0;
elseif v >= 1e1
fmt = '%.2f';
maxExp = 0;
else
fmt = '%.3f';
maxExp = 0;
end
% -------------------------------------------------------------------
function s = format_float(v, fmt, maxExp)
if fmt(end) == 'e'
v = v / (10 ^ maxExp);
s = [sprintf('%.3f', v) 'e+03'];
else
s = sprintf(fmt, v);
end
if '-' ~= s(1)
s = [' ' s];
end
% -------------------------------------------------------------------
function update_measurement(handles)
stats = cell(6, 2);
stats{1, 1} = ' #Points';
stats{2, 1} = ' Length';
stats{3, 1} = ' Max';
stats{4, 1} = ' Min';
stats{5, 1} = ' Mean';
stats{6, 1} = ' SD';
pointValues = getappdata(handles.figure_lp, 'pointValues');
stats{1, 2} = length(pointValues);
if stats{1, 2} > 0
stats{3, 2} = max(pointValues);
stats{4, 2} = min(pointValues);
if ~isempty(pointValues)
stats{5, 2} = mean(pointValues);
end
if ~isempty(pointValues)
stats{6, 2} = std(pointValues);
end
pointPos = getappdata(handles.figure_lp, 'pointPos');
if 1 == getappdata(handles.figure_lp, 'lineType')
set(handles.checkbox_stretch, 'Visible', 'off');
stats{2, 2} = range(pointPos);
update_2d_profile(handles);
else % if 2 == lineType
set(handles.checkbox_stretch, 'Visible', 'on');
numSegments = length(pointPos) - 1;
segmentLength = zeros(1, numSegments);
for i = 1 : numSegments
segmentLength(i) = pdist2(pointPos(i, :), pointPos(i+1, :));
end
stats{2, 2} = sum(segmentLength);
setappdata(handles.figure_lp, 'segmentLength', segmentLength);
update_3d_profile(handles);
end
valueFormat = getappdata(handles.figure_lp, 'valueFormat');
valueMaxExp = getappdata(handles.figure_lp, 'valueMaxExp');
valueText = arrayfun(@(x)format_float(x, valueFormat, valueMaxExp), ...
pointValues, 'UniformOutput', false);
posFormat = getappdata(handles.figure_lp, 'posFormat');
posMaxExp = getappdata(handles.figure_lp, 'posMaxExp');
posText = arrayfun(@(x)format_float(x, posFormat, posMaxExp), ...
pointPos, 'UniformOutput', false);
set(handles.uitable_points, 'Data', [valueText posText]);
end
set(handles.uitable_stats, 'Data', stats);
check_grid(handles);
check_marker(handles);
% -------------------------------------------------------------------
function update_2d_profile(handles)
pointValues = getappdata(handles.figure_lp, 'pointValues');
pointPos = getappdata(handles.figure_lp, 'pointPos');
h = plot(handles.axes_lineProfile, pointPos, pointValues, 'linewidth', 2);
setappdata(handles.figure_lp, 'hProfile', h);
rotate3d(handles.axes_lineProfile, 'off');
box(handles.axes_lineProfile, 'off');
xlabel(handles.axes_lineProfile, 'x');
ylabel(handles.axes_lineProfile, 'Value');
setappdata(handles.figure_lp, 'segmentLength', []);
set(handles.uitable_points, 'ColumnName', {'Value', 'x'});
set(handles.uitable_points, 'ColumnWidth', {65, 40});
% -------------------------------------------------------------------
function update_3d_profile(handles)
pointValues = getappdata(handles.figure_lp, 'pointValues');
pointPos = getappdata(handles.figure_lp, 'pointPos');
if isempty(pointValues) || isempty(pointPos)
return;
end
if 1 == get(handles.checkbox_stretch, 'Value')
segmentLength = getappdata(handles.figure_lp, 'segmentLength');
h = plot(handles.axes_lineProfile, [0 cumsum(segmentLength)], pointValues, 'linewidth', 1);
setappdata(handles.figure_lp, 'hProfile', h);
rotate3d(handles.axes_lineProfile, 'off');
box(handles.axes_lineProfile, 'off');
xlabel(handles.axes_lineProfile, 'Cumulative distance from first point');
ylabel(handles.axes_lineProfile, 'Value');
else
h = plot3(handles.axes_lineProfile, pointPos(:, 1), pointPos(:, 2), pointValues, 'linewidth', 1);
setappdata(handles.figure_lp, 'hProfile', h);
rotate3d(handles.axes_lineProfile, 'on');
xyLims = getappdata(handles.figure_lp, 'xyLims');
if isempty(xyLims)
xlim(handles.axes_lineProfile, 'auto');
ylim(handles.axes_lineProfile, 'auto');
else
xlim(handles.axes_lineProfile, xyLims(1:2));
ylim(handles.axes_lineProfile, xyLims(3:4));
end
box(handles.axes_lineProfile, 'off');
xlabel(handles.axes_lineProfile, 'x');
ylabel(handles.axes_lineProfile, 'y');
zlabel(handles.axes_lineProfile, 'Value');
end
set(handles.uitable_points, 'ColumnName', {'Value', 'x', 'y'});
set(handles.uitable_points, 'ColumnWidth', {50, 40, 40});
% -------------------------------------------------------------------
function check_grid(handles)
if 1 == get(handles.checkbox_grid, 'Value')
grid(handles.axes_lineProfile, 'on');
else
grid(handles.axes_lineProfile, 'off');
end
% -------------------------------------------------------------------
function check_marker(handles)
h = getappdata(handles.figure_lp, 'hProfile');
if 1 == get(handles.checkbox_marker, 'Value')
set(h, 'Marker', 'o', 'MarkerEdgeColor', 'none', 'MarkerFaceColor', 'r');
else
set(h, 'Marker', 'none');
end
% --- Outputs from this function are returned to the command line.
function varargout = line_measurement_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 checkbox_stretch.
function checkbox_stretch_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_stretch (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_stretch
hSel = getappdata(handles.figure_lp, 'hSelectedPoint');
if is_handle(hSel)
delete(hSel);
end
setappdata(handles.figure_lp, 'hSelectedPoint', []);
update_3d_profile(handles);
check_grid(handles);
check_marker(handles);
% --- Executes on button press in checkbox_grid.
function checkbox_grid_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_grid (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_grid
check_grid(handles);
% --- Executes on button press in checkbox_marker.
function checkbox_marker_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_marker (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_marker
check_marker(handles);
% --- Executes when selected cell(s) is changed in uitable_points.
function uitable_points_CellSelectionCallback(hObject, eventdata, handles)
% hObject handle to uitable_points (see GCBO)
% eventdata structure with the following fields (see UITABLE)
% Indices: row and column indices of the cell(s) currently selecteds
% handles structure with handles and user data (see GUIDATA)
if isempty(eventdata.Indices)
return;
end
r = eventdata.Indices(1);
hProfile = getappdata(handles.figure_lp, 'hProfile');
if isempty(hProfile)
return;
end
xd = get(hProfile, 'XData');
yd = get(hProfile, 'YData');
zd = get(hProfile, 'ZData');
lineType = getappdata(handles.figure_lp, 'lineType');
hSel = getappdata(handles.figure_lp, 'hSelectedPoint');
if isempty(hSel)
hold(handles.axes_lineProfile, 'on');
if 1 == lineType || 1 == get(handles.checkbox_stretch, 'Value')
hSel = plot(handles.axes_lineProfile, xd(r), yd(r));
else
hSel = plot3(handles.axes_lineProfile, xd(r), yd(r), zd(r));
end
set(hSel, 'Marker', 'o', 'MarkerEdgeColor', 'm', 'MarkerFaceColor', 'g');
hold(handles.axes_lineProfile, 'off');
setappdata(handles.figure_lp, 'hSelectedPoint', hSel);
else
set(hSel, 'XData', xd(r), 'YData', yd(r));
if 2 == lineType && 0 == get(handles.checkbox_stretch, 'Value')
set(hSel, 'ZData', zd(r));
end
end
% --------------------------------------------------------------------
function uitable_points_ButtonDownFcn(hObject, eventdata, handles)
% hObject handle to uitable_points (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
hSel = getappdata(handles.figure_lp, 'hSelectedPoint');
if ~isempty(hSel)
delete(hSel);
setappdata(handles.figure_lp, 'hSelectedPoint', []);
end
% --- Executes when user attempts to close figure_lp.
function figure_lp_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure_lp (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mainFigHandle = getappdata(handles.figure_lp, 'mainFigHandle');
if is_handle(mainFigHandle)
hFun = getappdata(mainFigHandle, 'hFunCallbackLineMeasurementClosed');
if isa(hFun, 'function_handle')
feval(hFun, mainFigHandle);
end
else
delete(hObject);
end
|
github
|
jacksky64/imageProcessing-master
|
image_stats.m
|
.m
|
imageProcessing-master/3dViewer/image_stats.m
| 5,961 |
utf_8
|
5e350d3d77071a8cfdaf1904d9583a79
|
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Copyright:
% Jun Tan
% University of Texas Southwestern Medical Center
% Department of Radiation Oncology
% Last edited: 08/19/2014
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function varargout = image_stats(varargin)
% IMAGE_STATS MATLAB code for image_stats.fig
% IMAGE_STATS, by itself, creates a new IMAGE_STATS or raises the existing
% singleton*.
%
% H = IMAGE_STATS returns the handle to a new IMAGE_STATS or the handle to
% the existing singleton*.
%
% IMAGE_STATS('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in IMAGE_STATS.M with the given input arguments.
%
% IMAGE_STATS('Property','Value',...) creates a new IMAGE_STATS or raises the
% existing singleton*. Starting from the left, property value pairs are
% applied to the GUI before image_stats_OpeningFcn gets called. An
% unrecognized property name or invalid value makes property application
% stop. All inputs are passed to image_stats_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 image_stats
% Last Modified by GUIDE v2.5 11-Aug-2014 20:13:00
% Begin initialization code - DO NOT EDIT
gui_Singleton = 0;
gui_State = struct('gui_Name', mfilename, ...
'gui_Singleton', gui_Singleton, ...
'gui_OpeningFcn', @image_stats_OpeningFcn, ...
'gui_OutputFcn', @image_stats_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 image_stats is made visible.
function image_stats_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 image_stats (see VARARGIN)
% Choose default command line output for image_stats
handles.output = hObject;
% Update handles structure
guidata(hObject, handles);
parse_args(hObject, varargin);
setappdata(hObject, 'entry_update_data', @parse_args);
set(hObject, 'Visible', getappdata(hObject, 'initialVisible'));
% -------------------------------------------------------------------
function parse_args(hFig, args)
handles = guidata(hFig);
numArgs = length(args);
assert(1 == numArgs || 2 == numArgs, 'Must have 1 or 2 arguments');
setappdata(handles.figure_is, 'mainFigHandle', []);
setappdata(handles.figure_is, 'initialVisible', 'on');
parse_image_data(handles, args{1});
if 2 == numArgs
assert(is_handle(args{2}));
setappdata(handles.figure_is, 'initialVisible', 'off');
setappdata(handles.figure_is, 'mainFigHandle', args{2});
end
update_stats(handles);
% -------------------------------------------------------------------
function parse_image_data(handles, imageData)
assert((isnumeric(imageData) || islogical(imageData)) && ismatrix(imageData), ...
'Data must be gray or binary 2D image.');
setappdata(handles.figure_is, 'imageData', double(imageData));
% -------------------------------------------------------------------
function update_stats(handles)
imageData = getappdata(handles.figure_is, 'imageData');
data = imageData(:);
hist(handles.axes_hist, data, 100);
box(handles.axes_hist, 'off');
xlabel(handles.axes_hist, 'Pixel value');
ylabel(handles.axes_hist, 'Counts');
stats = cell(6, 2);
stats{1, 1} = ' Area';
stats{1, 2} = numel(data);
stats{2, 1} = ' Width';
stats{2, 2} = size(imageData, 2);
stats{3, 1} = ' Height';
stats{3, 2} = size(imageData, 1);
stats{4, 1} = ' Max';
stats{4, 2} = max(data);
stats{5, 1} = ' Min';
stats{5, 2} = min(data);
stats{6, 1} = ' Mean';
stats{6, 2} = mean(data);
stats{7, 1} = ' SD';
stats{7, 2} = std(data);
set(handles.uitable_stats, 'Data', stats);
check_grid(handles);
% -------------------------------------------------------------------
function check_grid(handles)
if 1 == get(handles.checkbox_grid, 'Value')
grid(handles.axes_hist, 'on');
else
grid(handles.axes_hist, 'off');
end
% --- Outputs from this function are returned to the command line.
function varargout = image_stats_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 checkbox_grid.
function checkbox_grid_Callback(hObject, eventdata, handles)
% hObject handle to checkbox_grid (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
% Hint: get(hObject,'Value') returns toggle state of checkbox_grid
check_grid(handles);
% --- Executes when user attempts to close figure_is.
function figure_is_CloseRequestFcn(hObject, eventdata, handles)
% hObject handle to figure_is (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
mainFigHandle = getappdata(handles.figure_is, 'mainFigHandle');
if is_handle(mainFigHandle)
hFun = getappdata(mainFigHandle, 'hFunCallbackSliceStatsClosed');
if isa(hFun, 'function_handle')
feval(hFun, mainFigHandle);
end
else
delete(hObject);
end
|
github
|
jacksky64/imageProcessing-master
|
knnc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/knnc.m
| 3,535 |
utf_8
|
20362e51c361d7899c025ded631e1d9b
|
%KNNC K-Nearest Neighbor Classifier
%
% [W,K,E] = KNNC(A,K)
% [W,K,E] = KNNC(A)
%
% INPUT
% A Dataset
% K Number of the nearest neighbors (optional; default: K is
% optimized with respect to the leave-one-out error on A)
%
% OUTPUT
% W k-NN classifier
% K Number of the nearest neighbors used
% E The leave-one-out error of the KNNC
%
% DESCRIPTION
% Computation of the K-nearest neighbor classifier for the dataset A.
% The resulting classifier W is automatically evaluated by KNN_MAP.
%
% Warning: class prior probabilities in A are neglected.
%
% SEE ALSO
% MAPPINGS, DATASETS, KNN_MAP
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: knnc.m,v 1.4 2007/04/13 09:29:57 duin Exp $
function [W,knn,e,ek] = knnc(a,knn)
prtrace(mfilename);
if (nargin < 2)
prwarning(4,'Number of nearest neighbors not supplied, optimized wrt the leave-one-out error.');
knn = [];
end
% No input data, return an untrained classifier.
if (nargin == 0) | (isempty(a))
W = mapping('knnc',knn);
if (isempty(knn))
W = setname(W,'K-NN Classifier');
else
W = setname(W,[num2str(knn) '-NN Classifier']);
end
return;
end
islabtype(a,'crisp','soft');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a);
a = testdatasize(a,'objects');
a = seldat(a); % get labeled objects only
[m,k,c] = getsize(a);
nlab = getnlab(a);
if (isempty(knn))
% Optimize knn by the LOO procedure.
[num,bat] = prmem(m,m);
z = zeros(1,m);
N = zeros(c,m);
for i = 0:num-1 % Compute the distance matrix part by part
if (i == num-1) % depending on the available memory.
nn = m - num*bat + bat;
else
nn = bat;
end
I = [i*bat+1:i*bat+nn];
D=+distm(a,a(I,:));
[Y,L] = sort(D); % Sort in columns.
% L are the labels of the nearest-to-further neighbors for the objects from I.
L = nlab(L)';
Ymax = zeros(nn,m);
Yc = zeros(nn,m);
if islabtype(a,'soft')
error('Soft labels not yet allowed for optimisation of k')
end
for j = 1:c
Y = +(L == j); % Mark by 1 the positions of the class j in
for n = 3:m % the ordered distances to the objects from I.
Y(:,n) = Y(:,n-1) + Y(:,n);
end
% Y is NN x M; for objects from I, Y(:,P) counts all the objects
% from the class j that are within the first P nearest neighbors.
Y(:,1) = zeros(nn,1);
J = Y > Ymax; % J is the index of the 'winning' class
Ymax(J) = Y(J); % within the first nearest neighbors.
Yc(J) = j*ones(size(Yc(J)));
end
z = z + sum(Yc == repmat(nlab(I),1,m),1); % number of objects correctly classified for knn = 0,1,2,...
end
name = 'K-NN Classifier';
[e,knn] = max(z); % select best neighborhood size
knn = knn-1; % correct for leave-one-out
knn = max(knn,1); % correct for pathological case knn = 0 (it appeared to exist!: all objects were
% incorrectly classified for all neighbood sizes).
e = 1 - e/m;
ek = 1 - z/m;
ek(1) = [];
else % knn is fixed
if (knn > m)
error('The number of neighbors should not be larger than number of training objects.')
end
if (nargout > 2)
e = testk(a,knn);
end
name = [num2str(knn) '-NN Classifier'];
end
W = mapping('knn_map','trained',{a,knn},getlablist(a),k,c);
W = setname(W,name);
W = setcost(W,a);
return
|
github
|
jacksky64/imageProcessing-master
|
im_skel_meas.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_skel_meas.m
| 1,669 |
utf_8
|
dcdcd014bc93aaef5301141e3c64512a
|
%IM_SKEL_MEASURE Computation by DIP_Image of skeleton-based features
%
% F = IM_SKEL_MEASURE(A,FEATURES)
%
% INPUT
% A Dataset with binary object images dataset
% FEATURES Features to be computed
%
% OUTPUT
% F Dataset with computed features
%
% DESCRIPTION
% The following features may be computed on the skeleton images in A:
% 'branch', 'end', 'link', 'single'. They should be combined in a cell
% array.
%
% Use FEATURES = 'all' for computing all features (default).
%
% SEE ALSO
% DATASETS, DATAFILES, IM_SKEL, DIP_IMAGE, BSKELETON
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_skel_meas(a,features)
prtrace(mfilename);
if nargin < 2 | isempty(features), features = 'all'; end
if strcmp(features,'all')
features = {'branch', 'end', 'link', 'single'};
end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed');
b = setname(b,'Skeleton features',{features});
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,{features});
b = setfeatlab(b,features);
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
b = [];
if ~iscell(features), features = {features}; end
for i = 1:length(features)
if strcmp (features{i}, 'branch')
b = [ b sum(getbranchpixel(a)) ];
end;
if strcmp (features{i}, 'end')
b = [ b sum(getendpixel(a)) ];
end;
if strcmp (features{i}, 'link')
b = [ b sum(getlinkpixel(a)) ];
end;
if strcmp (features{i}, 'single')
b = [ b sum(getsinglepixel(a)) ];
end;
end;
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_fft.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_fft.m
| 859 |
utf_8
|
9c39c2a03e24449fb0baa8cf48e786b2
|
%IM_FFT 2D FFT of all images in dataset
%
% F = IM_FFT(A)
%
% INPUT
% A Dataset with object images (possibly multi-band)
%
% OUTPUT
% F Dataset with FFT images
%
% SEE ALSO
% DATASETS, DATAFILES, FFT2
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_fft(a,varargin)
prtrace(mfilename);
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',varargin);
b = setname(b,'Image FFT');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,varargin);
b = setfeatsize(b,getfeatsize(a));
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = double(a);
b = fft2(a);
if nargin > 1
for j=1:nargin-1
b = filtim(b,varargin{j});
end
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
parzenm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/parzenm.m
| 2,629 |
utf_8
|
fc2c033dbde1f0e376cebdb6f43eb220
|
%PARZENM Estimate Parzen densities
%
% W = PARZENM(A,H)
% W = A*PARZENM([],H)
%
% D = B*W
%
% INPUT
% A Input dataset
% H Smoothing parameters (scalar, vector)
%
% OUTPUT
% W output mapping
%
% DESCRIPTION
% A Parzen distribution is estimated for the labeled objects in A. Unlabeled
% objects are neglected, unless A is entirely unlabeled or double. Then all
% objects are used. If A is a multi-class dataset the densities are estimated
% class by class and then weighted and combined according their prior
% probabilities. In all cases, just single density estimator W is computed.
%
% The mapping W may be applied to a new dataset B using DENSITY = B*W.
%
% The smoothing parameter H is estimated by PARZENML if not supplied. It can
% be a scalar or a vector with as many components as A has features.
%
% SEE ALSO
% DATASETS, MAPPINGS, KNNM, GAUSSM, PARZENML, PARZENDC, KNNM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: parzenm.m,v 1.5 2008/05/21 11:49:59 duin Exp $
function w = parzenm(a,h,n)
prtrace(mfilename);
if (nargin < 3), n = 1; end
if (nargin < 2), h = []; end
% No input arguments specified: return an untrained mapping.
mapname = 'Parzen Density Estimation';
if (nargin < 1 | isempty(a))
w = mapping(mfilename,{h,n});
w = setname(w,mapname);
return;
end
a = dataset(a); a = remclass(a);
labname = getname(a);
islabtype(a,'crisp','soft');
isvaldfile(a,2,1); % at least 2 objects per class, 1 class
a = testdatasize(a);
a = testdatasize(a,'objects');
if (getsize(a,3) ~= 1)
w = mclassm(a,mapping(mfilename,h),'weight');
w = setlabels(w,labname);
w = setname(w,mapname);
return
end
[m,k] = size(a);
% Scale A such that its mean is shifted to the origin and
% the variances of all features are scaled to 1.
if isempty(h) % if no smoothing parameter given, we have to estimate
% it later, lets scale first
ws = scalem(a,'variance');
else
ws = affine(ones(1,k),zeros(1,k),a);
end
b = a*ws;
% SCALE is basically [1/mean(A) 1/STD(A)] based on the properties of SCALEM.
scale = ws.data.rot;
if (size(scale,1) ~= 1) % formally ws.data.rot stores a rotation matrix
scale = diag(scale)'; % extract the diagonal if it does,
end % otherwise we already have the diagonal
if isempty(h)
if n==1
h = repmat(parzenml(b),1,k)./scale;
else
h = repmat(emparzenml(b,n),1,k)./repmat(scale,n,1);
end
end
w = mapping('parzen_map','trained',{a,h},labname,k,1);
w = setname(w,mapname);
return
|
github
|
jacksky64/imageProcessing-master
|
col2gray.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/col2gray.m
| 1,596 |
utf_8
|
8f52ea4434366e7be840bf8ffebaf7dd
|
%COL2GRAY Mapping for converting multi-band images into single band images
%
% B = COL2GRAY(A,V)
% B = A*COL2GRAY([],V)
%
% INPUT
% A Multiband image or dataset with multi-band images as objects
% V Weight vector, one weight per band. Default: equal weights.
%
% OUTPUT
% B Output image or dataset.
%
% DESCRIPTION
% The multi-band components in the image A (3rd dimension) or in the
% objects in the dataset A are weigthed (default: equal weights) and
% averaged.
%
% SEE ALSO
% MAPPINGS, DATASTS, DATAFILES
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = col2gray(a,v)
prtrace(mfilename,2);
if nargin < 2, v = []; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{v});
b = setname(b,'Color-to-gray conversion');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtm(a,mfilename,v);
imsize = getfeatsize(a);
b = setfeatsize(b,imsize(1:2));
elseif isa(a,'double')
imsize = size(a);
if isempty(v)
if length(imsize) == 3
b = mean(a,3);
b = squeeze(b);
elseif length(imsize) == 2
b = a;
else
error('Illegal image size')
end
else
if length(imsize) == 2
b = a;
else
b = zeros(imsize(1),imsize(2),size(a,1));
for i=1:size(a,1)
for j=1:size(im,3)
b(:,:,i) =b(:,:,i) + b(:,:,j,i)*v(j);
end
end
end
end
else
error('Illegal datatype for input')
end
return
|
github
|
jacksky64/imageProcessing-master
|
nulibsvc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nulibsvc.m
| 5,160 |
utf_8
|
d2e65d89f90066e16b5bd949f48decea
|
%NULIBSVC Support Vector Classifier by libsvm, nu version
%
% [W,J,NU] = NULIBSVC(A,KERNEL,NU)
%
% INPUT
% A Dataset
% KERNEL Mapping to compute kernel by A*MAP(A,KERNEL)
% or string to compute kernel by FEVAL(KERNEL,A,A)
% or cell array with strings and parameters to compute kernel by
% FEVAL(KERNEL{1},A,A,KERNEL{2:END})
% Default: linear kernel.
% NU nu value, upperbound error.
% Default NU is derived from 1-NN error.
%
% OUTPUT
% W Mapping: Support Vector Classifier
% J Object idences of support objects. Can be also obtained as W{4}
% NU Actual nu_value used
%
% DESCRIPTION
% Optimizes a support vector classifier for the dataset A by the libsvm
% package, see http://www.csie.ntu.edu.tw/~cjlin/libsvm/. LIBSVC calls the
% svmtrain routine of libsvm for training. Classifier execution for a
% test dataset B may be done by D = B*W; In D posterior probabilities are
% given as computed by svmpredict using the '-b 1' option.
%
% The kernel may be supplied in KERNEL by
% - an untrained mapping, e.g. a call to PROXM like W = LIBSVC(A,PROXM([],'R',1))
% - a string with the name of the routine to compute the kernel from A
% - a cell-array with this name and additional parameters.
% This will be used for the evaluation of a dataset B by B*W or MAP(B,W) as
% well.
%
% If KERNEL = 0 (or not given) it is assumed that A is already the
% kernelmatrix (square). In this also a kernel matrix should be supplied at
% evaluation by B*W or MAP(B,W). However, the kernel has to be computed with
% respect to support objects listed in J (the order of objects in J does matter).
%
% REFERENCES
% R.-E. Fan, P.-H. Chen, and C.-J. Lin. Working set selection using the second order
% information for training SVM. Journal of Machine Learning Research 6, 1889-1918, 2005
%
% SEE ALSO
% MAPPINGS, DATASETS, LIBSVC, SVC, PROXM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [W,J,NU] = libsvc(a,kernel,NU)
prtrace(mfilename);
libsvmcheck;
if nargin < 3
NU = [];
end
if nargin < 2 | isempty(kernel)
kernel = proxm([],'p',1);
end
if nargin < 1 | isempty(a)
W = mapping(mfilename,{kernel,NU});
W = setname(W,'LIBSVM Classifier');
return;
end
if (~ismapping(kernel) | isuntrained(kernel)) % training
if isempty(NU), NU = 2*min(max(testk(a,1),0.01),(0.8*min(classsizes(a))/size(a,1))); end
%disp(NU)
opt = ['-s 1 -t 4 -b 1 -n ',num2str(NU), ' -q'];
islabtype(a,'crisp');
isvaldset(a,1,2); % at least 1 object per class, 2 classes
[m,k,c] = getsize(a);
nlab = getnlab(a);
K = compute_kernel(a,a,kernel);
K = min(K,K'); % make sure kernel is symmetric
K = [[1:m]' K]; % as libsvm wants it
% call libsvm
u = svmtrain(nlab,K,opt);
if isempty(u)
prwarning(1,'nulibsvc: no solution for SVM, pseudo-inverse will be used')
W = lkc(K,0);
J = [1:m]';
return
end
% Store the results:
J = full(u.SVs);
if isequal(kernel,0)
s = [];
in_size = length(J);
% in_size = 0; % to allow old and new style calls
else
s = a(J,:);
in_size = k;
end
lablist = getlablist(a);
W = mapping(mfilename,'trained',{u,s,kernel,J,opt},lablist(u.Label,:),in_size,c);
W = setname(W,'LIBSVM Classifier');
W = setcost(W,a);
else % execution
v = kernel;
w = +v;
m = size(a,1);
u = w{1};
s = w{2};
kernel = w{3};
J = w{4};
opt = w{5};
K = compute_kernel(a,s,kernel);
k = size(K,2);
if k ~= length(J)
if isequal(kernel,0)
if (k > length(J)) & (k >= max(J))
% precomputed kernel; old style call
prwarning(1,'Old style execution call: The precomputed kernel was calculated on a test set and the whole training set!')
else
error('Inappropriate precomputed kernel!\nFor the execution the kernel matrix should be computed on a test set and the set of support objects');
end
else
error('Kernel matrix has the wrong number of columns');
end
else
% kernel was computed with respect to the support objects
% we make an approprite correction in the libsvm structure
u.SVs = sparse((1:length(J))');
end
K = [[1:m]' K]; % as libsvm wants it
[lab,acc,d] = svmpredict(getnlab(a),K,u,'-b 1');
W = setdat(a,d,v);
end
return;
function K = compute_kernel(a,s,kernel)
% compute a kernel matrix for the objects a w.r.t. the support objects s
% given a kernel description
if isstr(kernel) % routine supplied to compute kernel
K = feval(kernel,a,s);
elseif iscell(kernel)
K = feval(kernel{1},a,s,kernel{2:end});
elseif ismapping(kernel)
K = a*map(s,kernel);
elseif kernel == 0 % we have already a kernel
K = a;
else
error('Do not know how to compute kernel matrix')
end
K = +K;
return
|
github
|
jacksky64/imageProcessing-master
|
cleval.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/cleval.m
| 8,372 |
utf_8
|
db8f67007c6c315e32e927542219cbac
|
%CLEVAL Classifier evaluation (learning curve)
%
% E = CLEVAL(A,CLASSF,TRAINSIZES,NREPS,T,TESTFUN)
%
% INPUT
% A Training dataset
% CLASSF Classifier to evaluate
% TRAINSIZE Vector of training set sizes, used to generate subsets of A
% (default [2,3,5,7,10,15,20,30,50,70,100]). TRAINSIZE is per
% class unless A has no priors set or has soft labels.
% NREPS Number of repetitions (default 1)
% T Tuning dataset (default [], use remaining samples in A)
% TESTFUN Mapping,evaluation function (default classification error)
%
% OUTPUT
% E Error structure (see PLOTE) containing training and test
% errors
%
% DESCRIPTION
% Generates at random, for all class sizes defined in TRAINSIZES, training
% sets out of the dataset A and uses these for training the untrained
% classifier CLASSF. CLASSF may also be a cell array of untrained
% classifiers; in this case the routine will be run for all of them. The
% resulting trained classifiers are tested on the training objects and
% on the left-over test objects. This procedure is then repeated NREPS
% times. The default test routine is classification error estimation by
% TESTC([],'crisp').
%
% Training set generation is done "with replacement" and such that for each
% run the larger training sets include the smaller ones and that for all
% classifiers the same training sets are used.
%
% If CLASSF is fully deterministic, this function uses the RAND random
% generator and thereby reproduces if its seed is reset (see RAND).
% If CLASSF uses RANDN, its seed may have to be set as well.
%
% Per default both the true error (error on the test set) and the
% apparent error (error on the training set) are computed. They will be
% visible when the curves are plotted using PLOTE.
%
% EXAMPLE
% See PREX_CLEVAL
%
% SEE ALSO
% MAPPINGS, DATASETS, CLEVALB, TESTC, PLOTE
% Copyright: D.M.J. Tax, R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function e = cleval(a,classf,learnsizes,nreps,t,testfun)
prtrace(mfilename);
if (nargin < 6) | isempty(testfun)
testfun = testc([],getlabtype(a));
end;
if (nargin < 5) | isempty(t)
prwarning(2,'no tuning set T supplied, using remaining samples in A');
t = [];
end;
if (nargin < 4) | isempty(nreps);
prwarning(2,'number of repetitions not specified, assuming NREPS = 1');
nreps = 1;
end;
if (nargin < 3) | isempty(learnsizes);
prwarning(2,'vector of training set class sizes not specified, assuming [2,3,5,7,10,15,20,30,50,70,100]');
learnsizes = [2,3,5,7,10,15,20,30,50,70,100];
end;
% Correct for old argument order.
if (isdataset(classf)) & (ismapping(a))
tmp = a; a = classf; classf = {tmp};
end
if (isdataset(classf)) & (iscell(a)) & (ismapping(a{1}))
tmp = a; a = classf; classf = tmp;
end
if ~iscell(classf), classf = {classf}; end
% Assert that all is right.
isdataset(a); ismapping(classf{1}); if (~isempty(t)), isdataset(t); end
% Remove requested class sizes that are larger than the size of the
% smallest class.
[m,k,c] = getsize(a);
if ~isempty(a,'prior') & islabtype(a,'crisp')
classs = true;
mc = classsizes(a);
toolarge = find(learnsizes >= min(mc));
if (~isempty(toolarge))
prwarning(2,['training set class sizes ' num2str(learnsizes(toolarge)) ...
' larger than the minimal class size; removed them']);
learnsizes(toolarge) = [];
end
else
if islabtype(a,'crisp') & isempty(a,'prior')
prwarning(1,['No priors found in dataset, class frequencies are used.' ...
newline ' Training set sizes hold for entire dataset']);
end
classs = false;
toolarge = find(learnsizes >= m);
if (~isempty(toolarge))
prwarning(2,['training set sizes ' num2str(learnsizes(toolarge)) ...
' larger than number of objects; removed them']);
learnsizes(toolarge) = [];
end
end
learnsizes = learnsizes(:)';
% Fill the error structure.
nw = length(classf(:));
datname = getname(a);
e.n = nreps;
e.error = zeros(nw,length(learnsizes));
e.std = zeros(nw,length(learnsizes));
e.apperror = zeros(nw,length(learnsizes));
e.appstd = zeros(nw,length(learnsizes));
e.xvalues = learnsizes(:)';
if classs
e.xlabel = 'Training set size per class';
else
e.xlabel = 'Training set size';
end
e.names = [];
if (nreps > 1)
e.ylabel= ['Averaged error (' num2str(nreps) ' experiments)'];
elseif (nreps == 1)
e.ylabel = 'Error';
else
error('Number of repetitions NREPS should be >= 1.');
end;
if (~isempty(datname))
e.title = ['Learning curve on ' datname];
end
if (learnsizes(end)/learnsizes(1) > 20)
e.plot = 'semilogx'; % If range too large, use a log-plot for X.
end
% Report progress.
s1 = sprintf('cleval: %i classifiers: ',nw);
prwaitbar(nw,s1);
% Store the seed, to reset the random generator later for different
% classifiers.
seed = rand('state');
% Loop over all classifiers (with index WI).
for wi = 1:nw
if (~isuntrained(classf{wi}))
error('Classifiers should be untrained.')
end
name = getname(classf{wi});
e.names = char(e.names,name);
prwaitbar(nw,wi,[s1 name]);
% E1 will contain the error estimates.
e1 = zeros(nreps,length(learnsizes));
e0 = zeros(nreps,length(learnsizes));
% Take care that classifiers use same training set.
rand('state',seed); seed2 = seed;
% For NREPS repetitions...
s2 = sprintf('cleval: %i repetitions: ',nreps);
prwaitbar(nreps,s2);
for i = 1:nreps
prwaitbar(nreps,i,[s2 int2str(i)]);
% Store the randomly permuted indices of samples of class CI to use in
% this training set in JR(CI,:).
if classs
JR = zeros(c,max(learnsizes));
for ci = 1:c
JC = findnlab(a,ci);
% Necessary for reproducable training sets: set the seed and store
% it after generation, so that next time we will use the previous one.
rand('state',seed2);
JD = JC(randperm(mc(ci)));
JR(ci,:) = JD(1:max(learnsizes))';
seed2 = rand('state');
end
elseif islabtype(a,'crisp')
rand('state',seed2); % get seed for reproducable training sets
% generate indices for the entire dataset taking care that in
% the first 2c objects we have 2 objects for every class
[a1,a2,I1,I2] = gendat(a,2*ones(1,c));
JD = randperm(m-2*c);
JR = [I1;I2(JD)];
seed2 = rand('state'); % save seed for reproducable training sets
else % soft labels
rand('state',seed2); % get seed for reproducable training sets
JR = randperm(m);
seed2 = rand('state'); % save seed for reproducable training sets
end
li = 0; % Index of training set.
nlearns = length(learnsizes);
s3 = sprintf('cleval: %i sizes: ',nlearns);
prwaitbar(nreps,s3);
for j = 1:nlearns
nj = learnsizes(j);
prwaitbar(nlearns,j,[s3 int2str(j) ' (' int2str(nj) ')']);
li = li + 1;
% J will contain the indices for this training set.
J = [];
if classs
for ci = 1:c
J = [J;JR(ci,1:nj)'];
end;
else
J = JR(1:nj);
end
trainset = a(J,:);
trainset = setprior(trainset,getprior(trainset,0));
w = trainset*classf{wi}; % Use right classifier.
e0(i,li) = trainset*w*testfun;
if (isempty(t))
Jt = ones(m,1);
Jt(J) = zeros(size(J));
Jt = find(Jt); % Don't use training set for testing.
testset = a(Jt,:);
testset = setprior(testset,getprior(testset,0));
e1(i,li) = testset*w*testfun;
else
testset = setprior(t,getprior(t,0));
e1(i,li) = testset*w*testfun;
end
end
prwaitbar(0);
end
prwaitbar(0);
% Calculate average error and standard deviation for this classifier
% (or set the latter to zero if there's been just 1 repetition).
e.error(wi,:) = mean(e1,1);
e.apperror(wi,:) = mean(e0,1);
if (nreps == 1)
e.std(wi,:) = zeros(1,size(e.std,2));
e.appstd(wi,:) = zeros(1,size(e.appstd,2));
else
e.std(wi,:) = std(e1)/sqrt(nreps);
e.appstd(wi,:) = std(e0)/sqrt(nreps);
end
end
prwaitbar(0);
% The first element is the empty string [], remove it.
e.names(1,:) = [];
return
|
github
|
jacksky64/imageProcessing-master
|
classc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/classc.m
| 3,622 |
utf_8
|
095c4dd1edad8a43a38da8b9d9263191
|
%CLASSC Convert classifier to normalized classifier (yielding confidences)
%
% V = CLASSC(W)
% V = W*CLASSC
% D = CLASSC(A*W)
% D = A*W*CLASSC
% D = CLASSC(A,W)
%
% INPUT
% W Trained or untrained classifier
% A Dataset
%
% OUTPUT
% V Normalized classifier producing confidences instead of
% densities or distances (after training if W is untrained)
%
% DESCRIPTION
% The trained or untrained classifier W may yield densities or unnormalised
% confidences. The latter holds for two-class discriminants like FISHERC
% and SVC as well as for neural networks. Such classifiers use or should
% use CNORMC to convert distances to confidences. In multi-class problems
% as well as in combining schemes they do not produce normalises
% confidences. These outcomes, like the density outcomes of classifiers
% liek QDC, LDC and PARZENC, can be converted by CLASSC into confidences:
% the sum of the outcomes will be one for every object.
%
% In case W is a one-dimensional mapping, it is converted into a two-class
% classifier, provided that during the construction a class label was
% supplied. If not, the mapping cannot be converted and an error is
% generated.
%
% CLASSC lists the outcomes on the screen in case no output argument is
% supplied. Also true and estimated labels are supplied.
%
% SEE ALSO
% MAPPINGS, DATASETS, CNORMC, LABELD
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: classc.m,v 1.5 2010/02/23 15:21:54 duin Exp $
function w = classc(w,flag)
prtrace(mfilename);
if nargin < 2, flag = 0; end % flag forces non=combiner behavior avoiding recursion
if (nargin == 0)
% Untrained mapping.
w = mapping('classc','combiner',flag);
elseif (ismapping(w))
% If mapping is stacked or parallel, recurse over the individual
% sub-mappings and call CLASSC for each of them.
if ((isstacked(w)) | (isparallel(w))) & (flag == 0)
v = cell(1,length(w.data));
for j = 1:length(w.data)
if ismapping(w.data{j}) % the parallel combiner may have nonmapping data
v{j} = feval(mfilename,w.data{j});
else
v{j} = w.data{j};
end
end
w = setdata(w,v);
w = feval(mfilename,w,1); % and here CLASSC is called for the combiner avoiding recursion
else
conv = get(w,'out_conv');
if (conv < 1)
% Set the "normalization" bit in the mapping's output conversion flag
w = set(w,'out_conv',conv+2);
else
prwarning(3,'mapping is already a classifier');
end;
end
elseif (isdataset(w))
if ismapping(flag)
if nargout == 1
w = feval(mfilename,w*flag);
else
feval(mfilename,w*flag);
clear w;
end
return
end
w = w*normm;
w = w*costm;
if nargout == 0 % list outcomes on the screen
ww = +w;
ss = repmat('-',1,9*size(ww,2));
fprintf('\n True Estimated Class \nLabels Labels Confidences\n');
fprintf('------------------%s\n',ss);
nlab = getnlab(w);
[wmax,K] = max(ww,[],2);
lablist = getlablist(w);
if ~isempty(lablist) & ~ischar(lablist)
nlab = lablist(nlab);
K = lablist(K);
end
for j=1:size(ww,1)
if (nlab(j) ~= K(j))
fprintf(' %3.0f ->%3.0f ',nlab(j),K(j));
else
fprintf(' %3.0f %3.0f ',nlab(j),K(j));
end
fprintf(' %7.4f',ww(j,:));
fprintf('\n');
end
lablist = getlablist(w);
if ischar(lablist)
fprintf('\n');
for j=1:size(lablist,1)
fprintf(' %i %s\n',j,lablist(j,:));
end
end
clear w;
end
else
error('input should be mapping or dataset');
end
return
|
github
|
jacksky64/imageProcessing-master
|
featselb.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featselb.m
| 2,850 |
utf_8
|
242e3f5afed7c113de4956acdbf3b569
|
%FEATSELB Backward feature selection for classification
%
% [W,R] = FEATSELB(A,CRIT,K,T,FID)
% [W,R] = FEATSELB(A,CRIT,K,N,FID)
%
% INPUT
% A Dataset
% CRIT String name of the criterion or untrained mapping
% (optional; default: 'NN', i.e. 1-Nearest Neighbor error)
% K Number of features to select
% (optional; default: return optimally ordered set of all features)
% T Tuning set (optional)
% N Number of cross-validations
% FID File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% W Output feature selection mapping
% R Matrix with step-by-step results of the selection
%
% DESCRIPTION
% Backward selection of K features using the dataset A. CRIT sets the
% criterion used by the feature evaluation routine FEATEVAL. If the
% dataset T is given, it is used as test set for FEATEVAL. Alternatvely a
% a number of cross-validation N may be supplied. For K = 0, the optimal
% feature set (corresponding to the maximum value of FEATEVAL) is returned.
% The result W can be used for selecting features by B*W. In this case,
% features are ranked optimally.
% The selected features are stored in W.DATA and can be found by +W.
% In R, the search is reported step by step as:
%
% R(:,1) : number of features
% R(:,2) : criterion value
% R(:,3) : added / deleted feature
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSELLR, FEATSEL,
% FEATSELO, FEATSELF, FEATSELI, FEATSELP, FEATSELM, PRPROGRESS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: featselb.m,v 1.6 2008/07/03 09:08:43 duin Exp $
function [w,r] = featselb(a,crit,ksel,t,fid)
prtrace(mfilename);
if (nargin < 2) | isempty(crit)
prwarning(2,'No criterion specified, assuming 1-NN.');
crit = 'NN';
end
if (nargin < 3) | isempty(ksel)
ksel = 0; % Consider all the features and sort them.
end
if (nargin < 4)
prwarning(3,'No tuning set supplied.');
t = [];
end
if (nargin < 5)
fid = [];
end
if nargin == 0 | isempty(a)
% Create an empty mapping:
w = mapping(mfilename,{crit,ksel,t});
else
prprogress(fid,'\nfeatselb : Backward Feature Selection')
[w,r] = featsellr(a,crit,ksel,0,1,t,fid);
%DXD This is a patch: when the number of features has to be
%optimized, and all features seem useful, when the list of
%features is not reshuffled to reflect the relative importance of
%the features:
% (Obviously, this should be fixed in featsellr, but I don't
% understand what is happening in there)
dim = size(a,2);
if (ksel==0) & (length(getdata(w))==dim)
rr = -r(:,3); rr(1) = [];
rr = [setdiff((1:dim)',rr) rr(end:-1:1)'];
w = setdata(w,rr);
end
prprogress(fid,'featselb finished\n')
end
w = setname(w,'Backward FeatSel');
return
|
github
|
jacksky64/imageProcessing-master
|
issym.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/issym.m
| 768 |
utf_8
|
d029ef5dca799d320df7ee0deb0d19fa
|
%ISSYM Checks whether a matrix is symmetric
%
% OK = ISSYM(A,DELTA)
%
% INPUT
% A Dataset
% DELTA Parameter for the precision check (optional; default: 1e-12)
%
% OUTPUT
% OK 1 if the matrix A is symmetric and 0, otherwise.
%
% DESCRIPTION
% A is considered as a symmetric matrix, when it is square and
% max(max(A-A')) is smaller than DELTA.
%
%
% Robert P.W. Duin, Elzbieta Pekalska, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
%
function [ok,nn] = issym(A,delta)
if nargin < 2,
prwarning(6,'The precision is not provided, set up to 1e-12.');
delta = 1e-12;
end
A = +A;
[m,k] = size(A);
if m ~= k,
error ('Matrix should be square.')
end
nn = max(max((A-A')));
ok = (nn < delta);
return;
|
github
|
jacksky64/imageProcessing-master
|
misval.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/misval.m
| 2,478 |
utf_8
|
c3add71d533e6203113d88dfc8a0fd1c
|
%MISVAL Fix the missing values in a dataset
%
% B = MISVAL(A,VAL)
% B = A*MISVAL([],VAL)
%
% INPUT
% A Dataset, containing NaNs (missing values)
% VAL String with substitution option
% or value used for substitution
%
% B Dataset with NaNs substituted
%
% DESCRIPTION
%
% The following values for VAL are possible:
% 'remove' remove objects (rows) that contain missing values (default)
% 'f-remove' remove features (columns) that contain missing values
% 'mean' fill the entries with the mean of their features
% 'c-mean' fill the entries with the class mean of their features
% <value> fill the entries with a fixed constant
%
% SEE ALSO
% DATASETS
% Copyright: D.M.J. Tax, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [x,msg] = misval(x,val)
if nargin < 2 | isempty(val), val = 'remove'; end
if nargin < 1 | isempty(x)
x = mapping(mfilename,val);
x = setname(x,'missing value')
else
x = dataset(x);
[m,k,c] = getsize(x);
% Where are the offenders?
I = isnan(x);
% If there are missing values, go:
if any(I(:))
switch val
case {'remove' 'delete'}
J = find(sum(I,2)==0);
x = x(J,:);
msg = 'Objects with missing values have been removed.';
case {'f-remove' 'f-delete'}
J = find(sum(I,1)==0);
x = x(:,J);
msg = 'Features with missing values have been removed.';
case 'mean'
for i=1:k
J = ~I(:,i);
if any(I(:,i)) %is there a missing value in this feature?
if ~any(J)
error('Missing value cannot be filled: all values are NaN.');
end
mn = mean(x(J,i));
x(find(I(:,i)),i) = mn;
end
end
msg = 'Missing values have been replaced by the feature mean.';
case 'c-mean'
for j=1:c
L = findnlab(x,j);
for i=1:k
J = ~I(L,i);
if any(I(L,i)) %is there a missing value in this feature for this class?
if ~any(J)
error('Missing value cannot be filled: all values are NaN.');
end
mn = mean(x(J,i));
x(find(I(:,i)),i) = mn;
end
end
end
msg = 'Missing values have been replaced by the class feature mean.';
otherwise
if isstr(val)
error('unknown option')
end
if ~isa(val,'double')
error('Missing values can only be filled by scalars.');
end
x(I) = val;
msg = sprintf('Missing values have been replaced by %f.',val);
end
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
isdataset.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/isdataset.m
| 501 |
utf_8
|
0b61fa069741029a5c4bf06e4ba660c4
|
%ISDATASET Test whether the argument is a dataset
%
% N = ISDATASET(A);
%
% INPUT
% A Input argument
%
% OUTPUT
% N 1/0 if A is/isn't a dataset
%
% DESCRIPTION
% The function ISDATASET test if A is a dataset object.
%
% SEE ALSO
% ISMAPPING, ISDATAIM, ISFEATIM
% $Id: isdataset.m,v 1.3 2007/03/22 08:54:59 duin Exp $
function n = isdataset(a)
prtrace(mfilename);
n = isa(a,'dataset') & ~isa(a,'datafile');
if (nargout == 0) & (n == 0)
error([newline 'Dataset expected.'])
end
return;
|
github
|
jacksky64/imageProcessing-master
|
stumpc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/stumpc.m
| 14,270 |
utf_8
|
eafef64246953de2e60096c0899fd40e
|
%STUMPC Decision stump classifier
%
% W = STUMPC(A,CRIT,N)
%
% Computation of a decision tree classifier out of a dataset A using
% a binary splitting criterion CRIT:
% INFCRIT - information gain
% MAXCRIT - purity (default)
% FISHCRIT - Fisher criterion
% Just N (default N=1) nodes are computed.
%
% see also DATASETS, MAPPINGS, TREEC, TREE_MAP
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: stumpc.m,v 1.2 2009/07/10 11:19:20 duin Exp $
function w = treec(a,crit,n)
prtrace(mfilename);
if nargin < 3 | isempty(n), n = 1; end
if nargin < 2 | isempty(crit), crit = 'maxcrit'; end
% When no input data is given, an empty tree is defined:
if nargin == 0 | isempty(a)
w = mapping(mfilename,{crit,n});
w = setname(w,'Decision Stump');
return
end
% Given some data, a tree can be trained
islabtype(a,'crisp');
isvaldset(a,1,2); % at least 1 object per class, 2 classes
% First get some useful parameters:
[m,k,c] = getsize(a);
nlab = getnlab(a);
tree = maketree(+a,nlab,c,crit,n);
% Store the results:
w = mapping('tree_map','trained',{tree,1},getlablist(a),k,c);
w = setname(w,'Decision Tree');
w = setcost(w,a);
return
%MAKETREE General tree building algorithm
%
% tree = maketree(A,nlab,c,crit,stop)
%
% Constructs a binary decision tree using the criterion function
% specified in the string crit ('maxcrit', 'fishcrit' or 'infcrit'
% (default)) for a set of objects A. stop is an optional argument
% defining early stopping according to the Chi-squared test as
% defined by Quinlan [1]. stop = 0 (default) gives a perfect tree
% (no pruning) stop = 3 gives a pruned version stop = 10 a heavily
% pruned version.
%
% Definition of the resulting tree:
%
% tree(n,1) - feature number to be used in node n
% tree(n,2) - threshold t to be used
% tree(n,3) - node to be processed if value <= t
% tree(n,4) - node to be processed if value > t
% tree(n,5:4+c) - aposteriori probabilities for all classes in
% node n
%
% If tree(n,3) == 0, stop, class in tree(n,1)
%
% This is a low-level routine called by treec.
%
% See also infstop, infcrit, maxcrit, fishcrit and mapt.
% Authors: Guido te Brake, TWI/SSOR, Delft University of Technology
% R.P.W. Duin, TN/PH, Delft University of Technology
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function tree = maketree(a,nlab,c,crit,n)
prtrace(mfilename);
[m,k] = size(a);
% Construct the tree:
% When all objects have the same label, create an end-node:
if all([nlab == nlab(1)])
% Avoid giving 0-1 probabilities, but 'regularize' them a bit using
% a 'uniform' Bayesian prior:
p = ones(1,c)/(m+c); p(nlab(1)) = (m+1)/(m+c);
tree = [nlab(1),0,0,0,p];
else
% now the tree is recursively constructed further:
[f,j,t] = feval(crit,+a,nlab); % use desired split criterion
p = sum(expandd(nlab),1);
if length(p) < c, p = [p,zeros(1,c-length(p))]; end
% When the stop criterion is not reached yet, we recursively split
% further:
if n >= 1
% Make the left branch:
J = find(a(:,j) <= t);
tl = maketree(+a(J,:),nlab(J),c,crit,n-1);
% Make the right branch:
K = find(a(:,j) > t);
tr = maketree(+a(K,:),nlab(K),c,crit,n-1);
% Fix the node labelings before the branches can be 'glued'
% together to a big tree:
[t1,t2] = size(tl);
tl = tl + [zeros(t1,2) tl(:,[3 4])>0 zeros(t1,c)];
[t3,t4] = size(tr);
tr = tr + (t1+1)*[zeros(t3,2) tr(:,[3 4])>0 zeros(t3,c)];
% Make the complete tree: the split-node and the branches:
tree= [[j,t,2,t1+2,(p+1)/(m+c)]; tl; tr];
else
% We reached the stop criterion, so make an end-node:
[mt,cmax] = max(p);
tree = [cmax,0,0,0,(p+1)/(m+c)];
end
end
return
%MAXCRIT Maximum entropy criterion for best feature split.
%
% [f,j,t] = maxcrit(A,nlabels)
%
% Computes the value of the maximum purity f for all features over
% the data set A given its numeric labels. j is the optimum feature,
% t its threshold. This is a low level routine called for constructing
% decision trees.
%
% [1] L. Breiman, J.H. Friedman, R.A. Olshen, and C.J. Stone,
% Classification and regression trees, Wadsworth, California, 1984.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function [f,j,t] = maxcrit(a,nlab)
prtrace(mfilename);
[m,k] = size(a);
c = max(nlab);
% -variable T is an (2c)x k matrix containing:
% minimum feature values class 1
% maximum feature values class 1
% minimum feature values class 2
% maximum feature values class 2
% etc.
% -variable R (same size) contains:
% fraction of objects which is < min. class 1.
% fraction of objects which is > max. class 1.
% fraction of objects which is < min. class 2.
% fraction of objects which is > max. class 2.
% etc.
% These values are collected and computed in the next loop:
T = zeros(2*c,k); R = zeros(2*c,k);
for j = 1:c
L = (nlab == j);
if sum(L) == 0
T([2*j-1:2*j],:) = zeros(2,k);
R([2*j-1:2*j],:) = zeros(2,k);
else
T(2*j-1,:) = min(a(L,:),[],1);
R(2*j-1,:) = sum(a < ones(m,1)*T(2*j-1,:),1);
T(2*j,:) = max(a(L,:),[],1);
R(2*j,:) = sum(a > ones(m,1)*T(2*j,:),1);
end
end
% From R the purity index for all features is computed:
G = R .* (m-R);
% and the best feature is found:
[gmax,tmax] = max(G,[],1);
[f,j] = max(gmax);
Tmax = tmax(j);
if Tmax ~= 2*floor(Tmax/2)
t = (T(Tmax,j) + max(a(find(a(:,j) < T(Tmax,j)),j)))/2;
else
t = (T(Tmax,j) + min(a(find(a(:,j) > T(Tmax,j)),j)))/2;
end
return
%INFCRIT The information gain and its the best feature split.
%
% [f,j,t] = infcrit(A,nlabels)
%
% Computes over all features the information gain f for its best
% threshold from the dataset A and its numeric labels. For f=1:
% perfect discrimination, f=0: complete mixture. j is the optimum
% feature, t its threshold. This is a lowlevel routine called for
% constructing decision trees.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function [g,j,t] = infcrit(a,nlab)
prtrace(mfilename);
[m,k] = size(a);
c = max(nlab);
mininfo = ones(k,2);
% determine feature domains of interest
[sn,ln] = min(a,[],1);
[sx,lx] = max(a,[],1);
JN = (nlab(:,ones(1,k)) == ones(m,1)*nlab(ln)') * realmax;
JX = -(nlab(:,ones(1,k)) == ones(m,1)*nlab(lx)') * realmax;
S = sort([sn; min(a+JN,[],1); max(a+JX,[],1); sx]);
% S(2,:) to S(3,:) are interesting feature domains
P = sort(a);
Q = (P >= ones(m,1)*S(2,:)) & (P <= ones(m,1)*S(3,:));
% these are the feature values in those domains
for f=1:k, % repeat for all features
af = a(:,f);
JQ = find(Q(:,f));
SET = P(JQ,f)';
if JQ(1) ~= 1
SET = [P(JQ(1)-1,f), SET];
end
n = length(JQ);
if JQ(n) ~= m
SET = [SET, P(JQ(n)+1,f)];
end
n = length(SET) -1;
T = (SET(1:n) + SET(2:n+1))/2; % all possible thresholds
L = zeros(c,n); R = L; % left and right node object counts per class
for j = 1:c
J = find(nlab==j); mj = length(J);
if mj == 0
L(j,:) = realmin*ones(1,n); R(j,:) = L(j,:);
else
L(j,:) = sum(repmat(af(J),1,n) <= repmat(T,mj,1)) + realmin;
R(j,:) = sum(repmat(af(J),1,n) > repmat(T,mj,1)) + realmin;
end
end
infomeas = - (sum(L .* log10(L./(ones(c,1)*sum(L)))) ...
+ sum(R .* log10(R./(ones(c,1)*sum(R))))) ...
./ (log10(2)*(sum(L)+sum(R))); % criterion value for all thresholds
[mininfo(f,1),j] = min(infomeas); % finds the best
mininfo(f,2) = T(j); % and its threshold
end
g = 1-mininfo(:,1)';
[finfo,j] = min(mininfo(:,1)); % best over all features
t = mininfo(j,2); % and its threshold
return
%FISHCRIT Fisher's Criterion and its best feature split
%
% [f,j,t] = fishcrit(A,nlabels)
%
% Computes the value of the Fisher's criterion f for all features
% over the dataset A with given numeric labels. Two classes only. j
% is the optimum feature, t its threshold. This is a lowlevel
% routine called for constructing decision trees.
% Copyright R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function [f,j,t] = fishcrit(a,nlab)
prtrace(mfilename);
[m,k] = size(a);
c = max(nlab);
if c > 2
error('Not more than 2 classes allowed for Fisher Criterion')
end
% Get the mean and variances of both the classes:
J1 = find(nlab==1);
J2 = find(nlab==2);
u = (mean(a(J1,:),1) - mean(a(J2,:),1)).^2;
s = std(a(J1,:),0,1).^2 + std(a(J2,:),0,1).^2 + realmin;
% The Fisher ratio becomes:
f = u ./ s;
% Find then the best feature:
[ff,j] = max(f);
% Given the feature, compute the threshold:
m1 = mean(a(J1,j),1);
m2 = mean(a(J2,j),1);
w1 = m1 - m2; w2 = (m1*m1-m2*m2)/2;
if abs(w1) < eps % the means are equal, so the Fisher
% criterion (should) become 0. Let us set the thresold
% halfway the domain
t = (max(a(J1,j),[],1) + minc(a(J2,j),[],1)) / 2;
else
t = w2/w1;
end
return
%INFSTOP Quinlan's Chi-square test for early stopping
%
% crt = infstop(A,nlabels,j,t)
%
% Computes the Chi-square test described by Quinlan [1] to be used
% in maketree for forward pruning (early stopping) using dataset A
% and its numeric labels. j is the feature used for splitting and t
% the threshold.
%
% [1] J.R. Quinlan, Simplifying Decision Trees,
% Int. J. Man - Machine Studies, vol. 27, 1987, pp. 221-234.
%
% See maketree, treec, classt, prune
% Guido te Brake, TWI/SSOR, TU Delft.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function crt = infstop(a,nlab,j,t)
prtrace(mfilename);
[m,k] = size(a);
c = max(nlab);
aj = a(:,j);
ELAB = expandd(nlab);
L = sum(ELAB(aj <= t,:),1) + 0.001;
R = sum(ELAB(aj > t,:),1) + 0.001;
LL = (L+R) * sum(L) / m;
RR = (L+R) * sum(R) / m;
crt = sum(((L-LL).^2)./LL + ((R-RR).^2)./RR);
return
%PRUNEP Pessimistic pruning of a decision tree
%
% tree = prunep(tree,a,nlab,num)
%
% Must be called by giving a tree and the training set a. num is the
% starting node, if omitted pruning starts at the root. Pessimistic
% pruning is defined by Quinlan.
%
% See also maketree, treec, mapt
% Guido te Brake, TWI/SSOR, TU Delft.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function tree = prunep(tree,a,nlab,num)
prtrace(mfilename);
if nargin < 4, num = 1; end;
[N,k] = size(a);
c = size(tree,2)-4;
if tree(num,3) == 0, return, end;
w = mapping('treec','trained',{tree,num},[1:c]',k,c);
ttt=tree_map(dataset(a,nlab),w);
J = testc(ttt)*N;
EA = J + nleaves(tree,num)./2; % expected number of errors in tree
P = sum(expandd(nlab,c),1); % distribution of classes
%disp([length(P) c])
[pm,cm] = max(P); % most frequent class
E = N - pm; % errors if substituted by leave
SD = sqrt((EA * (N - EA))/N);
if (E + 0.5) < (EA + SD) % clean tree while removing nodes
[mt,kt] = size(tree);
nodes = zeros(mt,1); nodes(num) = 1; n = 0;
while sum(nodes) > n; % find all nodes to be removed
n = sum(nodes);
J = find(tree(:,3)>0 & nodes==1);
nodes(tree(J,3)) = ones(length(J),1);
nodes(tree(J,4)) = ones(length(J),1);
end
tree(num,:) = [cm 0 0 0 P/N];
nodes(num) = 0; nc = cumsum(nodes);
J = find(tree(:,3)>0);% update internal references
tree(J,[3 4]) = tree(J,[3 4]) - reshape(nc(tree(J,[3 4])),length(J),2);
tree = tree(~nodes,:);% remove obsolete nodes
else
K1 = find(a(:,tree(num,1)) <= tree(num,2));
K2 = find(a(:,tree(num,1)) > tree(num,2));
tree = prunep(tree,a(K1,:),nlab(K1),tree(num,3));
tree = prunep(tree,a(K2,:),nlab(K2),tree(num,4));
end
return
%PRUNET Prune tree by testset
%
% tree = prunet(tree,a)
%
% The test set a is used to prune a decision tree.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function tree = prunet(tree,a)
prtrace(mfilename);
[m,k] = size(a);
[n,s] = size(tree);
c = s-4;
erre = zeros(1,n);
deln = zeros(1,n);
w = mapping('treec','trained',{tree,1},[1:c]',k,c);
[f,lab,nn] = tree_map(a,w); % bug, this works only if a is dataset, labels ???
[fmax,cmax] = max(tree(:,[5:4+c]),[],2);
nngood = nn([1:n]'+(cmax-1)*n);
errn = sum(nn,2) - nngood;% errors in each node
sd = 1;
while sd > 0
erre = zeros(n,1);
deln = zeros(1,n);
endn = find(tree(:,3) == 0)'; % endnodes
pendl = max(tree(:,3*ones(1,length(endn)))' == endn(ones(n,1),:)');
pendr = max(tree(:,4*ones(1,length(endn)))' == endn(ones(n,1),:)');
pend = find(pendl & pendr); % parents of two endnodes
erre(pend) = errn(tree(pend,3)) + errn(tree(pend,4));
deln = pend(find(erre(pend) >= errn(pend))); % nodes to be leaved
sd = length(deln);
if sd > 0
tree(tree(deln,3),:) = -1*ones(sd,s);
tree(tree(deln,4),:) = -1*ones(sd,s);
tree(deln,[1,2,3,4]) = [cmax(deln),zeros(sd,3)];
end
end
return
%NLEAVES Computes the number of leaves in a decision tree
%
% number = nleaves(tree,num)
%
% This procedure counts the number of leaves in a (sub)tree of the
% tree by using num. If num is omitted, the root is taken (num = 1).
%
% This is a utility used by maketree.
% Guido te Brake, TWI/SSOR, TU Delft
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function number = nleaves(tree,num)
prtrace(mfilename);
if nargin < 2, num = 1; end
if tree(num,3) == 0
number = 1 ;
else
number = nleaves(tree,tree(num,3)) + nleaves(tree,tree(num,4));
end
return
|
github
|
jacksky64/imageProcessing-master
|
plote.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/plote.m
| 8,258 |
utf_8
|
c431f890485b05d5b57ec1142bf67d65
|
%PLOTE Plot error curves
%
% H = PLOTE(E,LINEWIDTH,S,FONTSIZE,OPTIONS)
%
% INPUT
% E Structure containing error curves (see e.g. CLEVAL)
% LINEWIDTH Line width, < 5 (default 2)
% S Plot strings
% FONTSIZE Font size, >= 5 (default 16)
% OPTIONS Character strings:
% 'nolegend' suppresses the legend plot
% 'errorbar' add errorbars to the plot
% 'noapperror' suppresses the apparent error plot
%
% OUTPUT
% H Array of graphics handles
%
% DESCRIPTION
% Various evaluation routines like CLEVAL return an error curves packed in a
% structure E. PLOTE uses the information stored in E to plot the curves. The
% remaining parameters may be given in an arbitrary order.
%
% E may contain the following fields (E.ERROR is obligatory):
% E.ERROR C x N matrix of error values for C methods at N points
% (typically errors estimated on an independent test set)
% E.XVALUES C x N matrix of measurement points; if 1 x N, it is used for
% all C curves
% E.TITLE the title of the plot
% E.XLABEL the label for the x-axis
% E.YLABEL the label for the y-axis
% E.NAMES a string array of C names used for creating a LEGEND
% E.PLOT the plot command in a string: 'plot', 'semilogx', 'semilogy'
% or 'loglog'
% E.STD C x N matrix with standard deviations of the mean error values
% which are plotted if ERRBAR == 1
% Note that this is the st. dev. in the estimate of the mean
% and not the std. dev. of the error itself.
% E.APPERROR C x N matrix of error values for C methods at N points
% (typically errors estimated on the training set)
% E.APPSTD C x N matrix with standard deviations of the mean
% APPERROR values which are plotted if ERRBAR == 1
%
% These fields are automatically set by a series of commands like CLEVAL,
% CLEVALF, ROC and REJECT.
%
% The legend generated by PLOTE can be removed by LEGEND OFF. A new legend
% may be created by the LEGEND command using the handles stored in H.
%
% E may be a cell array of structures. These structures are combined
% vertically, assuming multiple runs of the same method and
% horizontally, assuming different methods.
%
% EXAMPLES
% See PREX_CLEVAL
%
% SEE ALSO
% CLEVAL, CLEVALF, ROC, REJECT
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: plote.m,v 1.5 2009/11/26 10:45:43 davidt Exp $
function handle = plote(varargin)
prtrace(mfilename);
% Set default parameter values.
e = [];
s = [];
linewidth = 2;
nolegend = 0;
fontsize = 16;
errbar = 0;
noapperror = 0;
ss = char('k-','r-','b-','m-','k--','r--','b--','m--');
ss = char(ss,'k-.','r-.','b-.','m-.','k:','r:','b:','m:');
ss_app = char('k--','r--','b--','m--','k:','r:','b:','m:');
ss_app = char(ss_app,'k--','r--','b--','m--','k-','r-','b-','m-');
% The input is so flexible, that we have to do a lot of work...
for j = 1:nargin
p = varargin{j};
if (isstruct(p)) | iscell(p)
e = p;
elseif (isstr(p)) & (strcmp(p,'errorbar') | strcmp(p,'ERRORBAR'))
errbar = 1;
elseif (isstr(p)) & (strcmp(p,'nolegend') | strcmp(p,'NOLEGEND'))
nolegend = 1;
elseif (isstr(p)) & (strcmp(p,'noapperror') | strcmp(p,'NOAPPERROR'))
noapperror = 1;
elseif (isstr(p))
ss = p;
elseif (length(p) == 1) & (p < 5)
linewidth = p;
elseif (length(p) == 1) & (p >= 5)
fontsize = p;
end
end
if iscell(e)
if min(size(e)) > 1
ee = cell(1,size(e,2));
for j=1:size(e,2)
ee{j} = vertcomb(e(:,j));
end
e = horzcomb(ee);
elseif size(e,1) > 1
e = vertcomb(e);
elseif size(e,2) > 1
e = horzcomb(e);
else
e = e{1};
end
end
% Handle multiple plots
if length(e) > 1
names = [];
hold_stat = ishold;
h = [];
ymax = 0;
for j = 1:length(e)
if errbar & isfield(e,'std')
if noapperror
hh = plote(e(j),linewidth,ss(j,:),'nolegend','errorbar','noapperror');
else
hh = plote(e(j),linewidth,ss(j,:),'nolegend','errorbar');
end
else
if noapperror
hh = plote(e(j),linewidth,ss(j,:),'nolegend','noapperror');
else
hh = plote(e(j),linewidth,ss(j,:),'nolegend');
end
end
V = axis; ymax = max(ymax,V(4));
hold on
if ~isfield(e(j),'names')
e(j).names = ' ';
end
names = char(names,e(j).names);
h = [h; hh];
end
names(1,:) = [];
V(4) = ymax;
axis(V);
if ~nolegend
legend(h,names,0);
end
if ~hold_stat, hold off; end
if nargout > 0, handle = h; end
return
end
% Check if we have the required data and data fields.
if (isempty(e))
error('Error structure not specified.')
end
if (~isfield(e,'error'))
error('Input structure should contain the ''error''-field.');
end
n = size(e.error,1);
if (~isfield(e,'xvalues'))
e.xvalues = [1:length(e.error)];
end
if (size(e.xvalues,1) == 1)
e.xvalues = repmat(e.xvalues,n,1);
end
if (isempty(s))
if n > size(ss,1)
nn = ceil(n/size(ss,1));
ss = repmat(ss,nn,1);
ss_app = repmat(ss_app,nn,1);
end
s = ss(1:n,:);
s_app = ss_app(1:n,:);
end
if (size(s,1) == 1) & (n > 1)
s = repmat(s,n,1);
s_app = repmat(s_app,n,1);
end
if (size(s,1) < n)
error('Insufficient number of plot strings.')
end
if (~isfield(e,'plot'))
e.plot = 'plot';
end
if errbar & isfield(e,'std')
ploterrorbar = 1;
else
ploterrorbar = 0;
end
plotapperror = (~noapperror && isfield(e,'apperror'));
% We can now start making the plot.
if ~ishold
clf;
end
h = []; ha = []; % handles for true and apparent error
for j = 1:n
L = find(e.error(j,:) ~= NaN);
if ploterrorbar
hh = feval('errorbar',e.xvalues(j,L),e.error(j,L),e.std(j,L),deblank(s(j,:)));
else
hh = feval(e.plot,e.xvalues(j,L),e.error(j,L),deblank(s(j,:)));
end
set(hh,'linewidth',linewidth); hold on; h = [h hh(end)];
% and the apparent error
if plotapperror
hh = errorbar(e.xvalues(j,L),e.apperror(j,L),e.appstd(j,L),...
deblank(s_app(j,:)));
ha = [ha hh(end)];
end
end
% That was basically it, now we only have to beautify it.
errmax = max(e.error(:));
set(gca,'fontsize',fontsize);
if (isfield(e,'xlabel')), xlabel(e.xlabel); end
if (isfield(e,'ylabel')), ylabel(e.ylabel); end
if (isfield(e,'title')), title(e.title); end
if (isfield(e,'names')) & (~isempty(e.names) & (~nolegend))
if plotapperror % take care for the legend in this case
nrn = size(e.names,1);
names = {};
for j=1:nrn
names{j} = ['\epsilon ' e.names(j,:)];
%names{j} = ['true error ' e.names(j,:)];
end
for j=1:nrn
names{nrn+j} = ['\epsilon_A ' e.names(j,:)];
%names{nrn+j} = ['apparent error ' e.names(j,:)];
end
legend([h ha],strvcat(names),0);
else
legend(h,e.names,0);
end
end
% A lot of work to make the scaling of the y-axis nice.
if (errmax > 0.6)
errmax = ceil(errmax*5)/5;
yticks = [0:0.2:errmax];
elseif (errmax > 0.3)
errmax = ceil(errmax*10)/10;
yticks = [0:0.1:errmax];
elseif (errmax > 0.2)
errmax = ceil(errmax*20)/20;
yticks = [0:0.05:errmax];
elseif (errmax > 0.1)
errmax = ceil(errmax*30)/30;
yticks = [0:0.03:errmax];
elseif (errmax > 0.06)
errmax = ceil(errmax*50)/50;
yticks = [0:0.02:errmax];
elseif (errmax > 0.03)
errmax = ceil(errmax*100)/100;
yticks = [0:0.01:errmax];
else
yticks = [0:errmax/3:errmax];
end
% atttempt to beautify plot
if (e.xvalues(end) >= 2)
%DXD
%axis([e.xvalues(1)-1,e.xvalues(end)+1,0,errmax]);
axis([min(min(e.xvalues)),max(max(e.xvalues)),0,errmax]);
elseif (e.xvalues(1) == 0)
axis([-0.003,e.xvalues(end),0,errmax]);
end
set(gca,'ytick',yticks);
hold off; if (nargout > 0), handle = h; end;
return
function e = vertcomb(e) % combine cell array
e1 = e{1};
for j=2:length(e);
e2 = e{j};
v = e1.n*(e1.n*(e1.std.^2) + e1.error.^2);
v = v + e2.n*(e2.n*(e2.std.^2) + e2.error.^2);
n = e1.n + e2.n;
e1.error = (e1.n*e1.error + e2.n*e2.error)/n;
e1.std = sqrt((v/n - e1.error.^2)/n);
e1.n = n;
end
e = e1;
return
function ee = horzcomb(e) % combine cell array
for j=1:length(e)
ee(j) = e{j};
end
|
github
|
jacksky64/imageProcessing-master
|
data2im.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/data2im.m
| 3,061 |
utf_8
|
e249f7bb34cbd866b2b0767974b132cc
|
%DATA2IM Convert PRTools dataset or datafile to image
%
% IM = DATA2IM(A,J)
% IM = DATA2IM(A(J,:))
%
% INPUT
% A Dataset or datafile containing images
% J Desired images
%
% OUTPUT
% IM If A is dataset, IM is a X*Y*N*K matrix with K images.
% K is the number of images (length(J))
% N is the number of bands per image.
% N = 3 for RGB images, N = 1 for gray value images.
%
% If A is a datafile, IM is a cell array of K images.
%
% DESCRIPTION
% An image, or a set of images stored in the objects or features of the
% dataset A are retrieved and returned as a 3D matrix IM. In case A is a
% datafile the images are stored in a cell array, except when a single
% image is requested.
%
% SEE ALSO
% DATASETS, IM2OBJ, IM2FEAT
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: data2im.m,v 1.13 2010/02/03 13:17:17 duin Exp $
function im = data2im(a,J)
prtrace(mfilename);
if nargin > 1, a = a(J,:); end
if isdatafile(a)
m = size(a,1);
im = cell(1,m);
s = sprintf('Unpacking %i images: ',m);
prwaitbar(m,s);
for j=1:m
prwaitbar(m,j,[s int2str(j)]);
%im{j} = readdatafile(a,1,0);
im{j} = feval(mfilename,dataset(a(j,:)));
end
prwaitbar(0);
if m==1
im = im{1};
end
return
end
%a = testdatasize(a); % Oeps, datafiles are first converted to datasets
% and then to images. This can be done better!
%isdataim(a); % Assert that A contains image(s).
data = +a; % Extract data from dataset, for computational advantage.
[m,k] = size(a); [objsize,featsize] = get(a,'objsize','featsize');
% Reshape data into output array.
if (isfeatim(a))
% A contains K images stored as features (each object is a pixel).
if length(objsize) == 1
im = zeros(1,objsize(1),k);
for j = 1:k
im(1,:,j) = reshape(data(:,j),1,objsize(1));
end
elseif length(objsize) == 2
im = zeros(objsize(1),objsize(2),k);
for j = 1:k
im(:,:,j) = reshape(data(:,j),objsize(1),objsize(2));
end
elseif length(objsize) == 3
im = zeros(objsize(1),objsize(2),k,objsize(3));
for j = 1:k
im(:,:,j,:) = reshape(data(:,j),objsize(1),objsize(2),objsize(3));
end
else
error('Unable to handle these images')
end
else
% A contains M images stored as objects (each feature is a pixel).
if length(featsize) == 1
im = zeros(1,featsize(1),1,m);
for j = 1:m
im(1,:,1,j) = reshape(data(j,:),1,featsize(1));
end
elseif length(featsize) == 2
im = zeros(featsize(1),featsize(2),1,m);
for j = 1:m
im(:,:,1,j) = reshape(data(j,:),featsize(1),featsize(2));
end
elseif length(featsize) == 3
im = zeros(featsize(1),featsize(2),featsize(3),m);
for j = 1:m
im(:,:,:,j) = reshape(data(j,:),featsize(1),featsize(2),featsize(3));
end
else
error('Unable to handle these images')
end
%im = squeeze(im); % some routines, like filtim, fail by squeezing
end
return
|
github
|
jacksky64/imageProcessing-master
|
lkc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/lkc.m
| 3,252 |
utf_8
|
5e29d726e68a367e8bc996a32c8cc158
|
%LKC Linear kernel classifier
%
% W = LKC(A,KERNEL)
%
% INPUT
% A Dataset
% KERNEL Mapping to compute kernel by A*MAP(A,KERNEL)
% or string to compute kernel by FEVAL(KERNEL,A,A)
% or cell array with strings and parameters to compute kernel by
% FEVAL(KERNEL{1},A,A,KERNEL{2:END})
% Default: linear kernel (PROXM([],'P',1))
%
% OUTPUT
% W Mapping: Support Vector Classifier
%
% DESCRIPTION
% This is a fall-back routine for other kernel procedures like SVC, RBSVC
% and LIBSVC. If they fail due to optimization problems they may fall back
% to this routine which computes a linear classifier in kernelspace using
% they pseudo-inverse of the kernel.
%
% The kernel may be supplied in KERNEL by
% - an untrained mapping, e.g. a call to PROXM like W = LIBSVC(A,PROXM([],'R',1))
% - a string with the name of the routine to compute the kernel from A
% - a cell-array with this name and additional parameters.
% This will be used for the evaluation of a dataset B by B*W or MAP(B,W) as
% well.
%
% If KERNEL = 0 it is assumed that A is already the kernel matrix (square).
% In this also a kernel matrix should be supplied at evaluation by B*W or
% MAP(B,W).
%
% SEE ALSO
% MAPPINGS, DATASETS, SVC, PROXM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function W = lkc(a,kernel)
prtrace(mfilename);
if nargin < 2 | isempty(kernel)
kernel = proxm([],'p',1);
end
if nargin < 1 | isempty(a)
W = mapping(mfilename,{kernel});
W = setname(W,'LKC Classifier');
return;
end
if (~ismapping(kernel) | isuntrained(kernel)) % training
islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a,'objects');
[m,k,c] = getsize(a);
nlab = getnlab(a);
K = compute_kernel(a,a,kernel);
K = min(K,K'); % make sure kernel is symmetric
targets = gettargets(setlabtype(a,'targets'));
v = prpinv([K ones(m,1); ones(1,m) 0])*[targets; zeros(1,c)];
lablist = getlablist(a);
W = mapping(mfilename,'trained',{v,a,kernel},lablist,size(a,2),c);
W = setname(W,'LKC Classifier');
W = cnormc(W,a);
W = setcost(W,a);
else % execution
w = kernel;
v = getdata(w,1); % weights
s = getdata(w,2); % trainset or empty
kernel = getdata(w,3); % kernelfunction or 0
m = size(a,1);
K = compute_kernel(a,s,kernel); % kernel testset
% Data is mapped by the kernel, now we just have a linear
% classifier w*x+b:
d = [K ones(m,1)]*v;
if size(d,2) == 1, d = [d -d]; end
W = setdat(a,d,w);
end
return;
function K = compute_kernel(a,s,kernel)
% compute a kernel matrix for the objects a w.r.t. the support objects s
% given a kernel description
if isstr(kernel) % routine supplied to compute kernel
K = feval(kernel,a,s);
elseif iscell(kernel)
K = feval(kernel{1},a,s,kernel{2:end});
elseif ismapping(kernel)
K = a*map(s,kernel);
elseif kernel == 0 % we have already a kernel
K = a;
else
error('Do not know how to compute kernel matrix')
end
K = +K;
return
|
github
|
jacksky64/imageProcessing-master
|
feateval.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/feateval.m
| 5,360 |
utf_8
|
574c3145ddb5fb970c464b329f8d8a60
|
%FEATEVAL Evaluation of feature set for classification
%
% J = FEATEVAL(A,CRIT,T)
% J = FEATEVAL(A,CRIT,N)
%
% INPUT
% A input dataset
% CRIT string name of a method or untrained mapping
% T validation dataset (optional)
% N number of cross-validations (optional)
%
% OUTPUT
% J scalar criterion value
%
% DESCRIPTION
% Evaluation of features by the criterion CRIT, using objects in the
% dataset A. The larger J, the better. Resulting J-values are
% incomparable over the various methods.
% The following methods are supported:
%
% crit='in-in' : inter-intra distance.
% crit='maha-s': sum of estimated Mahalanobis distances.
% crit='maha-m': minimum of estimated Mahalanobis distances.
% crit='eucl-s': sum of squared Euclidean distances.
% crit='eucl-m': minimum of squared Euclidean distances.
% crit='NN' : 1-Nearest Neighbour leave-one-out
% classification performance (default).
% (performance = 1 - error).
% crit='mad' : mean absolute deviation (only for regression!)
% crit='mse' : mean squared error (only for regression!)
%
% For classification problems, CRIT can also be any untrained
% classifier, e.g. LDC([],1e-6,1e-6). Then the classification error is
% used for a performance estimate. If supplied, the dataset T is used
% for obtaining an unbiased estimate of the performance of classifiers
% trained with the dataset A. If a number of cross-validations N is
% supplied, the routine is run for N times with different training and
% test sets generated from A by cross-validation. Results are averaged.
% If T nor N are given, the apparent performance on A is used.
%
% SEE ALSO
% DATASETS, FEATSELO, FEATSELB, FEATSELF, FEATSELP, FEATSELM, FEATRANK
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% REVISIONS
% DXD1: David Tax, 08-05-2003
% I added the inter/intra distance criterion.
% DXD2: David Tax, 10-06-2011
% I added the MAD and MSE criteria for regression.
% $Id: feateval.m,v 1.11 2010/02/08 15:31:48 duin Exp $
function J = feateval(a,crit,t)
prtrace(mfilename);
[ma,k,c] = getsize(a);
if nargin < 2
crit = 'NN';
end
if nargin < 3
t =[];
prwarning(4,'Where needed, input dataset is used for validation')
end
if is_scalar(t) & ~isdataset(t) % cross-validation desired, t rotations
% Why is it programmed like this ?????
%
% K = crossval(a,nmc,t,0); % trick to get rotation set from crossval
% J = 0;
% JALL = [1:size(a,1)];
% if ~ismapping(crit) | ~isuntrained(crit)
% error('Cross-validation only possible with untrained classifiers')
% end
% for j=1:t
% JIN = JALL;
% JOUT = find(K==j);
% JIN(JOUT) = [];
% JOUT = JALL(JOUT);
% train = a(JIN,:);
% test = a(JOUT,:);
% J = J + feval(mfilename,train,crit,test);
% end
% J = J/t;
% return
% end
%
% Let us do it simpel:
if ~ismapping(crit) | ~isuntrained(crit)
error('Cross-validation only possible with untrained classifiers')
end
J = 1-crossval(a,crit,t);
return
end
% islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a);
iscomdset(a,t);
if isstr(crit)
%DXD1
if strcmp(crit,'in-in') % inter/intra distances
islabtype(a,'crisp','soft');
if isempty(t)
[U,G] = meancov(a);
else
[U,G] = meancov(t);
end
S_b = prcov(+U); % between scatter
prior = getprior(a);
S_w = reshape(sum(reshape(G,k*k,c)*prior',2),k,k); % within scatter
J = trace(prinv(S_w)*S_b);
elseif strcmp(crit,'maha-s') | strcmp(crit,'maha-m') % Mahalanobis distances
islabtype(a,'crisp','soft');
if isempty(t)
D = distmaha(a);
else
[U,G] = meancov(a);
D = distmaha(t,U,G);
D = meancov(D);
end
if strcmp(crit,'maha-m')
D = D + realmax*eye(c);
J = min(min(D));
else
J = sum(sum(D))/2;
end
elseif strcmp(crit,'eucl-s') | strcmp(crit,'eucl-m') % Euclidean distances
islabtype(a,'crisp','soft');
U = meancov(a);
if isempty(t)
D = distm(U);
else
D = distm(t,U);
D = meancov(D);
end
if strcmp(crit,'eucl-m')
D = D + realmax*eye(c);
J = min(min(D));
else
J = sum(sum(D))/2;
end
elseif strcmp(crit,'NN') % 1-NN performance
islabtype(a,'crisp','soft');
if isempty(t)
J = 1 - testk(a,1);
else
J = 1 - testk(a,1,t);
end
elseif strcmp(crit,'kcentres') % data radius, unsupervised
% assumes disrep, so experimental
J = max(min(+a,[],2));
if J == 0, J = inf; else J = 1/J; end
elseif strcmp(crit,'representation_error') % also unsupervised
J = mean(min(+a,[],2));
if J == 0, J = inf; else J = 1/J; end
elseif strcmp(crit,'mad') % Mean Absolute Deviation for regression
J = 1-testr(a*linearr(a,0.001,1),'mad');
elseif strcmp(crit,'mse') % Mean Squared Error for regression
J = 1-testr(a*linearr(a,0.001,1),'mse');
else
error('Criterion undefined');
end
else
ismapping(crit);
if isuntrained(crit)
if isempty(t)
J = 1 - (a * (a * crit) * testc);
else
J = 1 - (t * (a * crit) * testc);
end
elseif isfixed(crit)
J = a * crit;
else
error('Criterion should be defined by an untrained or fixed mapping')
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
dcsc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/dcsc.m
| 7,568 |
utf_8
|
e21c176dfd20be277f7484f749f2319b
|
% DCSC Dynamic Classifier Selection Combiner
%
% V = DCSC(A,W,K,TYPE)
% V = A*(W*DCSC([],K,TYPE))
% D = B*V
%
% INPUT
% A Dataset used for training base classifiers as well as combiner
% B Dataset used for testing (executing) the combiner
% W Set of trained or untrained base classifiers
% K Integer, number of neighbors
% TYPE 'soft' (default) or 'crisp'
%
% OUTPUT
% V Trained Dynamic Classifier Selection
% D Dataset with prob. products (over base classifiers) per class
%
% DESCRIPTION
% This dynamic classifier selection takes for every object to be
% classified the K nearest neighbors of an evaluation set (training set) A
% and determines which classifier performs best over this set of objects.
% If the base classifiers (STACKED or PARALLEL) are untrained, A is used to
% train them as well.
%
% The selection of the best classifier can be made in a soft or in a crisp
% way. If TYPE is 'soft' (default) classifier confidences are averaged (see
% CLASSC), otherwise the best classifier is selected by voting.
%
% REFERENCE
% G. Giacinto and F. Roli, Methods for Dynamic Classifier Selection
% 10th Int. Conf. on Image Anal. and Proc., Venice, Italy (1999), 659-664.
%
% SEE ALSO
% DATASETS, MAPPINGS, STACKED, NAIVEBC, CLASSC, TESTD, LABELD
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function OUT = dcsc(par1,par2,par3,par4)
prtrace(mfilename);
name = 'Dynamic Classifier Selection';
DefaultNumNeigh = 20;
DefaultType = 'soft';
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Empty Call DCSC, DCSC([],K,TYPE)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
if nargin < 1 | isempty(par1)
if nargin < 3 | isempty(par3), par3 = DefaultType; end
if nargin < 2 | isempty(par2), par2 = DefaultNumNeigh; end
% If there are no inputs, return an untrained mapping.
% (PRTools transfers the latter into the first)
OUT = mapping(mfilename,'combiner',{par2,par3});
OUT = setname(OUT,name);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Storing Base Classifiers: W*DCSC, DCSC(W,K,TYPE)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif ismapping(par1)
if nargin < 3 | isempty(par3), par3 = DefaultType; end
if nargin < 2 | isempty(par2), par2 = DefaultNumNeigh; end
% call like OUT = DCSC(W,k) or OUT = W*DCSC([],k)
% store trained or untrained base classifiers,
% ready for later training of the combiner
BaseClassf = par1;
if ~isparallel(BaseClassf) & ~isstacked(BaseClassf)
error('Parallel or stacked set of base classifiers expected');
end
if ~(isa(par2,'double') & length(par2)==1 & isint(par2))
error('Number of neighbors should be integer scalar')
end
OUT = mapping(mfilename,'untrained',{BaseClassf,par2,par3});
OUT = setname(OUT,name);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Training Combiner (and base classifiers if needed):
% A*(W*DCSC), A*(W*DCSC([],K,TYPE)), DCSC(A,W,K,TYPE)
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif isdataset(par1) & ismapping(par2) & ...
(isuntrained(par2) | (istrained(par2) & (isstacked(par2) | isparallel(par2))))
% call like OUT = DCSC(TrainSet,W,k,type) or TrainSet*(W*DCSC([],k,type))
% (PRTools transfers the latter into the first)
% W is a set of trained or untrained set classifiers.
if nargin < 4 | isempty(par4), par4 = DefaultType; end
if nargin < 3 | isempty(par3), par3 = DefaultNumNeigh; end
TrainSet = par1;
BaseClassf = par2;
islabtype(TrainSet,'crisp'); % allow crisp labels only
isvaldfile(TrainSet,1,2); % at least one object per class, 2 classes
TrainSet = setprior(TrainSet,getprior(TrainSet,0)); % avoid many warnings
if ~(isstacked(BaseClassf) | isparallel(BaseClassf))
if iscombiner(BaseClassf)
error('No base classifiers found')
end
Data = getdata(BaseClassf);
BaseClassf = Data.BaseClassf; % base classifiers were already stored
end
if isuntrained(BaseClassf) % base classifiers untrained, so train them!
BaseClassf = TrainSet*BaseClassf;
n = length(getdata(BaseClassf));
else % base classifiers are trained, just check label lists
BaseClassifiers = getdata(BaseClassf);
n = length(BaseClassifiers);
for j=1:n
if ~isequal(getlabels(BaseClassifiers{j}),getlablist(TrainSet))
error('Training set and base classifiers should deal with same labels')
end
end
end
Data.BaseClassf = BaseClassf;
if nargin > 2 % overrules previously defined k (NumNeigh)
Data.NumNeigh = par3;
end
if nargin > 3 % overrules previously defined type
if strcmp(par4,'soft')
Data.SoftVote = 1;
else
Data.SoftVote = 0;
end
end
% Let us determine for every object in the trainingset how good it is
% classified by every base classifier
[m,p,c] = getsize(TrainSet);
%n = size(BaseClassf,2)/c; % nr. of base classifiers
ClassTrain1 = reshape(+(TrainSet*BaseClassf),m,c,n);
ClassTrain2 = zeros(m,n);
for j=1:n
ct = ClassTrain1(:,:,j)*normm;
ct = ct(sub2ind([m,c],[1:m]',[getnlab(TrainSet)]));
ClassTrain2(:,j) = ct;
end
if ~Data.SoftVote % find crisp outcomes
[cmax,L] = max(ClassTrain2,[],2);
ClassTrain2 = zeros(m,n);
ClassTrain2(sub2ind([m,n],[1:m]',L)) = ones(length(L),1);
end
Data.ClassTrain = ClassTrain2;
Data.TrainSet = TrainSet;
OUT = mapping(mfilename,'trained',Data,getlablist(TrainSet),size(TrainSet,2),getsize(TrainSet,3));
OUT = setname(OUT,name);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Evaluation of the trained combiner V: B*V, DCSC(B,V,K)
% TYPE cannot be changed anymore
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
elseif isdataset(par1) & ismapping(par2) & istrained(par2)
if nargin < 3 | isempty(par3), par3 = DefaultNumNeigh; end
TestSet = par1;
BaseClassf = getdata(par2,'BaseClassf');
TrainSet = getdata(par2,'TrainSet');
[m,p,c] = getsize(TrainSet);
n = size(BaseClassf,2)/c; % nr. of base classifiers
if nargin > 2
k = par3;
else
k = getdata(par2,'NumNeigh');
end
D = distm(TestSet,TrainSet); % disputable procedure for parallel base classifiers
[dd,J] = sort(+D,2); % J stores the numeric labels of the nearest training objects
ClassPerf = zeros(size(TestSet,1),n); % base classifier performances per testobject
TestSize = size(TestSet,1);
N = [1:TestSize];
kk = k;
ClassTrain = getdata(par2,'ClassTrain');
while ~isempty(N) & kk > 0
for j=1:n % find for every testobject and for all classifiers the mean
% performance (i.e. the mean of the correct class assignments) over
% its neighborhood
ClassPerf(:,j) = mean(reshape(ClassTrain(J(:,1:kk),j),TestSize,kk),2);
end
[cc,L(N,:)] = sort(-ClassPerf(N,:),2);
NN = find(cc(:,1) == cc(:,2)); % solve ties
N = N(NN); % select objects that suffer from ties
kk = kk-1; % try once more with smaller set of neighbors
end
U = getdata(BaseClassf);
d = zeros(TestSize,c);
feats = 0; % counter to find feature numbers for parallel classifiers
for j=1:n
featsize = size(U{j},1);
Lj = find(L(:,1)==j);
if ~isempty(Lj)
if isparallel(BaseClassf) % retrieve features for parallel classifiers
d(Lj,:) = +(TestSet(Lj,feats+1:feats+featsize)*U{j});
else
d(Lj,:) = +(TestSet(Lj,:)*U{j});
end
end
feats = feats+featsize;
end
OUT = setdat(TestSet,d,par2);
else
error('Illegal input');
end
|
github
|
jacksky64/imageProcessing-master
|
gendatm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatm.m
| 1,444 |
utf_8
|
052286de99e508d15b878b8079f7d6c7
|
%GENDATM Generation of multi-class 2-D data
%
% A = GENDATM(N)
%
% INPUT
% N Vector of class sizes (default: 20)
%
% OUTPUT
% A Dataset
%
% DESCRIPTION
% Generation of N samples in 8 classes of 2 dimensionally distributed data
% vectors. Classes have equal prior probabilities. If N is a vector of
% sizes, exactly N(I) objects are generated for class I, I = 1..8.
%
% SEE ALSO
% DATASETS, PRDATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: gendatm.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function a = gendatm(n)
prtrace(mfilename);
if (nargin == 0)
prwarning(3,'number of samples to generate not specified, assuming 20');
n = repmat(20,1,8);
end;
% Set equal priors and generate a class distribution according to it.
p = repmat(1/8,1,8); n = genclass(n,p);
% Generate 8 classes...
a1 = +gendath(n(1:2)); % ...first 2 classes: Highleyman data.
a2 = +gendatc(n(3:4))./5; % ...next 2 classes : spherical classes.
a3 = +gendatb(n(5:6))./5; % ...next 2 classes : banana data.
a4 = +gendatl(n(7:8))./5; % ...next 2 classes : Lithuanian data.
% Glue classes together with some proper offsets.
a = [a1; a2+5; a3+repmat([5,0],n(5)+n(6),1); a4+repmat([0 5],n(7)+n(8),1)];
lab = genlab(n,['a';'b';'c';'d';'e';'f';'g';'h']);
a = dataset(a,lab,'name','Multi-Class Problem');
return
|
github
|
jacksky64/imageProcessing-master
|
crossval.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/crossval.m
| 8,860 |
utf_8
|
0fd850193167e8858f4201c769c67060
|
%CROSSVAL Error/performance estimation by cross validation (rotation)
%
% [ERR,CERR,NLAB_OUT] = CROSSVAL(A,CLASSF,NFOLDS,1,TESTFUN)
% [ERR,STDS] = CROSSVAL(A,CLASSF,NFOLDS,NREP,TESTFUN)
% [ERR,CERR,NLAB_OUT] = CROSSVAL(A,CLASSF,NFOLDS,'DPS',TESTFUN)
% R = CROSSVAL(A,[],NFOLDS,0)
%
% INPUT
% A Input dataset
% CLASSF The untrained classifier to be tested.
% NFOLDS Number of folds
% (default: number of samples: leave-one-out)
% NREP Number of repetitions (default: 1)
% TESTFUN Mapping,evaluation function (default classification error)
%
% OUTPUT
% ERR Average test error or performance weighted by class priors.
% CERR Unweighted test errors or performances per class
% NLAB_OUT Assigned numeric labels
% STDS Standard deviation over the repetitions.
% R Index array with rotation set
%
% DESCRIPTION
% Cross validation estimation of the error or performance (defined by TESTFUN)
% of the untrained classifier CLASSF using the dataset A. The set is randomly
% permutated and divided in NFOLDS (almost) equally sized parts, using a
% stratified procedure. The classifier is trained on NFOLDS-1 parts and the
% remaining part is used for testing. This is rotated over all parts. ERR
% is
% their weighted avarage over the class priors. CERR are the class error
% frequencies. The inputs A and/or CLASSF may be cell arrays of datasets and
% classifiers. In that case ERR is an array with on position ERR(i,j) the
% error or performance of classifier j for dataset i. In this mode CERR and
% NLAB_OUT are returned in cell arrays.
%
% For NREP > 1 the mean error(s) over the repetitions is returned in ERR
% and the standard deviations in the observed errors in STDS.
%
% If NREP == 'DPS', crossvalidation is done by density preserving data
% splitting (DPS). In this case NFOLD should be a power of 2.
%
% In case NREP == 0 an index array is returned pointing to a fold for every
% object. No training or testing is done. This is useful for handling
% training and testing outside CROSSVAL.
%
% REFERENCES
% 1. R. Kohavi: A Study of Cross-Validation and Bootstrap for Accuracy
% Estimation and Model Selection. IJCAI 1995: 1137-1145.
% 2. H. Larochelle and Y. Bengio. Classification using Discriminative Restricted
% Boltzmann Machines. Proceedings of the 25th International Conference on
% Machine Learning (ICML), pages 536-543, 2008.
%
% SEE ALSO
% DATASETS, MAPPINGS, DPS, CLEVAL, TESTC
% Copyright: D.M.J. Tax, R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: crossval.m,v 1.16 2010/06/25 07:55:34 duin Exp $
function [err,cerr,nlabout,tclassf,tress] = crossval(data,classf,n,nrep,testf,fid)
prtrace(mfilename);
if nargin < 6, fid = []; end
if nargin < 5, testf = []; end
if nargin < 4, nrep = []; end
if nargin < 3, n = []; end
if ~ismapping(testf) & isempty(fid) % correct for old call without testf
fid = testf; testf = [];
end
if iscell(data) % generate prior warnings now
for j=1:length(data)
data{j} = setprior(data{j},getprior(data{j}));
end
else
data = setprior(data,getprior(data));
end
warnlevel = prwarning;
prwarning(0);
% datasets or classifiers are cell arrays
if iscell(classf) | iscell(data)
seed = rand('state');
if ~iscell(classf), classf = {classf}; end
if ~iscell(data), data = {data}; end
if isdataset(classf{1}) & ismapping(data{1}) % correct for old order
dd = data; data = classf; classf = dd;
end
numc = length(classf);
numd = length(data);
cerr = cell(numd,numc);
if nargout > 3
if isempty(nrep)
tclassf=cell(n,1,numc,numd);
tress =cell(n,1,numc,numd);
else
tclassf=cell(n,nrep,numc,numd);
tress =cell(n,nrep,numc,numd);
end
end
nlab_out = cell(numd,numc);
s1 = sprintf('crossval: %i classifiers: ',numc);
prwaitbar(numc,s1);
e = zeros(numd,numc);
for jc = 1:numc % Run over a set of classifiers
%disp(['classifier ' num2str(jc)])
prwaitbar(numc,jc,[s1 getname(classf{jc})]);
s2 = sprintf('crossval: %i datasets: ',numd);
prwaitbar(numd,s2);
for jd = 1:numd % Run over a set of datasets
prwaitbar(numd,jd,[s2 getname(data{jd})]);
rand('state',seed);
if nargout > 3 % store resulting classifiers
[ee,cc,nn,tclassf(:,:,jc,jd),tress(:,:,jc,jd)] = feval(mfilename,data{jd},classf{jc},n,nrep,testf);
else
[ee,cc,nn] = feval(mfilename,data{jd},classf{jc},n,nrep,testf);
end
e(jd,jc) = ee;
cerr(jd,jc) = {cc};
nlabout(jd,jc) = {nn};
end
prwaitbar(0);
end
prwaitbar(0);
if nrep > 1, cerr = cell2mat(cerr); nlabout = NaN; end
if nargout == 0
fprintf('\n %i-fold cross validation result for',n);
disperror(data,classf,e);
end
if nargout > 0, err = e; end
else % single dataset, single classifier
data = setprior(data,getprior(data)); % just to generate warning when needed
if isempty(nrep), nrep = 1; end
if isstr(nrep)
if ~islabtype(data,'crisp')
error('Density preserving splitting only upported for crisp labeled datasets')
end
if strcmp(lower(nrep),'dps')
proc = 'dps'; nrep = 1;
else
error('Sampling procedure not found')
end
elseif islabtype(data,'crisp')
proc = 'stratified';
else
proc = 'straight';
end
if nrep > 1
s3 = sprintf('crossval: %i repetitions: ',nrep);
prwaitbar(nrep,s3);
ee = zeros(1,nrep);
for j=1:nrep
prwaitbar(nrep,j,[s3 int2str(j)]);
if nargout > 3
[ee(j),ss,nlabout,tclassf(:,j,1,1),tress(:,j,1,1)] = feval(mfilename,data,classf,n,1,testf);
else
[ee(j),ss,nlabout] = feval(mfilename,data,classf,n,1,testf);
end
end
prwaitbar(0);
err = mean(ee);
cerr = std(ee);
nlabout = NaN;
prwarning(warnlevel);
return
end
if isdataset(classf) & ismapping(data) % correct for old order
dd = data; data = classf; classf = dd;
end
isdataset(data);
if nrep > 0, ismapping(classf); end
[m,k,c] = getsize(data);
lab = getlab(data);
if isempty(n), n = m; end
if n == m & ~isempty(testf)
error('No external error routine allowed in case of leave-one-out cross validation')
end
if n > m
warning('Number of folds too large: reset to leave-one-out')
n = m;
elseif n <= 1
error('Wrong size for number of cross-validation batches')
end
if (nrep > 0 & ~isuntrained(classf))
error('Classifier should be untrained')
end
J = randperm(m);
N = classsizes(data);
% attempt to find an more equal distribution over the classes
if strcmp(proc,'stratified')
if all(N >= n) & (c>1)
K = zeros(1,m);
for i = 1:length(N)
L = findnlab(data(J,:),i);
M = mod(0:N(i)-1,n)+1;
K(L) = M;
end
else
K = mod(1:m,n)+1;
end
elseif strcmp(proc,'dps')
J = [1:m];
ndps = floor(log2(n));
if n~=2^ndps
error('Number of folds should be power of 2')
end
K = dps(data,ndps);
else
K = mod(1:m,n)+1;
end
nlabout = zeros(m,1);
if nrep == 0 % trick to return rotation set
err = zeros(1,m);
err(J) = K;
prwarning(warnlevel);
return
end
f = zeros(n,1);
tress = zeros(size(data,1),getsize(data,3));
s4 = sprintf('crossval, %i-folds: ',n);
prwaitbar(n,s4);
for i = 1:n
prwaitbar(n,i,[s4 int2str(i)]);
%disp(['fold ',num2str(i)]);
OUT = find(K==i);
JOUT=J(OUT);
JIN = J; JIN(OUT) = [];
train_data = data(JIN,:);
%train_data = setprior(train_data,getprior(train_data));
w = train_data*classf; % training
% testing
if nargout > 3
tclassf(i,1,1,1) = {w};
end
testres = data(JOUT,:)*w;
if nargout > 4
tress(JOUT,:) = testres;
end
if ~isempty(testf)
f(i) = testres*testf;
end
testout = testres*maxc;
[mx,nlabout(JOUT)] = max(+testout,[],2);
% nlabout contains class assignments
end
prwaitbar(0);
%correct for different order of lablist and labels assigned by
%classifier. Assume this is constant over folds.
if (c>1) % we are dealing with a classifier
nlist = renumlab(getfeatlab(testout),getlablist(data));
nlabout = nlist(nlabout);
if isempty(testf)
f = zeros(1,c);
for j=1:c
J = findnlab(data,j);
f(j) = sum(nlabout(J)~=j)/length(J);
end
e = f*getprior(data,0)';
else
e = mean(f); % f already weighted by class priors inside testf
end
else % we are dealing with a regression problem
e = mean(f);
end
if nargout > 0
err = e;
if isempty(testf)
cerr = f;
else
cerr = [];
nlabout = [];
end
else
disp([num2str(n) '-fold cross validation error on ' num2str(size(data,1)) ' objects: ' num2str(e)])
end
end
prwarning(warnlevel);
return
|
github
|
jacksky64/imageProcessing-master
|
featsetc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featsetc.m
| 323 |
utf_8
|
af3d4cb5cf54ec2cf01ef80386e579cc
|
%FEATSETC Set classifier
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [out1,out2] = featsetc(a,objclassf,fsetindex,fsetcombc,fsetclassf,fsetlab)
error('featsetc has been replaced by bagc')
|
github
|
jacksky64/imageProcessing-master
|
baggingc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/baggingc.m
| 2,478 |
utf_8
|
e1527f453891053e0d7cc405f8973486
|
%BAGGINGC Bootstrapping and aggregation of classifiers
%
% W = BAGGINGC (A,CLASSF,N,ACLASSF,T)
%
% INPUT
% A Training dataset.
% CLASSF The base classifier (default: nmc)
% N Number of base classifiers to train (default: 100)
% ACLASSF Aggregating classifier (default: meanc), [] for no aggregation.
% T Tuning set on which ACLASSF is trained (default: [], meaning use A)
%
% OUTPUT
% W A combined classifier (if ACLASSF was given) or a stacked
% classifier (if ACLASSF was []).
%
% DESCRIPTION
% Computation of a stabilised version of a classifier by bootstrapping and
% aggregation ('bagging'). In total N bootstrap versions of the dataset A
% are generated and used for training of the untrained classifier CLASSF.
% Aggregation is done using the combining classifier specified in CCLASSF.
% If ACLASSF is a trainable classifier it is trained by the tuning dataset
% T, if given; else A is used for training. The default aggregating classifier
% ACLASSF is MEANC. Default base classifier CLASSF is NMC.
%
% SEE ALSO
% DATASETS, MAPPINGS, NMC, MEANC, BOOSTINGC
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: baggingc.m,v 1.3 2010/06/01 08:47:05 duin Exp $
function w = baggingc (a,clasf,n,rule,t)
prtrace(mfilename);
if (nargin < 5),
prwarning(2,'no tuning set supplied, using training set for tuning (risk of overfit)');
t = [];
end
if (nargin < 4)
prwarning(2,'aggregating classifier not specified, assuming meanc');
rule = meanc;
end
if (nargin < 3) | isempty(n),
prwarning(2,'number of repetitions not specified, assuming 100');
n = 100;
end
if (nargin < 2) | isempty(clasf),
prwarning(2,'base classifier not specified, assuming nmc');
clasf = nmc;
end
if ((nargin < 1) | isempty(a))
w = mapping('baggingc',{clasf,n,rule});
return
end
iscomdset(a,t); % test compatibility training and tuning set
% Concatenate N classifiers on bootstrap samples (100%) taken
% from the training set.
w = [];
for i = 1:n
w = [w gendat(a)*clasf];
end
% If no aggregating classifier is given, just return the N classifiers...
if (~isempty(rule))
% ... otherwise, train the aggregating classifier on the train or
% tuning set.
if (isempty(t))
w = traincc(a,w,rule);
else
w = traincc(t,w,rule);
end
end
w = setcost(w,a);
return
|
github
|
jacksky64/imageProcessing-master
|
svo_nu.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/svo_nu.m
| 3,962 |
utf_8
|
396fa04268e3a40213f79e02eb83ee67
|
%SVO_NU Support Vector Optimizer: NU algorithm
%
% [V,J,C] = SVO(K,NLAB,NU,PD)
%
% INPUT
% K Similarity matrix
% NLAB Label list consisting of -1/+1
% NU Regularization parameter (0 < NU < 1): expected fraction of SV (optional; default: 0.25)
%
% PD Do or do not the check of the positive definiteness (optional; default: 1 (to do))
%
% OUTPUT
% V Vector of weights for the support vectors
% J Index vector pointing to the support vectors
% C Equivalent C regularization parameter of SVM-C algorithm
%
% DESCRIPTION
% A low level routine that optimizes the set of support vectors for a 2-class
% classification problem based on the similarity matrix K computed from the
% training set. SVO is called directly from SVC. The labels NLAB should indicate
% the two classes by +1 and -1. Optimization is done by a quadratic programming.
% If available, the QLD function is used, otherwise an appropriate Matlab routine.
%
% NU is bounded from above by NU_MAX = (1 - ABS(Lp-Lm)/(Lp+Lm)), where
% Lp (Lm) is the number of positive (negative) samples. If NU > NU_MAX is supplied
% to the routine it will be changed to the NU_MAX.
%
% If NU is less than some NU_MIN which depends on the overlap between classes
% algorithm will typically take long time to converge (if at all).
% So, it is advisable to set NU larger than expected overlap.
%
% Weights V are rescaled in a such manner as if they were returned by SVO with the parameter C.
%
% SEE ALSO
% SVC_NU, SVO, SVC
% Copyright: S.Verzakov, [email protected]
% Based on SVO.M by D.M.J. Tax, D. de Ridder, R.P.W. Duin
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: svo_nu.m,v 1.3 2010/02/08 15:29:48 duin Exp $
function [v,J,C] = svo_nu(K,y,nu,pd)
prtrace(mfilename);
if (nargin < 4)
pd = 1;
end
if (nargin < 3)
prwarning(3,'Third parameter (nu) not specified, assuming 0.25.');
nu = 0.25;
end
nu_max = 1 - abs(nnz(y == 1) - nnz(y == -1))/length(y);
if nu > nu_max
prwarning(3,['nu==' num2str(nu) ' is not feasible; set to ' num2str(nu_max)]);
nu = nu_max;
end
vmin = 1e-9; % Accuracy to determine when an object becomes the support object.
% Set up the variables for the optimization.
n = size(K,1);
D = (y*y').*K;
f = zeros(1,n);
A = [y';ones(1,n)];
b = [0; nu*n];
lb = zeros(n,1);
ub = ones(n,1);
p = rand(n,1);
if pd
% Make the kernel matrix K positive definite.
i = -30;
while (pd_check (D + (10.0^i) * eye(n)) == 0)
i = i + 1;
end
if (i > -30),
prwarning(2,'K is not positive definite. The diagonal is regularized by 10.0^(%d)*I',i);
end
i = i+2;
D = D + (10.0^(i)) * eye(n);
end
% Minimization procedure initialization:
% 'qp' minimizes: 0.5 x' D x + f' x
% subject to: Ax <= b
%
if (exist('qld') == 3)
v = qld (D, f, -A, b, lb, ub, p, length(b));
elseif (exist('quadprog') == 2)
prwarning(1,'QLD not found, the Matlab routine QUADPROG is used instead.')
v = quadprog(D, f, [], [], A, b, lb, ub);
else
prwarning(1,'QLD not found, the Matlab routine QP is used instead.')
verbos = 0;
negdef = 0;
normalize = 1;
v = qp(D, f, A, b, lb, ub, p, length(b), verbos, negdef, normalize);
end
% Find all the support vectors.
J = find(v > vmin);
% First find the SV on the boundary
I = J(v(J) < 1-vmin);
Ip = I(y(I) == 1);
Im = I(y(I) == -1);
if (isempty(v) | isempty(Ip) | isempty(Im))
%error('Quadratic Optimization failed. Pseudo-Fisher is computed instead.');
prwarning(1,'Quadratic Optimization failed. Pseudo-Fisher is computed instead.');
v = prpinv([K ones(n,1)])*y;
J = [1:n]';
C = nan;
return;
end
v = y.*v;
%wxI = K(I,J)*v(J);
wxIp = mean(K(Ip,J)*v(J),1); % rho-b
wxIm = mean(K(Im,J)*v(J),1); % -rho-b
rho = 0.5*(wxIp-wxIm);
b = -0.5*(wxIp+wxIm);
%b = mean(rho*y(I) - wxI);
v = [v(J); b]/rho;
C = 1/rho;
return;
|
github
|
jacksky64/imageProcessing-master
|
im_dbr.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_dbr.m
| 4,020 |
utf_8
|
af0771a52e215a85ee7b958c4661a1ce
|
%IM_DBR Image Database Retrieval GUI
%
% [RANK,TARG,OUTL] = IM_DBR(DBASE,FSETS,CLASSF,COMB)
%
% INPUT
% DBASE - Dataset or datafile with N object images
% FSETS - Cell array with maximum 4 feature sets
% CLASSF - Cell array with untrained classifiers (Default: KNNC([],1))
% COMB - Combining classifier (Default: MEANC)
%
% OUTPUT
% RANK - Index array ranking the N object images
% TARG - Index array pointing to user defined target images
% OUTL - Index array pointing to user defined outlier images
%
% DESCRIPTION
% This command generates a Graphical User Interface (GUI) enabling the user
% to label a database of images in 'target' and 'outlier' images in an
% interactive and iterative way. Up to four feature sets can be given and
% corresponding classifiers that assist the user by predict an object ranking
% based on classification confidences for the 'target' class.
%
% The GUI shows the top-10 of the ranking and the user should classify
% them as targets or outliers (original object labels in DBASE are
% neglected). There are buttons for browsing through the ranked database
% or through the selected targets and outliers. Classifiers can be trained
% according to two different strategies using the top right buttons:
% Classify - uses all stored target and outlier objects (shown in the top
% left windows) for building a training set as well as the
% hand labeled images in the present screen.
% Label - uses just the hand labeled images in the present screen
% and neglects the stored targets and outliers. This enables
% a more flexible, but still controlled browsing throug the
% database.
% Reset - Resets the entire procedure by deleting all selected targets
% and outliers.
% Quit - Deletes the GUI and returns the ranking and selected targets
% and outliers to the user.
% A few additional buttons and sliders for controlling the system behavior:
% - Delete and move buttons for the selected targets and outliers
% - Weights for the feature sets. For each feature set a different
% classifier is computed generating target confidences for all images.
% This influences the operation of the combiniong classifier.
% The weights can be changed by a slider for every feature set.
% By default weights are 1.
% - Two buttons for setting all labels as target ('All target') or outlier
% ('All outlier').
% - Labels for the individual images can be changed by a mouse-click in the
% image or on the image check-box.
% - For all images a target confidence is computed. Depending on the 'all'
% and 'unlabeled' radio buttons at the bottom the ranking of all images
% or of the yet unlabeled images are shown.
% Note: It is not an error, but for most classifiers useless or
% counterproductive to label an object as target as well as outlier.
%
% EXAMPLE
% % This example assumes that the Kimia images are available as datafile
% % and that the DipImage image processing package is available.
% prwaitbar on
% a = kimia_images;
% x = im_moments(a,'hu');
% x = setname(x,'Hu moments');
% y = im_measure(a,a,{'size','perimeter','ccbendingenergy'});
% y = setname(y,'Shape features');
% [R,T,L] = im_dbr(a,{x,y}); % do your own search
% delfigs
% figure(1); show(a(R,:)); % show ranking
% figure(2); show(a(T,:)); % show targets
% figure(3); show(a(L,:)); % show outliers
% showfigs
%
% SEE ALSO
% DATASETS, DATAFILES, MAPPINGS, KNNC, MEANC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [R,T,L] = im_dbr(dbase,featsets,classf,comb);
if sscanf(version('-release'),'%i') < 14
error('IM_DBR needs Matlab version 14 or higher')
end
if nargin < 4, comb = meanc; end
if nargin < 3, classf = knnc([],1); end
[R,T,L] = image_dbr(dbase,featsets,classf,comb);
return
|
github
|
jacksky64/imageProcessing-master
|
testr.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testr.m
| 1,212 |
utf_8
|
3fb7df399bfa4a82711fe3d24a4e08d7
|
%TESTR MSE for regression
%
% E = TESTR(X,W,TYPE)
% E = TESTR(X*W,TYPE)
% E = X*W*TESTR([],TYPE)
%
% INPUT
% X Regression dataset
% W Regression mapping
% TYPE Type of error measure, default: mean squared error
%
% OUTPUT
% E Mean squared error
%
% DESCRIPTION
% Compute the error of regression W on dataset X. The following error
% measures have been defined for TYPE:
% 'mse' mean squared error
% 'mad' mean absolute deviation
%
% SEE ALSO
% RSQUARED, TESTC
% Copyright: D.M.J. Tax, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function e = testr(x,w,type)
if nargin<3
type = 'mse';
end
if nargin<2
w = [];
end
if isstr(w)
type = w;
w = [];
end
if nargin<1 | isempty(x)
e = mapping(mfilename,'fixed',{w,type});
e = setname(e,type);
return
end
if (ismapping(w) & istrained(w))
a = a*w;
end
switch type
case 'mse'
e = mean((+x(:,1) - gettargets(x)).^2);
case 'mad'
e = mean(abs(+x(:,1) - gettargets(x)));
otherwise
error('Error %s is not implemented.',type);
end
if nargout==0
%display results on the screen:
fprintf('Error on %d objects: %f.\n',...
size(x,1), e);
clear e;
end
|
github
|
jacksky64/imageProcessing-master
|
stacked.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/stacked.m
| 4,901 |
utf_8
|
79804a8343df74d2068f63cfa3b6d6be
|
%STACKED Combining classifiers in the same feature space
%
% WC = STACKED(W1,W2,W3, ....) or WC = [W1,W2,W3, ...]
% WC = STACKED({W1,W2,W3, ...}) or WC = [{W1,W2,W3, ...}]
% WC = STACKED(WC,W1,W2, ....) or WC = [WC,W2,W3, ...]
%
% INPUT
% W1,W2,W3 Set of classifiers
%
% OUTPUT
% WC Combined classifier
%
% DESCRIPTION
% The base classifiers (or mappings) W1, W2, W3, ... defined in the same
% feature space are combined in WC. This is a classifier defined for the
% same number of features as each of the base classifiers and with the
% combined set of outputs. So, for three two class classifiers defined for
% the classes 'c1' and 'c2', a dataset A is mapped by D = A*WC on the outputs
% 'c1','c2','c1','c2','c1','c2', which are the feature labels of D. Note that
% classification by LABELD(D) finds for each vector in D the feature label
% of the column with the maximum value. This is equivalent to using the
% maximum combiner MAXC,
%
% Other fixed combining rules like PRODC, MEANC, and VOTEC can be applied by
% D = A*WC*PRODC. A trained combiner like FISHERC has to be supplied with
% the appropriate training set by AC = A*WC; VC = AC*FISHERC. So the
% expression VC = A*WC*FISHERC yields a classifier, not a dataset as with
% fixed combining rules. This classifier operates in the intermediate
% feature space, the output space of the set of base classifiers. A new
% dataset B has to be mapped to this intermediate space first by BC = B*WC
% before it can be classified by D = BC*VC. As this is equivalent to D =
% B*WC*VC, the total trained combiner is WTC = WC*VC = WC*A*WC*FISHERC. To
% simplify this procedure PRTools executes the training of a combined
% classifier by WTC = A*(WC*FISHERC) as WTC = WC*A*WC*FISHERC.
%
% It is also possible to combine a set of untrained classifiers, e.g. WC =
% [LDC NMC KNNC([],1)]*CLASSC, in which CLASSC takes care that all outputs
% will be transformed to appropriate posterior probabilities. Training of
% all base classifiers is done by WC = A*WC. Again, this may be combined
% with training of a combiner by WTC = A*(WC*FISHERC).
%
% EXAMPLES
% PREX_COMBINING
% SEE ALSO
% MAPPINGS, DATASETS, MAXC, MINC, MEANC,
% MEDIANC, PRODC, FISHERC, PARALLEL
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: stacked.m,v 1.4 2009/03/18 16:17:59 duin Exp $
function w = stacked(varargin)
prtrace(mfilename);
% No arguments given: just return map information.
if (nargin == 0)
w = mapping(mfilename,'combiner');
return
end
% Single argument: should be a mapping or cell array of mappings.
if (nargin == 1)
v = varargin{1};
% If V is a single mapping, process it directly.
if (~iscell(v))
if (~isa(v,'mapping'))
error('Mapping expected.')
end
w = mapping('stacked',getmapping_type(v),{v},getlabels(v));
w = set(w,'size',getsize(v));
else
% If V is a cell array of mappings, call this function recursively.
if (size(v,1) ~= 1)
error('Row of cells containing mappings expected')
end
w = feval(mfilename,v{:});
end
return
end
% Multiple arguments, all of which are mappings: combine them.
%if (~((nargin == 2) & (isa(varargin{1},'dataset'))))
if (~(isa(varargin{1},'dataset')))
% Get the first mapping.
v1 = varargin{1};
if (isempty(v1))
start = 3;
v1 = varargin{2};
else
start = 2;
end
ismapping(v1); % Assert V1 is a mapping.
k = prod(getsize_in(v1));
labels = getlabels(v1);
type = getmapping_type(v1);
% If V1 is already a stacked mapping without output conversion,
% unpack it to re-stack.
if (~strcmp(getmapping_file(v1),mfilename)) | getout_conv(v1) > 1
v = {v1};
else
v = getdata(v1);
end
% Now stack the second to the last mapping onto the first.
for j = start:nargin
v2 = varargin{j};
if (~strcmp(type,getmapping_type(v2)))
error('All mappings should be of the same type.')
end
if (getsize(v2,1) ~= k)
error('Mappings should have equal numbers of inputs.')
end
v = [v {v2}];
labels = [labels;getlabels(v2)];
end
w = mapping('stacked',type,v,labels,k);
else
% The first argument is a dataset: apply the stacked mapping.
a = varargin{1};
v = varargin{2};
if (~isa(v,'mapping'))
error('Mapping expected as second argument.')
end
if nargin==2 & isstacked(v)
n = length(v.data);
else
v = varargin(2:end);
n = nargin-1;
end
% Calculate W, the output of the stacked mapping on A.
w = [];
for j = 1:n
b = a*v{j};
% If, for a mapping to 1D (e.g. a 2-class discriminant)
% more than 1 output is returned, truncate.
if (size(v{j},2) == 1)
b = b(:,1);
end
w = [w b]; % Concatenate the outputs.
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
bandsel.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/bandsel.m
| 4,320 |
utf_8
|
b397f93a16fc65c469e370035595021d
|
%BANDSEL Selection of bands from object images
%
% B = BANDSEL(A,J)
% W = BANDSEL([],J)
% B = A*BANDSEL([],J)
%
% INPUT
% A Dataset or datafile with multi-band object images
% J Indices of bands to be selected
%
% OUTPUT
% W Mapping performing the band selection
% B Dataset with selected bands (ordered according to J)
%
% DESCRIPTION
% If the objects in a dataset or datafile A are multi-band images, e.g. RGB
% images, or the result of IM_PATCH, then the featsize of A is [M,N,L] for
% for L bands of an M x N images. This routine makes a selection J out of
% L. The routine BAND2OBJ may be used to organize the bands vertically
% as separate objects. However, BANDSEL nor BAND2OBJ can be applied to
% datafiles for which already a bandselection has been defined by BANDSEL.
%
%
% SEE ALSO
% DATASETS, DATAFILES, IM2OBJ, IM_PATCH, BAND2OBJ
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w = bandsel(a,J)
mapname = 'Band Selection';
if nargin < 2, J = 1; end
if nargin < 1 | isempty(a)
w = mapping(mfilename,'fixed',{J});
w = setname(w,mapname);
elseif isdatafile(a) % just store administration
if size(J,1) ~= 1
if size(J,1) ~= size(a,1)
error('Matrix with band indices does not match number of objects')
end
else
J = repmat(J,size(a,1),1);
end
%determine number of bands to be selected
if iscell(J)
n = size(J{1},2);
else
n = size(J,2);
end
%store bandselection as a mapping to be executed
%during dataset conversion
v = mapping(mfilename,'fixed',{[]},[],0,0);
% make the mappings identical, i.e. independent of v.data
% and store the data in the ident field under 'bandsel'.
% This will enable vertical concatenation of datafiles
J0 = getident(a,'bandsel');
J1 = zeros(size(J));
if ~isempty(J0)
% we already have a bandselection set; change it
if size(J,1) == 1
J1 = J0(:,J);
else
for j=1:size(J0,1)
J1(j,:) = J0(j,J(j,:));
end
end
else
J1 = J;
end
%correct bandnames in ident
a = setident(a,J1,'bandsel');
bandnames = getident(a,'bandnames');
if ~isempty(bandnames)
for j=1:size(a,1)
bandnames{j} = bandnames{j}(J(j,:),:);
end
a = setident(a,bandnames,'bandnames');
end
v = setdata(v,[]);
w = addpostproc(a,v);
elseif isdataset(a) % execute
m = size(a,1);
if isempty(J) % J is stored in a.ident.bandsel
J = getident(a,'bandsel');
% we assume that new bandnames are already set,
% simulataneously with bandsel
if isempty(J) % no bandselection defined
w = a;
return
end
else
if size(J,1) == 1
J = repmat(J(:)',m,1);
else
if size(J,1) ~= m
error('Wrong size of band selection array')
end
end
bandnames = getident(a,'bandnames');
if ~isempty(bandnames)
for j=1:m
bandnames{j} = bandnames{j}(J,:);
end
a = setident(a,bandnames,'bandnames');
end
end
isobjim(a);
fsize = getfeatsize(a);
if length(fsize) < 3
error('No image bands defined for dataset')
end
if any(J(:) > fsize(3))
id = getident(a);
id = id(find(J>fsize(3)));
error(['Wrong index for image bands. Object ident: ' int2str(id(1))] )
end
k = prod(fsize(1:2)); % size of a band
L = repmat((J(:,1)-1)*k,1,k)+repmat([1:k],m,1); % indices of band_1 per object
if size(J,2) > 1 % concatenate in case of multiple band selection
for j=2:size(J,2)
LL = repmat((J(:,j)-1)*k,1,k)+repmat([1:k],m,1); % indices of band_j per object
L = [L LL]; % indices for all bands to be selected
end
end
adata = getdata(a); % Let us do the selection on the data
bdata = zeros(m,k*size(J,2));
for i=1:m % can this be done faster?
bdata(i,:) = adata(i,L(i,:));
end
b = setdat(a,bdata); % store the data in a dataset with all information of a
b = setident(b,[],'bandsel'); % bandselection done, avoid second in case of stacked selections
w = setfeatsize(b,[fsize(1:2) size(J,2)]);
else
error('Illegal command')
end
|
github
|
jacksky64/imageProcessing-master
|
datfilt.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/datfilt.m
| 1,208 |
utf_8
|
31f36e31d9f2ba195de6f48b03120f3c
|
%DATFILT Filtering of dataset images
%
% B = DATFILT(A,F)
%
% INPUT
% A Dataset with image data
% F Matrix with the convolution mask
%
% OUTPUT
% B Dataset containing all the images after filtering
%
% DESCRIPTION
% All images stored in the dataset A are horizontally and vertically
% convoluted by the 1-dimensional filter F. A uniform N*N filter is,
% thereby, realized by DATFILT(A,ONES(1,N)/N).
%
% SEE ALSO
% DATASETS, IM2OBJ, DATA2IM, IM2FEAT, DATGAUSS, DATAIM
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: datfilt.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function a = datfilt(a,f)
prtrace(mfilename);
[m,k] = getsize(a);
n = length(f);
nn = floor(n/2);
im = data2im(a);
[imheight,imwidth,nim] = size(im);
for i=1:nim
% Add a border with NN pixels, set the border to
% the mirrored original values (private function).
c = bord(im(:,:,i),NaN,nn);
c = conv2(f,f,c,'same');
im(:,:,i) = resize(c,nn,imheight,imwidth);
end
if (isfeatim(a))
a = setdata(a,im2feat(im),getfeatlab(a));
else
a = setdata(a,im2obj(im),getfeatlab(a));
end
return;
|
github
|
jacksky64/imageProcessing-master
|
linewidth.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/linewidth.m
| 605 |
utf_8
|
38780117b4f229c290a054070793bd28
|
%LINEWIDTH Set linewidth in plot
%
% linewidth(width)
%Set linewidth for current figure
function linewidth(width)
if strcmp(get(gca,'type'),'line')
set(gca,'linewidth',width);
end
children = get(gca,'children');
set_linewidth_children(children,width)
return
function set_linewidth_children(children,width)
if isempty(children), return, end
for i = children(:)'
if length(i) > 1
set_linewidth_children(i,width)
return
end
if strcmp(get(i,'type'),'line') | strcmp(get(i,'type'),'patch')
set(i,'linewidth',width);
end
children2 = get(i,'children');
set_linewidth_children(children2,width)
end
|
github
|
jacksky64/imageProcessing-master
|
medianc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/medianc.m
| 1,428 |
utf_8
|
b359e761a6b0660209c316be6d90edfb
|
%MEDIANC Median combining classifier
%
% W = MEDIANC(V)
% W = V*MEDIANC
%
% INPUT
% V Set of classifiers
%
% OUTPUT
% W Median combining classifier on V
%
% DESCRIPTION
% If V = [V1,V2,V3, ... ] is a set of classifiers trained on the same
% classes, then W is the median combiner: it selects the class with
% the median of the outputs of the input classifiers. This might also
% be used as A*[V1,V2,V3]*MEDIANC, in which A is a dataset to be
% classified.
%
% If it is desired to operate on posterior probabilities then the input
% classifiers should be extended to output these, as V = V*CLASSC.
%
% SEE ALSO
% MAPPINGS, DATASETS, VOTEC, MAXC, MINC, PRODC, MEANC, AVERAGEC, STACKED,
% PARALLEL, FIXEDCC
%
% EXAMPLES
% See PREX_COMBINING.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: medianc.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function w = medianc (p1)
prtrace (mfilename);
% The median combiner is constructed as a fixed combiner (FIXEDCC) of
% type 'median'.
type = 'median'; name = 'Median combiner';
% Possible calls: MEDIANC, MEDIANC(W) or MEDIANC(A,W).
if (nargin == 0)
w = mapping('fixedcc','combiner',{[],type,name});
else
w = fixedcc(p1,[],type,name);
end
if (isa(w,'mapping'))
w = setname(w,name);
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_rotate.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_rotate.m
| 1,230 |
utf_8
|
adfb824fe371037f44f120c02c27249f
|
%IM_ROTATE Rotate all images in dataset
%
% B = IM_ROTATE(A,ALF)
%
% INPUT
% A Dataset with object images (possibly multi-band)
% ALF Rotation angle (in radians),
% default: rotation to main axis
%
% OUTPUT
% B Dataset with rotated object images
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_rotate(a,alf)
prtrace(mfilename);
if nargin < 2, alf = []; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{alf});
b = setname(b,'Image rotate');
elseif isdataset(a)
error('Command cannot be used for datasets as it may change image size')
elseif isdatafile(a)
isobjim(a);
b = filtim(a,mfilename,{alf});
b = setfeatsize(b,getfeatsize(a));
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = double(a);
if isempty(alf)
m = im_moments(a,'central',[1 2 0; 1 0 2]');
C = [m(2) m(1); m(1) m(3)];
[E,D] = preig(C); [DD,ind] = sort(diag(D));
alf = atan2(E(2,ind(1)),E(1,ind(1)))+pi/2;
end
b = imrotate(a,alf*360/(2*pi),'bilinear','crop');
end
return
|
github
|
jacksky64/imageProcessing-master
|
gensubsets.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gensubsets.m
| 2,064 |
utf_8
|
b46581d4b9ea139026fe9db863da530c
|
%GENSUBSETS Generate sequence of embedded training sets
%
% [L,R] = GENSUBSETS(NLAB,S)
% [L,R] = GENSUBSETS(A,S)
%
% INPUT
% NLAB Column vector of numeric labels of some dataset A.
% NLAB = GETNLAB(A)
% A Dataset for which subsets are to be created
% S Array of growing subset sizes.
% S(K,J) should specify the size of training set K for class J with
% numeric label J.
%
% OUTPUT
% L Cell array of length SIZE(S,1)+1 containing a series of growing
% sets of indices or datasets. Datasets can be reconstructed from
% indices by A(L{K},:). The last element of L refers to the
% original dataset A
% R Cell array of length SIZE(S,1)+1 containing a series of shrinking
% sets of indices or datasets. Datasets can be reconstructed from
% indices by A(R{K},:). The last element of R is empty.
%
% DESCRIPTION
% Learning curves of classifier performances should be based on a
% consistent set of training sets, such that training set K1 is a subset of
% training set K2 if K1 < K2. This routine generates such a set on the
% basis of the numeric labels of the dataset A. L refers to the selected
% objects and R to the deselected ones.
%
% SEE ALSO
% DATASETS, GENDAT
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [L,R] = gensubsets(input,S)
if isdataset(input)
nlab = getnlab(input);
else
nlab = input;
end
[n,c] = size(S); % number of subsets n, number of classes c
if max(nlab) ~= c
error('Number of columns of size matrix not equal to number of classes')
end
m = length(nlab);
L = cell(1,n+1);
R = cell(1,n+1);
a = dataset([1:m]',nlab); % make fake dataset with data equal indices
L{n+1} = [1:m]';
R{n+1} = [];
for j=n:-1:1
[inset,outset] = gendat(a(L{j+1},:),S(j,:));
L{j} = +inset;
R{j} = [R{j+1};+outset];
end
if isdataset(input)
for j=1:n+1
L{j} = input(L{j},:);
R{j} = input(R{j},:);
end
end
|
github
|
jacksky64/imageProcessing-master
|
ploto.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/ploto.m
| 1,981 |
utf_8
|
a555d41642039708da0330e072b05329
|
%PLOTO Plot objects as 1-D functions of the feature number
%
% [HH HO HC] = PLOTO(A,N)
%
% INPUT
% A Dataset
% N Integer
%
% OUTPUT
% HH Lines handles
% HO Object identifier handles
% HC Class number handles
%
% DESCRIPTION
% Produces 1-D function plots for all the objects in dataset A. The plots
% are organised as subplots, N on a row. Default is the squareroot of the
% number of objects. Object identifiers and class numbers are written in
% the correspopnding plots.
%
% See also DATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [h_out1,h_out2,h_out3] = ploto(a,p)
prtrace(mfilename);
if nargin < 2, p = []; end
[m,k,c] = getsize(a);
nlab = getnlab(a);
% Define the color for each of the classes:
if c == 2
map = [0 0 1; 1 0 0];
else
map = hsv(c);
end
% Make subplots for each object, so a grid of p x q subplots is
% defined
h = [];
if ~isempty(p)
q = ceil(m/p);
elseif m > 3
p = ceil(sqrt(m)); q = ceil(m/p);
else
p = m; q = 1;
end
% Get the object labels
labs = getlabels(a);
ymin = min(a.data(:));
ymax = max(a.data(:));
V = [1 k ymin ymax];
% Make the plot for each of the objects:
h = [];
ho = [];
hc = [];
s = sprintf('Plot %i objects: ',m);
prwaitbar(m,s);
for j = 1:m
if isdatafile(a) | 1
prwaitbar(m,j,[s int2str(j)]);
b = +dataset(a(j,:));
ymin = min(b);
ymax = max(b);
k = length(b);
V = [1 k ymin ymax];
else
b = +a(j,:);
end
% Create the subplots with the correct sizes:
subplot(q,p,j)
hh = plot(b);
set(gca,'xtick',[]);
set(gca,'ytick',[]);
axis(gca,V);
ho = [ho text(2,ymax-0.15*(ymax-ymin),getident(a(j,:),'string'))];
hc = [hc text(3*k/4,ymax-0.15*(ymax-ymin),num2str(nlab(j)))];
h = [h hh];
hold on
end
prwaitbar(0);
% The last details to take care of:
if nargout > 0
h_out1 = h;
h_out2 = ho;
h_out3 = hc;
end
return
|
github
|
jacksky64/imageProcessing-master
|
iscomdset.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/iscomdset.m
| 1,536 |
utf_8
|
e4f1285eb09e4258dd2fb8a71fa2e676
|
%ISCOMDSET Test whether datasets are compatible
%
% N = ISCOMDSET(A,B,CLAS);
%
% INPUT
% A Input argument, to be tested on dataset
% B Input argument, to be tested on compatibility with A
% CLAS 1/0, test on equal classes (1) or don't test (0)
% (optional; default 1)
%
% OUTPUT
% N 1/0 if A and B are / are not compatible datasets
%
% DESCRIPTION
% The function ISCOMDSET tests whether A and B are compatible
% datasets, i.e. have the same features and the same classes.
%
% SEE ALSO
% ISDATASET, ISMAPPING, ISDATAIM, ISFEATIM, ISVALDFILE, ISVALDSET
function n = iscomdset(a,b,clas)
prtrace(mfilename);
if nargin < 3, clas = 1; end
if isempty(b) % return of second dataset empty (i.e. not supplied)
return
end
if nargout == 0
isdataset(a);
isdataset(b);
else
n = isdataset(a) & isdataset(b);
end
featlaba = setstr(getfeatlab(a));
featlabb = setstr(getfeatlab(b));
nf = strcmp(featlaba,featlabb);
if ~nf
if nargout == 0
error([newline 'Datasets for training and testing/tuning should' newline ...
'have the same features in the same order.'])
else
n = 0;
end
end
if clas
lablista = setstr(getlablist(a));
lablistb = setstr(getlablist(b));
no = strcmp(lablista,lablistb);
if ~no
if nargout == 0
error([newline 'Datasets for training and testing/tuning should' newline ...
'have the same class labels in the same order.'])
else
n = 0;
end
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
prdata.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prdata.m
| 1,605 |
utf_8
|
5945233e9aca3aff5de534a83caf9910
|
%PRDATA Read data files
%
% A = PRDATA(FILENAME,FLAG)
%
% INPUT
% FILENAME Name of delimited ASCII file containing rows of data
% FLAG If not 0, first column is assumed to contain labels (default 1)
%
% OUTPUT
% A Dataset
%
% DESCRIPTION
% Reads data into the dataset A. The first word of each line is interpreted
% as label data. Each line is stored row-wise and interpreted as the feature
% values of a single object.
%
% SEE ALSO
% DATASETS, PRDATASET
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: prdata.m,v 1.3 2008/03/20 07:42:01 duin Exp $
function a = prdata(file,labels)
prtrace(mfilename);
% ASCII magic...
if (strcmp(computer,'MAC2')), crlf = 13; else, crlf = 10; end
if (nargin < 2)
prwarning(4,'first column of file is assumed to contain labels');
labels = 1;
end
% Open the file.
fid = fopen(file);
if (fid < 0)
error('Error in opening file.')
end
% Read the data. First, find the number of items on the first line.
s = fread(fid,inf,'uchar'); i = find(s==crlf);
n = length(sscanf(setstr(s(1:i(1))),'%e'));
fseek(fid,0,'bof'); % Return to the begin of the file.
[a,num] = fscanf(fid,'%e',inf); % Keep reading N objects per line.
a = reshape(a,n,num/n)'; % Reshape to the correct data matrix.
% Create the dataset, depending where the labels were stored.
if (labels)
lab=a(:,1); a(:,1)=[];
a = dataset(a,lab);
else
a = dataset(a);
end
% And close the file.
fclose(fid);
return
|
github
|
jacksky64/imageProcessing-master
|
affine.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/affine.m
| 6,661 |
utf_8
|
6cff6eade53ed2451811ada3fd31a10b
|
%AFFINE Construct affine (linear) mapping from parameters
%
% W = AFFINE(R,OFFSET,LABLIST_IN,LABLIST_OUT,SIZE_IN,SIZE_OUT)
% W = AFFINE(R,OFFSET,A)
% W = AFFINE(W1,W2)
%
% INPUT
% R Matrix of a linear mapping from a K- to an L-dimensional space
% OFFSET Shift applied after R; a row vector of the length L
% (optional; default: zeros(1,L))
% LABLIST_IN Labels of the features of the input space
% (optional; default: (1:K)')
% LABLIST_OUT Labels of the features of the output space, e.g. class names
% for linear classifiers (optional; default: (1:L)')
% SIZE_IN If based on images: size vector of the input dimensionality
% (optional; default: K)
% SIZE_OUT If based on images: size vector of the output dimensionality
% (optional; default: L)
% A Dataset (LAB_IN_LIST and SIZE_IN are derived from A)
% W1,W2 Affine mappings
%
% OUTPUT
% W Affine mapping
%
% DESCRIPTION
% Defines a mapping W based on a linear transformation R and an offset.
% R should be a [K x L] matrix describing a linear transformation from
% a K-dimensional space to an L-dimensional space. If K=1, then R is
% interpreted as the diagonal of an [L x L] diagonal matrix. OFFSET is
% a row vector of the length L, added afterwords.
%
% Affine mappings are treated by PRTools in a special way. A scaling
% defined for an affine mapping, e.g. by W = SETSCALE(W,SCALE) is directly
% executed by a multiplication of the coefficients. Also, the product of
% two affine mappings is directly converted to a new affine mapping.
% Finally, the transpose of an affine mapping exists and is defined as
% an another affine mapping. Consequently, this routine also executes
% W = AFFINE(W1,W2) if W1 and W2 are affine and B = AFFINE(A,W), if A
% is a dataset and W is an affine mapping.
%
% An [M x K] dataset A can be mapped as D = A*W. The result is equivalent
% to [+A, ones(M,1)]*[R; OFFSET]. The dataset D has feature labels stored
% in LABLIST. The number of this labels should, thereby, be at least L.
%
% SEE ALSO
% DATASETS, MAPPINGS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: affine.m,v 1.10 2009/03/17 10:03:51 duin Exp $
function w = affine(R,offset,lablist_in, lablist_out,size_in,size_out)
prtrace(mfilename);
if (nargin == 1) | (~isa(offset,'mapping'))
% Definition of an affine mapping
[m,k] = size(R);
if (nargin < 6)
prwarning(5,'SIZE_OUT is not specified. The number of columns of R, %d, is assumed.', k);
size_out = k;
end
if (nargin < 5)
prwarning(5,'SIZE_IN is not specified. The number of rows of R, %d, is assumed.', m);
size_in = m;
end
if (nargin < 4)
prwarning(5,'LABLIST_OUT is not specified, [1:%d]'' assumed.', k);
lablist_out = [];
end
if (nargin < 3)
prwarning(5,'LABLIST_IN is not specified, [1:%d]'' assumed.', m);
lablist_in = [];
end
if (nargin < 2) | (isempty(offset))
prwarning(3,'OFFSET not specified, a zero vector assumed.');
offset = zeros(1,k);
end
% Check consistencies
if (~isa(R,'double'))
error('No proper transformation matrix stored.')
end
if (size_in == 1) & nargin < 3 % R is a scaling vector
size_in = size_out;
end
if (isempty(lablist_in))
lablist_in = genlab(1,[1:size_in]');
end
cost = [];
if (isa(lablist_in,'dataset')) % Copy labels from dataset/datafile
cost = lablist_in.cost;
size_in = getfeatsize(lablist_in);
lablist_in = getfeatlab(lablist_in);
%if isempty(lablist_in)
% lablist_in = num2str([1:size_in]');
%end
% size_out = k; % Wrong for classifiers defined for 1D datasets
end
if ~isempty(lablist_in) & (size(lablist_in,1) < m)
error('Wrong number of input labels supplied.')
end
if isempty(lablist_out)
lablist_out = genlab(1,[1:size_out]');
end
if (size(lablist_out,1) < k)
error('Wrong number of output labels supplied.')
end
if any(size(offset) ~= [1,k])
error('Offset is not a row vector of the correct size.')
end
% Store the results:
d.rot = R;
d.offset = offset;
d.lablist_in = lablist_in;
w = mapping(mfilename,'trained',d,lablist_out,size_in,size_out);
w = setcost(w,cost);
elseif isa(R,'mapping')
% Two mappings, stored in R and OFFSET, should be combined.
w1 = R;
w2 = offset;
if (~isclassifier(w1)) & (~isclassifier(w2)) & (strcmp(getmapping_file(w1),'affine')) & (strcmp(getmapping_file(w2),'affine'))
% Combine two affine mappings
% If d1.rot or d2.rot are vectors, they have to be interpreted as
% the diagonal matrices, unless the inner dimension does not fit.
d1 = +w1;
d2 = +w2;
if (size(d1.rot,1) == 1) % d1.rot is a vector
if (size(d2.rot) == 1) % d2.rot is a vector
d.rot = d1.rot.*d2.rot;
d.offset = d1.offset.*d2.rot + d2.offset;
else % d2.rot is a matrix
d.rot = repmat(d1.rot',1,size(d2.rot,2)).*d2.rot;
d.offset = d1.offset*d2.rot + d2.offset;
end
else % d1.rot is a matrix
%RD Here comes a bug fix that I needed to continue, I am not sure it
%RD is sufficient It may even introduce new problems, especially for
% 1D datasets.
%if size(d2.rot,1) == 1 % d2.rot is vector
if (size(d1.rot,2) > 1) & (size(d2.rot,1) == 1) % d2.rot is a vector
d.rot = d1.rot.*repmat(d2.rot,size(d1.rot,1),1);
d.offset = d1.offset.*d2.rot + d2.offset;
else % d2.rot is a matrix
d.rot = d1.rot*d2.rot;
d.offset = d1.offset*d2.rot + d2.offset;
end
end
d.lablist_in = d1.lablist_in;
w = mapping(mfilename,'trained',d,getlabels(w2),getsize_in(w1),getsize_out(w2));
else
% Store a sequential mapping.
w = sequential(w1,w2);
end
else
% Execution of the affine mapping.
% R is a dataset, OFFSET defines the mapping.
v = offset;
[m,k] = size(R);
d = +v;
if all(size(v) == 0)
d.rot = repmat(d.rot,1,k);
d.offset = zeros(1,k);
end
if (size(d.rot,1) == 1) & (k > 1)
% No rotation, just a scaling
x = zeros(m,k);
Rdat = +R;
if (m > k) % Necessary switch for handling large feature sizes.
for j=1:k
x(:,j) = Rdat(:,j)*d.rot(j);
end
else
for i=1:m
x(i,:) = Rdat(i,:).*d.rot;
end
end
x = x + repmat(d.offset,m,1);
else % Rotation.
x = [+R,ones(m,1)] * [d.rot;d.offset];
end
if size(v,2) == 2 & size(x,2) == 1
x = [x -x];
end
w = setdat(R,x,v);
end
return;
|
github
|
jacksky64/imageProcessing-master
|
show.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/show.m
| 1,832 |
utf_8
|
747bec8ec7718217efb36afb78ddd30a
|
%SHOW PRTools general show
%
% H = SHOW(A,N,B)
%
% INPUT
% A Image
% N Number of images on a row
% B Intensity value of background (default 0.5);
%
% OUTPUT
% H Graphics handle
%
% DESCRIPTION
% PRTools offers a SHOW command for variables of the data classes DATASET
% and DATAFILE. In order to have a simliar command for images not converted
% to a DATASET this commands made availble. A should be 2D, 3D or 4D image.
%
% 2D images are fully displayed.
%
% 3D images are converted to a dataset with as many feature images as given
% in the 3rd dimension and displayed by DATASET/SHOW.
%
% 4D images with 3 bands in the 3rd dimension are converted to a dataset with
% as many 3-color object images as are given in the 4th dimension and
% displayed by DATASET/SHOW
%
% All other 4D images are converted to a dataset with as many 2D feature
% images as given by the dimensions 3 and 4 and displayed by DATASET/SHOW.
% Unless given otherwise, N is set to size(A,3).
%
% SEE ALSO DATASET/SHOW DATAFILE/SHOW
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function h = show(a,n,background)
prtrace(mfilename);
if nargin < 3, background = 0.5; end
if nargin < 2, n = []; end
a = double(a);
s = size(a);
if length(s) == 2
if any(s==1)
error('Image expected')
end
a = im2obj(a);
elseif length(s) == 3 & s(3) ~= 3
a = im2feat(a);
a = dataset(a,NaN); % avoid display label image
else
if length(s) >= 3 & s(3) == 3
a = im2obj(a,s(1:3));
else
a = reshape(a,s(1),s(2),prod(s(3:end)));
a = im2feat(a);
a = dataset(a,0); % avoid display label image
end
end
if nargout > 0
h = show(a,n,background);
else
show(a,n,background);
end
|
github
|
jacksky64/imageProcessing-master
|
gauss.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gauss.m
| 4,857 |
utf_8
|
f871f6aac7a86da963a8c0f48b508082
|
%GAUSS Generation of a multivariate Gaussian dataset
%
% A = GAUSS(N,U,G,LABTYPE)
%
% INPUT (in case of generation a 1-class dataset in K dimensions)
% N Number of objects to be generated (default 50).
% U Desired mean (vector of length K).
% G K x K covariance matrix. Default eye(K).
% LABTYPE Label type (default 'crisp')
%
% INPUT (in case of generation a C-class dataset in K dimensions)
% N Vector of length C with numbers of objects per class.
% U C x K matrix with class means, or
% Dataset with means, labels and priors of classes
% (default: zeros(C,K))
% G K x K x C covariance matrix of right size.
% Default eye(K);
% LABTYPE Label type (default 'crisp')
%
% OUTPUT
% A Dataset containing multivariate Gaussian data
%
% DESCRIPTION
% Generation of N K-dimensional Gaussian distributed samples for C classes.
% The covariance matrices should be specified in G (size K*K*C) and the
% means, labels and prior probabilities can be defined by the dataset U with
% size (C*K). If U is not a dataset, it should be a C*K matrix and A will
% be a dataset with C classes.
%
% If N is a vector, exactly N(I) objects are generated for class I, I = 1..C.
%
% EXAMPLES
% 1. Generation of 100 points in 2D with mean [1 1] and default covariance
% matrix:
%
% GAUSS(100,[1 1])
%
% 2. Generation of 50 points for each of two 1-dimensional distributions with
% mean -1 and 1 and with variances 1 and 2:
%
% GAUSS([50 50],[-1;1],CAT(3,1,2))
%
% Note that the two 1-dimensional class means should be given as a column
% vector [1;-1], as [1 -1] defines a single 2-dimensional mean. Note that
% the 1-dimensional covariance matrices degenerate to scalar variances,
% but have still to be combined into a collection of square matrices using
% the CAT(3,....) function.
%
% 3. Generation of 300 points for 3 classes with means [0 0], [0 1] and
% [1 1] and covariance matrices [2 1; 1 4], EYE(2) and EYE(2):
%
% GAUSS(300,[0 0; 0 1; 1 1]*3,CAT(3,[2 1; 1 4],EYE(2),EYE(2)))
%
% SEE ALSO
% DATASETS, PRDATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function a = gauss(n,u,g,labtype)
prtrace(mfilename);
if (nargin < 1)
prwarning (2,'number of samples not specified, assuming N = 50');
n = 50;
end
cn = length(n);
if (nargin < 2)
prwarning (2,'means not specified; assuming one dimension, mean zero');
u = zeros(cn,1);
end;
if (nargin < 3)
prwarning (2,'covariances not specified, assuming unity');
g = eye(size(u,2));
end
if (nargin < 4)
prwarning (3,'label type not specified, assuming crisp');
labtype = 'crisp';
end
% Return an empty dataset if the number of samples requested is 0.
if (length(n) == 1) & (n == 0)
a = dataset([]);
return
end
% Find C, desired number of classes based on U and K, the number of
% dimensions. Make sure U is a dataset containing the means.
if (isa(u,'dataset'))
[m,k,c] = getsize(u);
lablist = getlablist(u);
p = getprior(u);
if c == 0
u = double(u);
end
end
if isa(u,'double')
[m,k] = size(u);
c = m;
lablist = genlab(ones(c,1));
u = dataset(u,lablist);
p = ones(1,c)/c;
end
if (cn ~= c) & (cn ~= 1)
error('The number of classes specified by N and U does not match');
end
% Generate a class frequency distribution according to the desired priors.
n = genclass(n,p);
% Find CG, the number of classes according to G.
% Make sure G is not a dataset.
if (isempty(g))
g = eye(k);
cg = 1;
else
g = real(+g); [k1,k2,cg] = size(g);
if (k1 ~= k) | (k2 ~= k)
error('The number of dimensions of the means U and covariance matrices G do not match');
end
if (cg ~= m & cg ~= 1)
error('The number of classes specified by the means U and covariance matrices G do not match');
end
end
% Create the data A by rotating and scaling standard normal distributions
% using the eigenvectors of the specified covariance matrices, and adding
% the means.
a = [];
for i = 1:m
j = min(i,cg); % Just in case CG = 1 (if G was not specified).
% Sanity check: user can pass non-positive definite G.
[V,D] = preig(g(:,:,j)); V = real(V); D = real(D); D = max(D,0);
a = [a; randn(n(i),k)*sqrt(D)*V' + repmat(+u(i,:),n(i),1)];
end
% Convert A to dataset by adding labels and priors.
labels = genlab(n,lablist);
a = dataset(a,labels,'lablist',lablist,'prior',p);
% If non-crisp labels are requested, use output of Bayes classifier.
switch (labtype)
case 'crisp'
;
case 'soft'
w = nbayesc(u,g);
targets = a*w*classc;
a = setlabtype(a,'soft',targets);
otherwise
error(['Label type ' labtype ' not supported'])
end
a = setname(a,'Gaussian Data');
return
|
github
|
jacksky64/imageProcessing-master
|
nlabcmp.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nlabcmp.m
| 975 |
utf_8
|
91014c1ad5b78b2874f44cf02e296fcb
|
%NLABCMP Compare two label lists and count the differences
%
% [N,C] = NLABCMP(LAB1,LAB2)
%
% INPUT
% LAB1,
% LAB2 Label lists
%
% OUTPUT
% C A 0/1 vector pointing to different/equal labels
% N Number of differences in LAB1 and LAB2
%
% DESCRIPTION
% Compares two label lists and counts the disagreements between them.
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: nlabcmp.m,v 1.4 2008/07/28 08:57:42 duin Exp $
function [N,C] = nlabcmp(S1,S2)
prtrace(mfilename);
[m,k] = size(S1);
[n,l] = size(S2);
if (m ~= n)
error('Label list sizes do not match.')
end
if (iscell(S1) ~= iscell(S2))
error('Label lists should be both cells, strings or numeric.')
end
if (iscell(S1))
C = strcmp(S1,S2);
elseif (all(size(S1) == size(S2)))
C = all(S1'==S2',1)';
else
C = strcmp(cellstr(S1),cellstr(S2));
end
N = m - sum(C);
return
|
github
|
jacksky64/imageProcessing-master
|
featsellr.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/featsellr.m
| 9,276 |
utf_8
|
899156db13a08ae7791a4a549dd9d1c7
|
%FEATSELLR Plus-L-takeaway-R feature selection for classification
%
% [W,RES] = FEATSELLR(A,CRIT,K,L,R,T,FID)
%
% INPUT
% A Dataset
% CRIT String name of the criterion or untrained mapping
% (optional; default: 'NN', i.e. 1-Nearest Neighbor error)
% K Number of features to select
% (optional; default: return optimally ordered set of all features)
% L Number of features to select at a time (plus-L, default: 1), L ~= R
% R Number of features to deselect at a time (takeaway-R, default: 0)
% T Tuning set (optional)
% N Number of cross-validations (optional)
% FID File ID to write progress to (default [], see PRPROGRESS)
%
% OUTPUT
% W Output feature selection mapping
% RES Matrix with step-by-step results of the selection
%
% DESCRIPTION
% Floating selection of K features using the dataset A, by iteratively
% selecting L optimal features and deselecting R. Starts from the full
% set of features when L < R, otherwise from the empty set. CRIT sets the
% criterion used by the feature evaluation routine FEATEVAL. If the dataset
% T is given, it is used as a tuning set for FEATEVAL. Alternatively
% a number of cross-validations N may be supplied. For K = 0, the optimal
% feature set (maximum value of FEATEVAL) is returned. The result W can be
% used for selecting features by B*W. In this case, features are ranked
% optimally.
% The selected features are stored in W.DATA and can be found by +W.
% In R, the search is reported step by step as:
%
% RES(:,1) : number of features
% RES(:,2) : criterion value
% RES(:,3:3+max(L,R)) : added / deleted features
%
% SEE ALSO
% MAPPINGS, DATASETS, FEATEVAL, FEATSEL
% FEATSELO, FEATSELB, FEATSELF, FEATSELI, FEATSELP, FEATSELM, PRPROGRESS
% Copyright: D. de Ridder, [email protected]
% Faculty of Electrical Engineering, Mathematics and Computer Science
% Delft University of Technology, Mekelweg 4, 2628 CD Delft, The Netherlands
% $Id: featsellr.m,v 1.6 2009/11/27 08:53:00 duin Exp $
function [w,res] = featsellr(a,crit,ksel,l,r,t,fid)
prtrace(mfilename);
if (nargin < 2) | isempty(crit)
prwarning(2,'No criterion specified, assuming 1-NN.');
crit = 'NN';
end
if (nargin < 3) | isempty(ksel)
ksel = 0; % Consider all the features and sort them.
end
if (nargin < 4) | isempty(l)
l = 1;
end;
if (nargin < 5) | isempty(r)
r = 0;
end;
if (nargin < 6)
prwarning(3,'No tuning set supplied.');
t = [];
end
if (nargin < 7)
fid = [];
end
if (l==r)
error('In ''Plus-L-takeaway-R feature selection'' L should be unequal to R')
end
% No inputs arguments provided, return an untrained mapping.
if (nargin == 0) | (isempty(a))
w = mapping('featsellr',{crit,ksel,t});
w = setname(w,'+L-R FeatSel');
return
end
isvaldfile(a,1,2); % At least 1 object per class, 2 classes.
a = testdatasize(a);
a = setprior(a,getprior(a));
if ~is_scalar(t), iscomdset(a,t); end
[m,k,c] = getsize(a);
featlist = getfeatlab(a);
% Initialise counters.
state.l = l; state.r = r;
if (state.l > state.r) % Start from empty set.
state.I = []; % Pool of selected feature indices.
state.critval_opt = 0; % Maximum criterion value found so far.
state.res = zeros(0,2+max(l,r)); % Report of selection process.
else
state.I = [1:k]; % Pool of the feature indices to be used.
state.critval_opt = feateval(a,crit,t); % Max. criterion found so far.
state.res = [k,state.critval_opt,zeros(1,max(l,r))]; % Report of selection process.
end;
state.I_opt = state.I; state.critval = [];
% Evaluate the criterion function for the entire dataset A.
prprogress(fid,['\nfeatsellr: Plus-' num2str(l) '-takeaway-' num2str(r) ...
' feature selection\n'])
if ksel == 0
if (l > r)
s = sprintf('Forward search of optimal feature set out of %i: ',k);
else
s = sprintf('Backward search of optimal feature set out of %i: ',k);
end
nsize = k;
else
s = sprintf('Selection of %i features: ',ksel);
nsize = abs(length(state.I)-ksel);
end
prwaitbar(nsize,s);
while (ksel == 0 & (((state.l > state.r) & (length(state.I) <= k-state.l)) | ...
((state.l < state.r) & (length(state.I) > state.r)))) | ...
(ksel > 0 & state.l > state.r & length(state.I) < ksel) | ...
(ksel > 0 & state.l < state.r & length(state.I) > ksel)
% Calculate criterion values C for the features in I and find the feature
% giving the maximum.
if (l > r)
state = plusl(a,crit,t,state,fid);
if (r > 0), state = takeawayr(a,crit,t,state,fid); end;
prwaitbar(nsize,length(state.I),[s int2str(length(state.I))]);
else
state = takeawayr(a,crit,t,state,fid);
if (l > 0), state = plusl(a,crit,t,state,fid); end;
prwaitbar(nsize,k-length(state.I),[s int2str(length(state.I))]);
end;
end;
prwaitbar(0);
% Make sure we end up with exactly KSEL features.
if (ksel == 0) & (state.l > state.r) & (length(state.I) < k)
state.l = k - length(state.I);
state = plusl(a,crit,t,state,fid);
elseif (ksel == 0) & (state.l < state.r) & (length(state.I) > 1)
state.r = length(state.I) - 1;
state = takeawayr(a,crit,t,state,fid);
elseif (ksel > 0) & (state.l > state.r) & (length(state.I) > ksel)
state.r = length(state.I) - ksel;
state = takeawayr(a,crit,t,state,fid);
elseif (ksel > 0) & (state.l < state.r) & (length(state.I) < ksel)
state.l = ksel - length(state.I);
state = plusl(a,crit,t,state,fid);
end;
if (ksel ~= 0), state.I_opt = state.I; end;
w = featsel(k,state.I_opt);
if ~isempty(featlist)
w = setlabels(w,featlist(state.I_opt,:));
end
w = setname(w,'+L-R FeatSel');
res = state.res;
prprogress(fid,'featsellr finished\n')
return;
function state = plusl(a,crit,t,state,fid)
% J contains the indices of the nonselected features.
[m,k,c] = getsize(a); J = setdiff(1:k,state.I);
critval_opt = 0; Jsub_opt = [];
% Find all possible choices of L indices out of J.
[Jsub,ind] = npickk(J,state.l);
while (~isempty(Jsub))
% Calculate the criterion when subset JSUB is added.
if (isempty(t))
critval = feateval(a(:,[state.I Jsub]),crit);
elseif is_scalar(t)
critval = feateval(a(:,[state.I Jsub]),crit,t);
else
critval = feateval(a(:,[state.I Jsub]),crit,t(:,[state.I Jsub]));
end;
% Store the best subset and its criterion value.
if (critval > critval_opt)
critval_opt = critval;
Jsub_opt = Jsub;
end;
[Jsub,ind] = npickk(J,state.l,ind);
end;
state.I = [state.I Jsub_opt];
if (critval_opt > state.critval_opt) | ...
(critval_opt == state.critval_opt & ...
length(state.I) < length(state.I_opt)),
state.critval_opt = critval_opt;
state.I_opt = state.I;
end;
line = [length(state.I),critval_opt,...
[Jsub_opt zeros(1,size(state.res,2)-2-length(Jsub_opt))]];
prprogress(fid,' %d %f \n',line(1:2));
state.res = [state.res; line];
return
function state = takeawayr(a,crit,t,state,fid)
% J contains the indices of the selected features.
[m,k,c] = getsize(a); J = state.I;
critval_opt = 0; Jsub_opt = [];
% Find all possible choices of L indices out of J.
[Jsub,ind] = npickk(J,state.r);
while (~isempty(Jsub))
% Calculate the criterion when subset JSUB is removed.
if (isempty(t))
critval = feateval(a(:,[setdiff(state.I,Jsub)]),crit);
elseif is_scalar(t)
critval = feateval(a(:,[setdiff(state.I,Jsub)]),crit,t);
else
critval = feateval(a(:,[setdiff(state.I,Jsub)]),crit,...
t(:,[setdiff(state.I,Jsub)]));
end;
% Store the best subset and its criterion value.
if (critval > critval_opt)
critval_opt = critval;
Jsub_opt = Jsub;
end;
[Jsub,ind] = npickk(J,state.r,ind);
end;
state.I = setdiff(state.I,Jsub_opt);
if (critval_opt > state.critval_opt) | ...
(critval_opt == state.critval_opt & ...
length(state.I) < length(state.I_opt)),
state.critval_opt = critval_opt;
state.I_opt = state.I;
end;
line = [length(state.I),critval_opt,...
[-Jsub_opt zeros(1,size(state.res,2)-2-length(Jsub_opt))]];
prprogress(fid,' %d %f \n',line(1:2));
state.res = [state.res; line];
return
% NPICKK - A kind-of-recursive implementation of NCHOOSEK.
%
% Picks K elements out of vector V and returns them in R, with their indices
% in I. Initialise with [R,I] = NPICKK(V,K); subsequent calls should be
% [R,I] = NPICKK(V,K,I). If the set is exhausted, returns R = I = [].
function [r,i] = npickk(v,k,i)
n = length(v);
if (nargin < 3) | (isempty(i))
i = 1:k; j = 1;
else
% Increase the last index.
j = k; i(j) = i(j) + 1;
% While there's an overflow, increase the previous index
% and reset the subsequent ones.
while (i(j) > n-(k-j)) & (j >= 2)
i(j-1) = i(j-1) + 1;
for l = j:k
i(l) = i(l-1) + 1;
end;
j = j - 1;
end;
end;
% If the last index is too large, we're done.
if (i(end) > n)
r = []; i = [];
else
r = v(i);
end;
return
|
github
|
jacksky64/imageProcessing-master
|
prdatasets.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prdatasets.m
| 3,170 |
utf_8
|
a203d844b15ee8e794afdc358bd12a83
|
%PRDATASETS Checks availability of a PRTOOLS dataset
%
% PRDATASETS
%
% Checks the availability of the PRDATASETS directory, downloads the
% Contents file and m-files if necessary and adds it to the search path.
% Lists Contents file.
%
% PRDATASETS(DSET)
%
% Checks the availability of the particular dataset DSET. DSET should be
% the name of the m-file. If it does not exist in the 'prdatasets'
% directory an attempt is made to download it from the PRTools web site.
%
% PRDATASETS(DSET,SIZE,URL)
%
% This command should be used inside a PRDATASETS m-file. It checks the
% availability of the particular dataset file and downloads it if needed.
% SIZE is the size of the dataset in Mbyte, just used to inform the user.
% In URL the web location may be supplied. Default is
% http://prtools.org/prdatafiles/DSET.mat
%
% All downloading is done interactively and should be approved by the user.
%
% SEE ALSO
% DATASETS, PRDATAFILES, PRDOWNLOAD
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function prdatasets(dset,siz,url)
if nargin < 3, url = []; end
if nargin > 0 & isempty(url)
url = ['http://prtools.org/prdatasets/' dset '.mat'];
end
if nargin < 2, siz = []; end
if nargin < 1, dset = []; end
dirname = fullfile(cd,'prdatasets');
if exist('prdatasets/Contents','file') ~= 2
path = input(['The directory prdatasets is not found in the search path.' ...
newline 'If it exists, give the path, otherwise hit the return for an automatic download.' ...
newline 'Path to prdatasets: '],'s');
if ~isempty(path)
addpath(path);
feval(mfilename,dset,siz);
return
else
dirname = fullfile(cd,'prdatasets');
[ss,dirname] = prdownload('http://prtools.org/prdatasets/prdatasets.zip',dirname);
addpath(dirname)
end
end
if isempty(dset) % just list Contents file
help('prdatasets/Contents')
elseif ~isempty(dset) & nargin == 1 % check / load m-file
% this just loads the m-file in case it does not exist and updates the
% Contents file
if strcmp(dset,'renew')
if exist('prdatasets/Contents','file') ~= 2
% no prdatasets in the path, just start
feval(mfilename);
else
dirname = fileparts(which('prdatasets/Contents'));
prdownload('http://prtools.org/prdatasets/prdatasets.zip',dirname);
end
elseif exist(['prdatasets/' dset],'file') ~= 2
prdownload(['http://prtools.org/prdatasets/' dset '.m'],dirname);
prdownload('http://prtools.org/prdatasets/Contents.m',dirname);
end
else % now we load the m-file as well as the data given by the url
% feval(mfilename,dset); % don't do this to allow for different mat-file
% naming
rootdir = fileparts(which('prdatasets/Contents'));
[pp,ff,xx] = fileparts(url);
if exist(fullfile(rootdir,[ff xx]),'file') ~= 2
siz = ['(' num2str(siz) ' MB)'];
q = input(['Dataset is not available, OK to download ' siz ' [y]/n ?'],'s');
if ~isempty(q) & ~strcmp(q,'y')
error('Dataset not found')
end
prdownload(url,rootdir);
disp(['Dataset ' dset ' ready for use'])
end
end
|
github
|
jacksky64/imageProcessing-master
|
gentrunk.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gentrunk.m
| 1,849 |
utf_8
|
3a239e0c7a1bf3700f24ce43dc0e7187
|
%GENTRUNK Generation of Trunk's classification problem of 2 Gaussian classes
%
% A = GENTRUNK(N,K)
%
% INPUT
% N Dataset size, or 2-element array of class sizes (default: [50 50]).
% K Dimensionality of the dataset to be generated (default: 2).
%
% OUTPUT
% A Dataset.
%
% DESCRIPTION
% Generation of a K-dimensional 2-class dataset A of N objects. Both classes
% are Gaussian distributed with the idenity matrix as covariance matrix.
% The means of the first class are defined by ua(j) = 1/sqrt(j). The means
% for the second class are ub = -ua. These means are such that the Nearest
% Mean Classifier always shows peaking for a finite training set.
%
% REFERENCES
% 1. G.V. Trunk, A Problem of Dimensionality: A Simple Example, IEEE Trans.
% Pattern Analysis and Machine Intelligence, vol. 1, pp. 306-307, 1979
% 2. A.K. Jain, R.P.W. Duin, and J. Mao, Statistical Pattern Recognition:
% A Review, IEEE Transactions on Pattern Analysis and Machine Intelligence,
% vol. 22, pp. 4-37, 2000.
%
% EXAMPLE
% a = gentrunk([1000 1000],200);
% e = clevalf(a,nmc,[1:9 10:5:25 50:25:200],[5 5],25);
% plote(e)
%
% SEE ALSO
% DATASETS, PRDATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: gentrunk.m,v 1.2 2009/01/27 13:01:42 duin Exp $
function A = gendats (N,k)
prtrace(mfilename);
if (nargin < 1), N = [50 50]; end
if (nargin < 2), k = 50; end
% Set equal priors and generate random class sizes according to these.
p = [0.5 0.5]; N = genclass(N,p);
% Unit covariance matrices
GA = eye(k); GB = eye(k);
% Trunk means
ma = 1./sqrt(1:k);
mb = -ma;
U = dataset([ma;mb],[1 2]');
U = setprior(U,p);
% Create dataset.
A = gendatgauss(N,U,cat(3,GA,GB));
A = setname(A,'Trunk''s Problem');
return
|
github
|
jacksky64/imageProcessing-master
|
setdat.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/setdat.m
| 1,305 |
utf_8
|
c0fb96a1040be90efb0e4d9553ba0e5d
|
%SETDAT Reset data and feature labels of dataset for classification output
%
% A = SETDAT(A,DATA,W)
%
% INPUT
% A Dataset
% DATA Dataset or double
% W Mapping (optional)
%
% OUTPUT
% A Dataset
%
% DESCRIPTION
% The data in the dataset A is replaced by DATA (dataset or double). The
% number of objects in A and DATA should be equal. Optionally, A is given
% the feature labels and the output size as defined by the the mapping W.
% This call is identical to:
% A = SETDATA(A,DATA);
% A = SET(A,'featlab',GETLABELS(W),'featsize',GETSIZE_OUT(W));
%
% SEE ALSO
% DATASET, SETDATA
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: setdat.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function a = setdat(a,b,w)
prtrace(mfilename);
if ~isdataset(a)
a = dataset(a);
end
a = setdata(a,b);
if (nargin > 2)
if (~isa(w,'mapping'))
error('Third parameter should be mapping')
end
% Special case: 2 classes, p(class2) = 1-p(class1).
%No! this should not be done here!
%if (size(a,2) == 1) & (size(w,2) == 2)
% a = [a 1-a];
%end
% Add attributes of W to A.
a = set(a,'featlab',getlabels(w),'featsize',getsize_out(w));
end
return;
|
github
|
jacksky64/imageProcessing-master
|
testc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testc.m
| 15,179 |
utf_8
|
80b4f31f69f8abb91b74a44a0c35913c
|
%TESTC Test classifier, error / performance estimation
%
% [E,C] = TESTC(A*W,TYPE)
% [E,C] = TESTC(A,W,TYPE)
% E = A*W*TESTC([],TYPE)
%
% [E,F] = TESTC(A*W,TYPE,LABEL)
% [E,F] = TESTC(A,W,TYPE,LABEL)
% E = A*W*TESTC([],TYPE,LABEL)
%
% INPUT
% A Dataset
% W Trained classifier mapping
% TYPE Type of performance estimate, default: probability of error
% LABEL Target class, default: none
%
% OUTPUT
% E Error / performance estimate
% C Number of erroneously classified objects per class.
% They are sorted according to A.LABLIST
% F Error / performance estimate of the non-target classes
%
% DESCRIPTION
% This routine supplies several performance estimates for a trained
% classifier W based on a test dataset A. It is possible to supply a cell
% array of datasets {A*W}, an N x 1 cell array of datasets {A} and an N x M
% cell array of mappings {W}.
%
% A should contain test objects for every class assigned by W.
% Objects in A belonging to different classes than defined for W as well
% as unlabeled objects are neglected. Note that this implies that TESTC
% applied to a rejecting classifier (e.g. REJECTC) estimates the
% performance on the not rejected objects only. By
% [E,C] = TESTC(A,W); E = (C./CLASSSIZES(A))*GETPRIOR(A)';
% the classification error with respect to all objects in A may be
% computed. Use CONFMAT for an overview of the total class assignment
% including the unlabeled (rejected) objects.
%
% In case of missing classes in A, [E,C] = TESTC(A*W) returns in E a NaN
% but in C still the number of erroneously classified objects per class.
%
% If LABEL is given, the performance estimate relates just to that class as
% target class. If LABEL is not given a class average is returned weighted
% by the class priors.
%
% The following performance measures are supported for TYPE:
% 'crisp' Expected classification error based on error counting,
% weighted by the class priors (default).
% 'FN' E False negative
% F False positive
% 'TP' E True positive
% F True negative
% 'soft' Expected classification error based on soft error
% summation, i.e. a sum of the absolute difference between
% classifier output and target, weighted by class priors.
% 'F' Lissack and Fu error estimate
% 'mse' Expected mean square difference between classifier output
% and target (based on soft labels), weighted by class
% priors.
% 'auc' Area under the ROC curve (this is an error and not a
% performance!). For multi class problems this is the
% weigthed average (by class priors) of the one-against-rest
% contributions of the classes.
% 'precision' E Fraction of true target objects among the objects
% classified as target. The target class is defined by LABEL.
% Priors are not used.
% F Recall, fraction of correctly classified objects in the
% target class. Priors are not used.
% 'sensitivity' E Fraction of correctly classified objects in the target
% class (defined by LABEL). Priors are not used.
% Sensitivity as used her is identical to recall.
% F Specificity, fraction non target objects that are not
% classified into the target class (defined by LABEL).
% Priors are not used.
%
% EXAMPLES
% See PREX_PLOTC.
%
% SEE ALSO
% MAPPINGS, DATASETS, CONFMAT, REJECTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: testc.m,v 1.19 2010/02/18 15:57:07 duin Exp $
function [OUT1,OUT2] = testc(a,w,type,label)
prtrace(mfilename);
if nargin < 4, label = []; end
if nargin < 3, type = []; end
if nargin < 2, w = []; end
if nargin < 1, a = []; end
if isstr(w) % takes care of testc(a*w,type,label)
label = type; type = w; w = [];
end
%
% if isempty(type)
% type = 'crisp';
% end
if (isempty(a)) % prepares a*testc([],w,type,label), or a*testc([],type,label)
out1 = mapping(mfilename,'fixed',{w,type,label});
out1 = setname(out1,'testc');
out1 = setbatch(out1,0); % Don't run in batch mode
out2 = [];
elseif (~ismapping(w) & ~iscell(w)) | (ismapping(w) & isfixed(w) & strcmp(getname(w),'testc'))
% call like testc(a*w,type,label), or a*testc([],w,type,label) which
% results in testc(a*w,V) in which V = testc([],type,label)
if ismapping(w) % retrieve parameters stored in testc([],w,type,label
label = getdata(w,3);
type = getdata(w,2);
w = getdata(w,1);
end
if (iscell(a))
% If this argument is a cell array, recursively call this
% function to get errors for all elements in the cell array.
out1 = zeros(size(a));
out2 = cell(size(a));
for j1 = 1:size(a,1)
for j2 = 1:size(a,2)
[out1(j1,j2),out2{j1,j2}] = feval(mfilename,a{j1,j2},w,type,label);
end
end
elseif (isdatafile(a)) % datafile needs some handling as we need to
% process all objects separately
c = getsize(a,3);
out2 = zeros(1,c);
next = 1;
a = setprior(a,getprior(a));
while next > 0
[b,next] = readdatafile(a,next);
if isempty(w)
[out1,class_err] = feval(mfilename,dataset(b));
else
[out1,class_err] = feval(mfilename,b,w,type,label);
end
out2 = out2 + class_err;
end
if isempty(a.prior)
out1 = sum(out2)/size(a,1);
else
p = getprior(a);
csizes = classsizes(a);
if any(csizes == 0)
out1 = NaN;
prwarning(1,'Some classses have no test objects')
else
out1 = (out2./classsizes(a))*p';
end
end
else % here we are for the real work
isdataset(a); % we need a real dataset for evaluation
if (ismapping(w) & istrained(w))
a = a*w;
end
fflab = renumlab(getfeatlab(a));
if any(fflab == 0) % reject option! Allowed?
if isempty(strmatch(type,char('crisp','FN','TP','precision','sensitivity')))
error('Reject option incompatible with desired error measure')
else % remove all objects to be rejected
reject_col = find(fflab == 0);
[ma,J] = max(+a,[],2);
L = find(J~=reject_col);
a = a(L,:);
end
end
a = a*maxc; % takes care that every class appears as a single column in a
%a = remclass(a);
lablist = getlablist(a); % classes of interest
featlab = getfeatlab(a);
flab = renumlab(featlab,lablist);
csizes = classsizes(a);
if any(flab == 0)
prwarning(1,'Some classes assigned by the classifier have no test objects')
end
if any (csizes == 0)
if nargout < 2 | ~isempty(label) % no error / performance measure can be returned
error('Some classes have no test objects')
else % we can, however, return, the error per class
prwarning(2,'Some classes have no test objects')
c = getsize(a,3);
I = matchlablist(a*labeld,lablist);
nlab = getnlab(a);
OUT2 = zeros(1,c);
for j=1:c
J = find(nlab==j);
OUT2(j) = sum(I(J)~=j);
end
OUT1 = NaN;
end
return
end
clab = renumlab(lablist,featlab);
if any(clab == 0)
prwarning(1,'Superfluous test objects found, they will be neglected')
J = find(clab~=0);
a = seldat(a,J);
a = setlablist(a);
csizes = csizes(J);
end
[m,k,c] = getsize(a); p = getprior(a); labtype = getlabtype(a);
if isempty(type) % set default error measure types
if islabtype(a,'crisp')
type = 'crisp';
elseif islabtype(a,'soft')
type = 'soft';
else
type = 'mse'
end
end
confm = cmat(a); % compute confusion matrix
if isempty(label)
lablist = getlablist(a);
out2 = (csizes - diag(confm)');
out = zeros(1,c);
out1 = 0;
for j = 1:c % compute crit one-against-rest
% confm2 = [confm(j,j) sum(confm(j,:))-confm(j,j); sum(confm(:,j))-confm(j,j) ...
% sum(confm(:))-sum(confm(:,j))-sum(confm(j,:)) + confm(j,j)];
confm2 = [confm(j,j) csizes(j)-confm(j,j); sum(confm(:,j))-confm(j,j) ...
sum(confm(:))-sum(confm(:,j))-csizes(j) + confm(j,j)];
b = seldat(a,j);
out(j) = comp_crit(type,confm2,a,j,lablist(j,:));
if isempty(a.prior)
out1 = out1 + out(j);
else
out1 = out1 + p(j) * out(j) / size(b,1);
end
end
if isempty(a.prior)
out1 = out1 / m;
end
else
n = getclassi(a,label);
confm2 = [confm(n,n) sum(confm(n,:))-confm(n,n); sum(confm(:,n))-confm(n,n) ...
sum(confm(:))-sum(confm(:,n))-sum(confm(n,:)) + confm(n,n)];
[out1 out2] = comp_crit(type,confm2,a,n,label);
out1 = out1/csizes(n);
out2 = out2/(m-csizes(n));
end
end
elseif (iscell(a)) | (iscell(w))
% If there are two input arguments and either of them is a cell array,
% recursively call this function on each of the cells.
% Non-cell array inputs are turned into 1 x 1 cell arrays.
if (~iscell(a)), a = {a}; end
if (~iscell(w)), w = {w}; end
if (min(size(a) > 1))
error('2D cell arrays of datasets not supported')
end
% Check whether the number of datasets matches the number of mappings.
if (length(a) == 1)
a = repmat(a,size(w,1));
elseif (min(size(w)) == 1 & length(a) ~= length(w)) | ...
(min(size(w)) > 1 & length(a) ~= size(w,1))
error('Number of datasets does not match cell array size of classifiers.')
end
% Now recursively call this function for each combination of dataset
% A{I} and mapping W{I,J}.
out1 = cell(size(w));
out2 = cell(size(w));
for i=1:size(w,1)
for j=1:size(w,2)
[out1{i,j},out2{i,j}] = feval(mfilename,a{i}*w{i,j},type,label);
end
end
else
% Assert that the second argument is a trained mapping, and call
% this function on the mapped data.
ismapping(w); istrained(w);
[out1,out2]= feval(mfilename,a*w,type,label);
end
% If there are no output arguments, display the error(s) calculated.
% Otherwise, copy the calculated errors to the output arguments.
if (nargout == 0) & (nargin > 0)
if (iscell(a))
if (nargin == 1)
for j1 = 1:size(a,1)
for j2 = 1:size(a,2)
disp(['Mean classification error on ' ...
num2str(size(a{j1,j2},1)) ' test objects: ' num2str(out1(j1,j2))]);
end
end
else
fprintf('\n Test results result for');
disperror(a,w(1,:),cell2mat(out1));
end
else
if (nargin == 1)
disp(['Mean classification error on ' num2str(size(a,1)) ' test objects: ' num2str(out1)])
else
if ~isempty(w) %DXD empty mapping can happen after a*w*testc
fprintf(' %s',getname(w,20));
else %DXD is this a good alternative?
fprintf(' %s',getname(a,20));
end
fprintf(' %5.3f',out1);
fprintf('\n');
end
end
else
OUT1 = out1;
OUT2 = out2;
end
return
%TESTAUC Multiclass error area under the ROC
%
% E = TESTAUC(A*W)
% E = TESTAUC(A,W)
% E = A*W*TESTAUC
%
% INPUT
% A Dataset to be classified
% W Classifier
%
% OUTPUT
% E Error, Area under the ROC
%
% DESCRIPTION
% The area under the error ROC is computed for the datset A w.r.t. the
% classifer W. The estimator is based on a rank analysis of the classifier
% outcomes. Ties are broken by a two-way sorting and averaging.
%
% The multiclass situation is solved by averaging over all outcomes of
% the one-against-rest ROCs.
%
% Note that E is an error and not a performance measure like the AUC often
% used in literature.
%
% SEE ALSO
% DATASETS, MAPPINGS, TESTC, ROC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function e = testauc(a,w,n)
prtrace(mfilename);
if nargin < 3, n = []; end
if (nargin == 0) | (isempty(a))
% No input arguments given: return mapping information.
e = mapping(mfilename,'fixed',{label});
e = setbatch(e,0);
return
elseif (nargin == 1 | isempty(w))
% Classification matrix already computed
d = a;
else
% Compute classification matrix now
d = a*w;
end
[m,k,c] = getsize(d);
s = classsizes(d);
if k == 1 % classifier with a single class outcome, make two for consistency
d = [d 1-d];
k = 2;
end
if isempty(n)
e = zeros(1,c);
for j = 1:c
e(j) = auc_one(d,s,j);
end
e = e*getprior(d)';
else
e = auc_one(d,s,n);
end
return
function e = auc_one(d,s,j)
% compute AUC for class j versus rest
m = size(d,1);
lablist = getlablist(d); % class names
n = findfeatlab(d,lablist(j,:));
% forward sorting
[ds,J1] = sort(-d(:,n)); [j1,K1] = sort(J1);
% backward sorting to solve ties
[ds,J2] = sort(flipud(-d(:,n))); [j2,K2] = sort(J2); K2 = flipud(K2);
% get all object indices for this class
K = findnlab(d,j);
% retrieve number of wrong pairs
e = (sum(K1(K)) + sum(K2(K))-(s(j)*(s(j)+1)))/2;
% error contribution
e = e / ((m-s(j))*s(j));
return
function confm = cmat(a)
% simplified confusion matrix procedure, class order as in c.lablist
% a should be a classification matrix with the same feature labels
% (no doubles) as a.lablist
lablist = getlablist(a);
featlab = getfeatlab(a);
N = getsize(a,3);
flab = renumlab(featlab,lablist);
nlab = getnlab(a);
aa = +a;
confm = zeros(N,N);
for j=1:N
J = find(nlab==j);
[mx,K] = max(aa(J,:),[],2);
confm(j,:) = histc(flab(K)',1:N);
end
function [out1,out2] = comp_crit(type,c,a,n,label)
% c : 2 x 2 confusion matrix
% a : classification data
% n : relevant class
switch type
case 'crisp'
out1 = c(1,2);
out2 = c(2,1);
case 'FN'
out1 = c(1,2);
out2 = c(2,1); % FP
case 'TP'
out1 = c(1,1);
out2 = c(2,2); % TN
case 'precision'
out1 = c(1,1)/(c(1,1)+c(2,1));
out1 = out1*(c(1,1)+c(1,2)); % sum of per sample contributions
out2 = c(1,1)/(c(1,1)+c(1,2)); % recall (=sensitivity)
out2 = out2*(c(2,2)+c(2,1)); % sum of per sample contributions
case 'sensitivity'
out1 = c(1,1)/(c(1,1)+c(1,2));
out1 = out1*(c(1,1)+c(1,2)); % sum of per sample contributions
out2 = c(2,2)/(c(2,1)+c(2,2)); % specificity
out2 = out2*(c(2,2)+c(2,1)); % sum of per sample contributions
case 'soft' % normalised difference between desired and real targets
a = setlabtype(a,'soft')*classc;
t = gettargets(a);
k = findfeatlab(a,label);
d = abs(+a(:,k) - t(:,n));
J = find(isnan(d));
d(J) = ones(size(J));
out1 = sum(d)/2; % needed for consistency as every error is counted twice
%out1 = sum(d);
out2 = [];
case 'F' % Lissack and Fu error
b = seldat(a,n)*classc;
out1 = sum(1-max(+b,[],2));
out2 = [];
case {'mse','MSE'}
k = findfeatlab(a,label);
b = seldat(a,n);
out1 = sum((+b(:,k)-gettargets(b)).^2);
case {'nmse','NMSE'} % use normalised outputs
k = findfeatlab(a,label);
b = seldat(a,n)*classc;
out1 = sum((+b(:,k)-gettargets(b)).^2);
case {'auc','AUC'}
out1 = testauc(a,[],n)*(c(1,1)+c(1,2));% sum of per sample contributions
out2 = [];
otherwise
error('Error / performance type not found')
end
|
github
|
jacksky64/imageProcessing-master
|
labeld.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/labeld.m
| 3,452 |
utf_8
|
a0eb48345f2f78a977286d3b730bf6ee
|
%LABELD Find labels of classification dataset (perform crisp classification)
%
% LABELS = LABELD(Z)
% LABELS = Z*LABELD
% LABELS = LABELD(A,W)
% LABELS = A*W*LABELD
% LABELS = LABELD(Z,THRESH)
% LABELS = Z*LABELD([],THRESH)
% LABELS = LABELD(A,W,THRESH)
% LABELS = A*W*LABELD([],THRESH)
%
% INPUT
% Z Classification dataset, or
% A,W Dataset and classifier mapping
% THRESH Rejection threshold
%
% OUTPUT
% LABELS List of labels
%
% DESCRIPTION
% Returns the labels of the classification dataset Z (typically the result
% of a mapping or classification A*W). For each object in Z (i.e. each row)
% the feature label or class label (i.e. the column label) of the maximum
% column value is returned.
%
% Effectively, this performs the classification. It can also be considered
% as a conversion from soft labels Z to crisp labels.
%
% When the parameter THRESH is supplied, then all objects which
% classifier output falls below this value are rejected. The returned
% label is then NaN or a string with spaces (depending if the labels are
% numeric or string). Because the output of the classifier is used, it
% is recommended to convert the output to a posterior prob. output using
% CLASSC. (David Tax, 27-12-2004)
%
% SEE ALSO
% MAPPINGS, DATASETS, TESTC, PLOTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function labels = labeld(a,w,thresh)
prtrace(mfilename);
% Add the possibility to reject objects for which the posterior is
% too low:
if (nargin < 3)
thresh = [];
end
if (nargin == 2) & isa(w,'double') % we did something like labeld(z,0.3)
thresh = w;
w = [];
end
if (nargin < 2)
w = [];
end
if (nargin == 0) | isempty(a)
% Untrained mapping.
labels = mapping(mfilename,'fixed',{thresh});
elseif isempty(w)
if (isdatafile(a)) % datafile needs to process objects separately
labels = cell(size(a,1),1);
next = 1;
while next > 0
[b,next,J] = readdatafile(a,next);
labs = feval(mfilename,b,[],thresh);
for i=1:length(J)
labels{J(i)} = labs(i,:);
end
end
if isstr(labels{1})
labels = char(labels);
else
labels = cell2mat(labels);
end
return
end
% In a classified dataset, the feature labels contain the output
% of the classifier.
[m,k] = size(a); featlist = getfeatlab(a);
Jrej = []; % as a start, we don't reject objects
if (k == 1)
% If there is one output, assume it's a 2-class discriminant:
% decision boundary = 0.
J = 2 - (double(a) >= 0);
if ~isempty(thresh)
warning('Inproper thresholding of the 2-class dataset, please use classc.');
end
else
% Otherwise, pick the column containing the maximum output.
[dummy,J] = max(+a,[],2);
% Reject the objects which have posteriors lower than the
% threshold
if ~isempty(thresh)
Jrej = find(dummy<thresh);
end
end
labels = featlist(J,:);
% Take care for the rejected objects:
if ~isempty(Jrej)
if isa(featlist,'double')
labels(Jrej) = NaN;
elseif isa(featlist,'char')
labels(Jrej,:) = repmat(' ',size(featlist(1,:)) ); % Trick!:-)
else
error('The featlist of A is confusing. Cannot make a reject label');
end
end
else
% Just construct classified dataset and call again.
labels = feval(mfilename,a*w,thresh);
end
return
|
github
|
jacksky64/imageProcessing-master
|
nmsc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nmsc.m
| 2,013 |
utf_8
|
d6f267790fb4836284cfe76cb9641f13
|
%NMSC Nearest Mean Scaled Classifier
%
% W = NMSC(A)
% W = A*NMSC
%
% INPUT
% A Trainign dataset
%
% OUTPUT
% W Nearest Mean Scaled Classifier mapping
%
% DESCRIPTION
% Computation of the linear discriminant for the classes in the dataset A
% assuming normal distributions with zero covariances and equal class variances.
% The use of soft labels is supported.
%
% The difference with NMC is that NMSC is based on an assumption of normal
% distributions and thereby automatically scales the features and is
% sensitive to class priors. NMC is a plain nearest mean classifier that is
% feature scaling sensitive and unsensitive to class priors.
%
% SEE ALSO
% DATASETS, MAPPINGS, NMC, LDC ,FISHERC, QDC, UDC
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: nmsc.m,v 1.7 2008/01/25 10:20:07 duin Exp $
function w = nmsc(a)
prtrace(mfilename);
% No input arguments: return an untrained mapping.
if (nargin < 1) | (isempty(a))
w = mapping(mfilename);
w = setname(w,'Scaled Nearest Mean');
return
end
islabtype(a,'crisp','soft');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
[m,k,c] = getsize(a);
p = getprior(a);
a = setprior(a,p);
[U,GG] = meancov(a);
% All class covariance matrices are assumed to be diagonal. They are
% weighted by the priors, unlike the standard nearest mean classifier (NMC).
G = zeros(c,k);
for j = 1:c
G(j,:) = diag(GG(:,:,j))';
end
G = p*G;
% The two-class case is special, as it can be conveniently stored as an
% affine mapping.
if (c == 2)
ua = +U(1,:); ub = +U(2,:);
R = G*(ua - ub)';
R = ((ua - ub)./G)';
offset = ((ub./G)*ub' - (ua./G)*ua')/2 + log(p(1)/p(2));
w = affine(R,offset,a,getlablist(a),k,c);
w = cnormc(w,a);
else
pars.mean = +U; pars.cov = G; pars.prior = p;
w = normal_map(pars,getlab(U),k,c);
end
w = setname(w,'Scaled Nearest Mean');
w = setcost(w,a);
return
|
github
|
jacksky64/imageProcessing-master
|
testauc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/testauc.m
| 2,064 |
utf_8
|
f5ad0b21b349ec323644d52b39eb9be6
|
%TESTAUC Multiclass error area under the ROC
%
% E = TESTAUC(A*W)
% E = TESTAUC(A,W)
% E = A*W*TESTAUC
%
% INPUT
% A Dataset to be classified
% W Classifier
%
% OUTPUT
% E Error, Area under the ROC
%
% DESCRIPTION
% The area under the ROC is computed for the datset A w.r.t. the
% classifer W. The estimator is based on a rank analysis of the classifier
% outcomes. Ties are broken by a two-way sorting and averaging.
%
% The multiclass situation is solved by averaging over all outcomes of
% the one-against-rest ROCs.
%
% Note that E is an error and not a performance measure like the AUC often
% used in literature.
%
% SEE ALSO
% DATASETS, MAPPINGS, TESTC, ROC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function e = testauc(a,w)
prtrace(mfilename);
if (nargin == 0) | (isempty(a))
% No input arguments given: return mapping information.
e = mapping(mfilename,'fixed');
return
elseif (nargin == 1)
% Classification matrix already computed
d = a;
else
% Compute classification matrix now
d = a*w;
end
[m,k,c] = getsize(d);
s = classsizes(d);
if k == 1 % classifier with a single class outcome, make two for consistency
d = [d 1-d];
k = 2;
end
class_names = getfeatlab(d); % class names
e = zeros(1,c);
for j=1:c % run over all classes
% forward sorting
[ds,J1] = sort(-d(:,j)); [j1,K1] = sort(J1);
% backward sorting to solve ties
[ds,J2] = sort(flipud(-d(:,j))); [j2,K2] = sort(J2); K2 = flipud(K2);
% get all object indices for this class
K = findlabels(d,class_names(j,:));
% retrieve number of wrong pairs
e(j) = (sum(K1(K)) + sum(K2(K))-(s(j)*(s(j)+1)))/2;
% error contribution
e(j) = e(j) / ((m-s(j))*s(j));
end
% average over all classes
e = mean(e);
|
github
|
jacksky64/imageProcessing-master
|
genclass.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/genclass.m
| 1,579 |
utf_8
|
b363022121705e34497b3a5c067eabd1
|
%GENCLASS Generate class frequency distribution
%
% M = GENCLASS(N,P)
%
% INPUT
% N Number (scalar)
% P Prior probabilities
%
% OUTPUT
% M Class frequency distribution
%
% DESCRIPTION
% Generates a class frequency distribution M of N (scalar) samples
% over a set of classes with prior probabilities given by the vector P.
% The numbers of elements in P determines the number of classes and
% thereby the number of elements in M. P should be such that SUM(P) = 1.
% If N is a vector with length C, then M=N is returned. This transparent
% behavior is implemented to avoid tests in other routines.
%
% Note that this is a random process, so M = GENCLASS(100,[0.5, 0.5])
% may result in M = [45 55].
%
% This routines is used in various data generation routines like
% GENDATH to determine the distribution of the objects over the classes.
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: genclass.m,v 1.3 2006/09/26 12:55:32 duin Exp $
function N = genclass(N,p)
prtrace(mfilename);
if nargin < 2 | isempty(p)
p = ones(1,length(N))/length(N);
end
c = length(p);
if length(N) == c
;
elseif length(N) > 1
error('Mismatch in numbers of classes')
else
if nargin < 2 | isempty(p)
p = repmat(1/c,1,c);
end
P = cumsum(p);
if abs(P(c)-1) > 1e-10
error('Sum of class prior probabilities should be one')
end
X = rand(N,1);
K = repmat(X,1,c) < repmat(P(:)',N,1);
L = sum(K,1);
N = L - [0 L(1:c-1)];
end
return
|
github
|
jacksky64/imageProcessing-master
|
prtools_news.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prtools_news.m
| 2,342 |
utf_8
|
b439aced7644c0559d07b4f2e2542d8c
|
%PRTOOLS_NEWS List PRTools news and download new versions
%
% PRTOOLS_NEWS List PRTools news
% PRTOOLS_NEWS(DIRNAME,UNZIP) Reload PRTools
%
% DIRNAME is the directory to download PRTools. If UNZIP == 1
% (default 0) it is unzipped.
function out = prtools_news(dirname,unzip_link)
% to be implemented later:
% try
% % fake, just to be sure that PRTools datasets are used
% dataset(rand(5,2),genlab(5),'name','apple');
% catch
% error([newline 'PRTools has not been properly installed. It should be at the top of' ...
% newline 'the Matlab path. After restarting Matlab adjust and save the path' ...
% newline 'and give ''prtools'' as the first command']);
% end
%
% if nargin > 0 & ~isempty(dirname)
% if dirname == -1
% return % this was just a test to see whether PRTools was properly installed
% end
% end
if ~usejava('jvm')
if nargout == 1
out = ' No Java (JVM) installed, some commands cannot be used';
elseif nargin == 0
error('Java (JVM) has not been installed, so the ''prtools''-command does not work')
end
end
if nargin < 2, unzip_link = 0; end
[links,mod] = readlinks;
if nargin == 0
if nargout == 0
if isempty(links)
error('Error in reaching PRTools web links');
else
web(links{1},'-browser');
end
else
out = mod; % needed for call in dataset
end
elseif nargin == 1 & dirname == 0 % read mod
disp(mod);
elseif isempty(links)
error('Error in reaching PRTools web links');
else
if isempty(dirname)
dirname = pwd;
end
if ~isstr(dirname)
n = dirname;
dirname = pwd;
else
n = 2;
end
[pp,ff] = fileparts(links{n});
if unzip_link
[pp,ff] = fileparts(links{n});
fprintf(1,'Downloading and unzipping %s ....\n',ff)
unzip(links{n},dirname);
disp('Download ready');
else
if exist(dirname) == 0
mkdir(dirname);
end
fprintf(1,'Downloading %s ....\n',ff)
[pathname,filename,ext] = fileparts(links{n});
fname = fullfile(dirname,[filename ext]);
if ~usejava('jvm') & isunix
[status,fname] = unix('wget -q -O - http://prtools.org/files/prtoolslinks.txt');
if status > 1
error('Download failed, no Java?')
end
else
[pathname,status] = urlwrite(links{n},fname);
end
disp('Download ready');
end
end
|
github
|
jacksky64/imageProcessing-master
|
gendatw.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatw.m
| 834 |
utf_8
|
c8923ae31b9b5ca941d682f2f264e9ce
|
%GENDATW Sample dataset by given weigths
%
% B = GENDATW(A,V,N)
%
% INPUT
% A Dataset
% V Vector with weigths for each object in A
% N Number of objects to be generated (default size A);
%
% OUTPUT
% B Dataset
%
% DESCRIPTION
% The dataset A is sampled using the weigths in V as a prior distribution.
function b = gendatw(a,v,n)
isdataset(a);
if nargin < 3, n = size(a,1); end
v = v./sum(v);
if any(v<0)
error('Weights should be positive');
end
mins = 0;
nn = 0;
while(mins < 2)
N = genclass(n,v);
L = [];
while any(N > 0)
L = [L find(N > 0)];
N = N-1;
end
b = a(L,:);
mins = min(classsizes(b));
nn = nn + 1;
if nn > 100
error('Problems with weighted subsampling: classes have disappeared. Please enlarge training set.')
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
kernelm.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/kernelm.m
| 5,348 |
utf_8
|
3e8ef13d0db7c522ec59556fa1e416ba
|
%KERNELM Kernel mapping, dissimilarity representation
%
% [W,J] = KERNELM(A,KERNEL,SELECT,P1,P2 , ...)
% W = A*KERNELM([],KERNEL,SELECT,P1,P2 , ...)
% K = B*W
%
% INPUT
% A,B Datasets
% KERNEL Untrained kernel / dissimilarity representation,
% a mapping computing proximities between objects.
% default: Euclidean dissimilarities: PROXM([],'d',1)
% SELECT Name of object selection procedure, see below
% P1,P2, ... Additional parameters for SELECT
%
% OUTPUT
% W Mapping
% J Vector with indices of selected objects for representation
% K Kernel matrix, dissimilarity representation,
% size [SIZE(B,1) LENGTH(J)]
%
% DESCRIPTION
% Computes the kernel mapping W for the representation objects in A. The
% computation of the kernel matrix, which is a proximity matrix (similarities
% or dissimilarities) should be defined in KERNEL by an untrained mapping like
% PROXM for predefined proximities or USERKERNEL for user specified
% proximities.
% A*KERNEL should 'train' the kernel, i.e. specify A as representation set.
% B*(A*KERNEL) should compute the kernel matrix: a dataset.
%
% Initially, the kernel mapping has a size [SIZE(A,2) SIZE(A,1)]. For
% increased efficiency or accuracy the representation set may be reduced
% by a routine given by the string SELECT to select to objects J, using
% possibly additional parameters P1, P2, etcetera. This option of
% representation set reduction is the only difference between the use of
% KERNELM and routines like PROXM and USERKERNEL.
%
% The following choices for SELECT are supported:
%
% 'random' random selection of P1 objects, maximum P2
% 'gendat' [X,Y,J] = GENDAT(A,P1)
% 'kcentres' [LAB,J] = KCENTRES(DISTM(A),P1,P2)
% 'modeseek' [LAB,J] = MODESEEK(DISTM(A),P1)
% 'edicon' J = EDICON(DISTM(A),P1,P2,P3)
% 'featsel' J = +FEATSELM(A*KERNELM(A,TYPE,P),P1,P2,P3)
%
% REFERENCES
% 1. E.Pekalska, R.P.W.Duin, P.Paclik, Prototype selection for dissimilarity-
% based classification, Pattern Recognition, vol. 39, no. 2, 2006, 189-208.
% 2. E.Pekalska and R.P.W.Duin, The Dissimilarity Representation for Pattern
% Recognition, Foundations and Applications, World Scientific, 2005, 1-607.
%
% EXAMPLE
% A = GENDATB;
% W = (SCALEM*KERNELM([],[],'random',5)*LOGLC);
% SCATTERD(A)
% PLOTC(A*W)
%
% SEE ALSO
% DATASETS, MAPPINGS, PROXM, USERKERNEL
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: kernelm.m,v 1.7 2007/07/10 08:25:29 duin Exp $
function w = kernelm(a,kernel,select,varargin);
prtrace(mfilename);
if isempty(varargin), varargin = {[] [] []}; end
if length(varargin) == 1, varargin = {varargin{:} [] []}; end
if length(varargin) == 2, varargin = {varargin{:} []}; end
if (nargin < 3)
select = [];
prwarning(4,'No representation set reduction specified.')
end
if (nargin < 2) | isempty(kernel)
prwarning(3,'No kernel mapping specified. Euclidean distances assumed')
kernel = proxm([],'d',1);
end
if (nargin < 1) | (isempty(a))
% Definition: an untrained mapping.
w = mapping(mfilename,{kernel,select,varargin{:}});
w = setname(w,'Kernel mapping');
elseif isstr(kernel) % old format of call: kernelm(a,type,p,n), training
type = kernel;
p = select;
if ~isempty(varargin)
if length(varargin) > 1
error('Wrong parameters supplied')
end
n = varargin{1};
else
n = [];
end
[m,k] = size(a);
kernel = proxm([],type,p);
w = mapping(mfilename,'trained',{a*kernel},getlab(a),k,m);
if ~isempty(n)
w = w*pca(a*w,n);
end
w = setname(w,'Kernel Mapping');
elseif isa(kernel,'mapping') & ~strcmp(getmapping_file(kernel),mfilename) % training
a = testdatasize(a);
a = testdatasize(a,'objects');
isuntrained(kernel);
[m,k] = size(a);
%w = mapping('kernelm','trained',{a*kernel},getlab(a),k,m);
if isempty(select)
w = mapping('kernelm','trained',{a*kernel},getlab(a),k,m);
elseif ismapping(select)
r = a*select;
w = mapping('kernelm','trained',{r*kernel},getlab(a),k,size(r,1));
else
switch select
case 'random'
J = randperm(m);
n = varargin{1};
if isempty(n) | n > m
error('Number of objects to be selected not given or too large')
end
if n < 1, n = ceil(n*m); end % fraction given
if ~isempty(varargin{2})
n = min(n,varargin{2});
end
J = J(1:n);
case 'gendat'
[x,y,J] = gendat(a,varargin{1});
case 'kcentres'
[lab,J] = kcentres(distm(a),varargin{1:2});
case 'modeseek'
[lab,J] = modeseek(distm(a),varargin{1});
case 'edicon'
J = edicon(distm(a),varargin{1:3});
case 'featsel'
w = mapping('kernelm','trained',{a*kernel},getlab(a),k,m);
J = +featselm(a*w,varargin{1:3});
otherwise
error('Unknown choice for object selection')
end
% redefine mapping with reduced representation set
labels_out = getlab(a);
w = mapping('kernelm','trained',{a(J,:)*kernel},labels_out(J,:),k,length(J));
end
w = setname(w,'Kernel Mapping');
else % Execution of the mapping, w will be a dataset.
kern = getdata(kernel,1); % trained kernel is stored in datafield
K = a*kern;
w = setdat(a,K,kern);
end
return;
|
github
|
jacksky64/imageProcessing-master
|
rbsvc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rbsvc.m
| 2,053 |
utf_8
|
41cca5dbfaed944ed3654474ee369f0b
|
%RBSVC Automatic radial basis Support Vector Classifier
%
% [W,KERNEL,NU] = RBSVC(A)
%
% INPUT
% A Dataset
%
% OUTPUT
% W Mapping: Radial Basis Support Vector Classifier
% KERNEL Untrained mapping, representing the optimised kernel
% NU Resulting value for NU from NUSVC
%
% DESCRIPTION
% This routine computes a classifier by NUSVC using a radial basis kernel
% with an optimised standard deviation by REGOPTC. The resulting classifier
% W is identical to NUSVC(A,KERNEL,NU). As the kernel optimisation is based
% on internal cross-validation the dataset A should be sufficiently large.
% Moreover it is very time-consuming as the kernel optimisation needs
% about 100 calls to SVC.
%
% SEE ALSO
% MAPPINGS, DATASETS, PROXM, SVC, NUSVC, REGOPTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [w,kernel,nu] = rbsvc(a,sig)
if nargin < 2 | isempty(sig)
sig = NaN;
end
if nargin < 1 | isempty(a)
w = mapping(mfilename,{sig});
else
islabtype(a,'crisp');
isvaldfile(a,2,2); % at least 1 object per class, 2 classes
a = testdatasize(a,'objects');
c = getsize(a,3);
if (c > 2)
% Compute c classifiers: each class against all others.
w = mclassc(a,mapping(mfilename,{sig}));
else
if isnan(sig) % optimise sigma
% find upper bound
d = sqrt(+distm(a));
sigmax = min(max(d)); % max: smallest furthest neighbor distance
% find lower bound
d = d + 1e100*eye(size(a,1));
sigmin = max(min(d)); % min: largest nearest neighbor distance
% call optimiser
defs = {1};
parmin_max = [sigmin,sigmax];
[w,kernel,nu] = regoptc(a,mfilename,{sig},defs,[1],parmin_max,testc([],'soft'));
else % kernel is given
kernel = proxm([],'r',sig);
[w,J,nu] = nusvc(a,kernel);
end
end
end
w = setname(w,'RB Support Vector Classifier');
return
|
github
|
jacksky64/imageProcessing-master
|
gendatp.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatp.m
| 2,955 |
utf_8
|
5b3389c5a8b91866cde0c9f0155e41ab
|
%GENDATP Parzen density data generation
%
% B = GENDATP(A,N,S,G)
%
% INPUT
% A Dataset
% N Number(s) of points to be generated (optional; default: 50 per class)
% S Smoothing parameter(s)
% (optional; default: a maximum likelihood estimate based on A)
% G Covariance matrix used for generation of the data
% (optional; default: the identity matrix)
%
% OUTPUT
% B Dataset of points generated according to Parzen density
%
% DESCRIPTION
% Generation of a dataset B of N points by using the Parzen estimate of the
% density of A based on a smoothing parameter S. N might be a row/column
% vector with different numbers for each class. Similarly, S might be
% a vector with different smoothing parameters for each class. If S = 0,
% then S is determined by a maximum likelihood estimate using PARZENML.
% If N is a vector, then exactly N(I) objects are generated for the class I.
% G is the covariance matrix to be used for generating the data. G may be
% a 3-dimensional matrix storing separate covariance matrices for each class.
%
% SEE ALSO
% DATASETS, GENDATK
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: gendatp.m,v 1.5 2010/03/25 15:41:39 duin Exp $
function B = gendatp(A,N,s,G)
prtrace(mfilename);
if (nargin < 1)
error('No dataset found');
end
A = dataset(A);
A = setlablist(A); % remove empty classes first
[m,k,c] = getsize(A);
p = getprior(A);
if (nargin < 2)
prwarning(4,'Number of points not specified, 50 per class assumed.');
N = repmat(50,1,c);
end
if (nargin < 3)
prwarning(4,'Smoothing parameter(s) not specified, to be determined be an ML estimate.');
s = 0;
end
if (length(s) == 1)
s = repmat(s,1,c);
end
if (length(s) ~= c)
error('Wrong number of smoothing parameters.')
end
if (nargin < 4)
prwarning(4,'Covariance matrices not specified, identity matrix assumed.');
covmat = 0; % covmat indicates whether a covariance matrix should be used
% 0 takes the identity matrix as the covariance matrix
else
covmat = 1;
if (ndims(G) == 2)
G = repmat(G,[1 1 c]);
end
if any(size(G) ~= [k k c])
error('Covariance matrix has a wrong size.')
end
end
N = genclass(N,p);
lablist = getlablist(A);
B = [];
labels = [];
% Loop over classes.
for j=1:c
a = getdata(A,j);
a = dataset(a);
ma = size(a,1);
if (s(j) == 0) % Estimate the smoothing parameter.
h = parzenml(a);
else
h = s(j);
end
if (~covmat)
b = a(ceil(rand(N(j),1) * ma),:) + randn(N(j),k).*repmat(h,N(j),k);
else
b = a(ceil(rand(N(j),1) * ma),:) + ...
gendatgauss(N(j),zeros(1,k),G(:,:,j)).*repmat(h,N(j),k);
end
B = [B;b];
labels = [labels; repmat(lablist(j,:),N(j),1)];
end
B = dataset(B,labels);
B = setprior(B,p);
B = set(B,'featlab',getfeatlab(A),'name',getname(A),'featsize',getfeatsize(A));
return
|
github
|
jacksky64/imageProcessing-master
|
spirals.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/spirals.m
| 553 |
utf_8
|
9c160bf41b06bee2e4e497139043f7f5
|
%SPIRALS 194 objects with 2 features in 2 classes
%
% A = SPIRALS
% A = SPIRALS(M,N)
%
% Load the dataset in A, select the objects and features according to the
% index vectors M and N. This is one of the Spiral dataset implementations.
%
% See also DATASETS, PRDATASETS
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function a = spirals(M,N);
if nargin < 2, N = []; end
if nargin < 1, M = []; end
a = prdataset('spirals',M,N);
a = setname(a,'Spirals');
|
github
|
jacksky64/imageProcessing-master
|
plotdg.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/plotdg.m
| 1,889 |
utf_8
|
a5fda91cafdb6a5f1d4df34153470a49
|
%PLOTDG Plot dendrogram
%
% PLOTDG(DENDROGRAM,K)
%
% INPUT
% DENDROGRAM Dendrogram
% K Number of clusters
%
% OUTPUT
%
% DESCRIPTION
% Plots a dendrogram as generated by HCLUST. If the optional K is given the
% dendrogram is compressed first to K clusters. Along the horizontal axis
% the numbers stored in DENDROGRAM(1,:) are written as text. The dendrogram
% itself is defined by DENDROGRAM(2,:) in which each entry stands for the
% level on which the previous and next group of objects are clustered.
%
% SEE ALSO
% HCLUST
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: plotdg.m,v 1.2 2006/03/08 22:06:58 duin Exp $
function plotdg(dendrogram,k)
prtrace(mfilename);
[n,m] = size(dendrogram);
if n ~= 2
error('No proper dendrogram supplied')
end
if nargin == 2 % compress dendrogram to k clusters
if k > m
error('Number of clusters should be less than sample size')
end
F = [dendrogram(2,:),inf];
S = sort(-F); t = -S(k+1); % find cluster level
I = [find(F >= t),m+1]; % find all indices where cluster starts
dendrogram = [I(2:k+1) - I(1:k); F(I(1:k))];
m = k;
end
[S,I] = sort(dendrogram(2,:));
C = [0:m-1;1:m;zeros(1,m);2:m+1];
X = zeros(m,4); Y = X;
T = zeros(m,4);
for i=1:m-1
X(i,:) = [C(2,I(i)), C(2,I(i)), C(2,C(1,I(i))), C(2,C(1,I(i)))];
Y(i,:) = [C(3,I(i)), S(i), S(i), C(3,C(1,I(i)))];
C(:,C(1,I(i))) = [C(1,C(1,I(i))), (C(2,I(i)) + C(2,C(1,I(i))))/2, ...
S(i), C(4,I(i))]';
C(1,C(4,I(i))) = C(1,I(i));
T(i,:) = sprintf('%4d',dendrogram(1,i));
end
T(m,:) = sprintf('%4d',dendrogram(1,m));
T = char(T);
X(m,:) = [0 0 m+1 m+1];
Y(m,:) = [0 0 0 0];
plot(X',Y','-b');
h = gca;
set(h,'box','off');
set(h,'xtick',[1:m]);
set(h,'xticklabel',T);
set(h,'fontsize',8)
return
|
github
|
jacksky64/imageProcessing-master
|
newline.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/newline.m
| 174 |
utf_8
|
2a39d991937508030bfbf1e69ec3c1a6
|
%NEWLINE The platform dependent newline character
%
% c = newline
% $Id: newline.m,v 1.3 2010/03/18 12:25:21 duin Exp $
function c = newline
c = sprintf('\n');
return
|
github
|
jacksky64/imageProcessing-master
|
genlab.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/genlab.m
| 3,076 |
utf_8
|
f6ea44f4198613eeb28e3339d6174aa7
|
%GENLAB Generate labels for classes
%
% LABELS = GENLAB(N,LABLIST)
%
% INPUT
% N Number of labels to be generated
% LABLIST Label names (optional; default: numeric labels 1,2,3,...)
%
% OUTPUT
% LABELS Labels in a column vector or strinag array
%
% DESCRIPTION
% Generate a set of labels as defined by the LABLIST. N is a number or
% a row/column vector of the values for each class. If N is a vector, then
% the first N(i) labels get the value LABLIST(i,:). N should have as many
% components as LABLIST. If N is a scalar, then N labels are generated for
% each class. LABLIST is a column vector or a string array. Labels can be
% used to construct a labeled dataset.
%
% EXAMPLES
% Numeric labels, 1..10, 10 classes, 100 labels per class.
% LAB1 = GENLAB(100*ones(1,10));
% Character labels, 3 classes, 10 labels per class.
% LAB2 = GENLAB([10 10 10], ['A';'B';'C']);
% Name labels, 2 classes, 50 labels per class.
% The commands below are equivalent.
% LAB3 = GENLAB([50 50], {'Apple'; 'Pear'});
% LAB3 = GENLAB([50 50], ['Apple'; 'Pear ']);
%
% SEE ALSO
% DATASETS, DATASET
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: genlab.m,v 1.4 2009/09/23 08:33:55 duin Exp $
function labels = genlab(n,lablist)
prtrace(mfilename);
if (nargin == 1)
% Create numeric labels.
labels = [];
lab = 1;
if (all(n == n(1))) % All label categories have equal cardinalities.
J = repmat([1:length(n)],n(1),1);
labels = J(:);
else
for i = 1:length(n)
labels = [labels; repmat(lab,n(i),1)];
lab = lab+1;
end
end
else % LABLIST present
% Create string or character labels.
if iscell(lablist), lablist = lablist(:); end
[m,ncol] = size(lablist);
if m ~= length(n)
% This is only possible when all label categories have equal cardinalities.
if (length(n) > 1)
error('Wrong number of labels supplied.')
else
J = repmat([1:m],n,1);
labels = lablist(J(:),:);
end
elseif (iscell(lablist)) % Cell array
% We are here when e.g. GENLAB([10 10],{'Apple'; 'Pear'}) is called.
labels = {};
for i = 1:length(n)
labels = [labels; repmat(lablist(i),n(i),1)];
end
labels = char(labels); % cell string labels are not supported anymore
elseif (isstr(lablist)) % Character array
% We are here when e.g. GENLAB([10 10],['Apple'; 'Pear ']) is called.
labels = char(repmat(lablist(1,:),n(1),1));
for i = 2:length(n)
if (n(i) > 0)
labels = char(labels,repmat(lablist(i,:),n(i),1));
end
end
if (n(1) == 0) % First label category not wanted.
labels(1,:) = [];
end
else
% Again numeric labels.
% We are here, when e.g. GENLAB([10 10 10], [3;6;7]) is called.
if (ncol > 1)
error('Labels should be characters, strings or single numbers.')
end
labels = [];
for i = 1:length(n)
labels = [labels; repmat(lablist(i),n(i),1)];
end
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_berosion.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_berosion.m
| 1,256 |
utf_8
|
ea9ba28359fad8fd157dc7a9cb947476
|
%IM_BEROSION Binary erosion of images stored in a dataset (DIP_Image)
%
% B = IM_BEROSION(A,N,CONNECTIVITY,EDGE_CONDITION)
% B = A*IM_BEROSION([],N,CONNECTIVITY,EDGE_CONDITION)
%
% INPUT
% A Dataset with binary object images dataset (possibly multi-band)
% N Number of iterations (default 1)
% CONNECTIVITY See BEROSION
% EDGE_CONDITION Value of edge, default 1
%
% OUTPUT
% B Dataset with eroded images
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE, BEROSION
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Physics, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
function b = im_berosion(a,n,connect,edgecon)
prtrace(mfilename);
if nargin < 4 | isempty(edgecon), edgecon = 1; end
if nargin < 3 | isempty(connect), connect = -2; end
if nargin < 2 | isempty(n), n = 1; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{n,connect,edgecon});
b = setname(b,'Image erosion');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,{n,connect,edgecon});
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = dip_image(a,'bin');
b = berosion(a,n,connect,edgecon);
end
return
|
github
|
jacksky64/imageProcessing-master
|
im_minf.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_minf.m
| 1,134 |
utf_8
|
fe024d15ba47c051482648153256c205
|
%IM_MINF Minimum filter of images stored in a dataset (DIP_Image)
%
% B = IM_MINF(A,SIZE,SHAPE)
% B = A*IM_MINF([],SIZE,SHAPE)
%
% INPUT
% A Dataset with object images dataset (possibly multi-band)
% SIZE Filter width in pixels, default SIZE = 7
% SHAPE String with shape:'rectangular', 'elliptic', 'diamond'
% Default: elliptic
%
% OUTPUT
% B Dataset with filtered images
%
% SEE ALSO
% DATASETS, DATAFILES, DIP_IMAGE, MINF
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_minf(a,size,shape)
prtrace(mfilename);
if nargin < 3 | isempty(shape), shape = 'elliptic'; end
if nargin < 2 | isempty(size), size = 7; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{size,shape});
b = setname(b,'Minimum filter');
elseif isa(a,'dataset') % allows datafiles too
isobjim(a);
b = filtim(a,mfilename,{size,shape});
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
a = 1.0*dip_image(a);
b = minf(a,size,shape);
end
return
|
github
|
jacksky64/imageProcessing-master
|
setname.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/setname.m
| 287 |
utf_8
|
038915ac208df9ac19248da017fefef0
|
%SETNAME Mapping for easy name setting
%
% A = A*SETNAME([],NAME)
% W = W*SETNAME([],NAME)
%
%Set name of dataset A or mapping W
function a = setname(a,varargin)
if nargin < 1 | isempty(a)
a = mapping(mfilename,'combiner',varargin);
else
a = setname(a,varargin);
end
|
github
|
jacksky64/imageProcessing-master
|
subsc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/subsc.m
| 4,474 |
utf_8
|
c48deab246d0527ec9f8facef7c0cb91
|
%SUBSC Subspace Classifier
%
% W = SUBSC(A,N)
% W = SUBSC(A,FRAC)
%
% INPUT
% A Dataset
% N or FRAC Desired model dimensionality or fraction of retained
% variance per class
%
% OUTPUT
% W Subspace classifier
%
% DESCRIPTION
% Each class in the trainingset A is described by linear subspace of
% dimensionality N, or such that at least a fraction FRAC of its variance
% is retained. This is realised by calling PCA(AI,N) or PCA(AI,FRAC) for
% each subset AI of A (objects of class I). For each class a model is
% built that assumes that the distances of the objects to the class
% subspaces follow a one-dimensional distribution.
%
% New objects are assigned to the class of the nearest subspace.
% Classification by D = B*W, in which W is a trained subspace classifier
% and B is a testset, returns a dataset D with one-dimensional densities
% for each of the classes in its columns.
%
% If N (ALF) is NaN it is optimised by REGOPTC.
%
% REFERENCE
% E. Oja, The Subspace Methods of Pattern Recognition, Wiley, New York, 1984.
%
% SEE ALSO
% DATASETS, MAPPINGS, PCA, FISHERC, FISHERM, GAUSSM, REGOPTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function W = subsc(A,N)
name = 'Subspace classf.';
% handle default
if nargin < 2, N = 1; end
% handle untrained calls like subsc([],3);
if nargin < 1 | isempty(A)
W = mapping(mfilename,{N});
W = setname(W,name);
return
end
if isa(N,'double') & isnan(N) % optimize regularisation parameter
defs = {1};
parmin_max = [1,size(A,2)];
W = regoptc(A,mfilename,{N},defs,[1],parmin_max,testc([],'soft'),0);
elseif isa(N,'double')
% handle training like A*subsc, A*subsc([],3), subsc(A)
% PRTools takes care that they are all converted to subsc(A,N)
islabtype(A,'crisp'); % allow crisp labels only
isvaldfile(A,1,2); % at least one object per class, two objects
A = testdatasize(A,'features');
A = setprior(A,getprior(A));
[m,k,c] = getsize(A); % size of the training set
for j = 1:c % run over all classes
B = seldat(A,j); % get the objects of a single class only
u = mean(B); % compute its mean
B = B - repmat(u,size(B,1),1); % subtract mean
v = pca(B,N); % compute PCA for this class
v = v*v'; % trick: affine mappings in the original space
B = B - B*v; % differences of objects and their mappings
s = mean(sum(B.*B,2)); % mean square error w.r.t. the subspace
data(j).u = u; % store mean
data(j).w = v; % store mapping
data(j).s = s; % store mean square distance
end
% define trained mapping,
% store class labels and size
W = mapping(mfilename,'trained',data,getlablist(A),k,c);
W = setname(W,name);
elseif isa(N,'mapping')
% handle evaluation of a trained subspace classifier W for a dataset A.
% The command D = A*W is by PRTools translated into D = subsc(A,W)
% Such a call is detected here by the fact that N appears to be a mapping.
W = N; % avoid confusion: call the mapping W
m = size(A,1); % number of test objects
[k,c] = size(W); % mapping size: from K features to C classes
d = zeros(m,c); % output: C class densities for M objects
for j=1:c % run over all classes
u = W.data(j).u; % class mean in training set
v = W.data(j).w; % mapping to subspace in original space
s = W.data(j).s; % mean square distance
B = A - repmat(u,m,1); % substract mean from test set
B = B - B*v; % differences objects and their mappings
d(:,j) = sum(B.*B,2)/s; % convert to distance and normalise
end
d = exp(-d/2)/sqrt(2*pi); % convert to normal density
A = dataset(A); % make sure A is a dataset
d = setdata(A,d,getlabels(W)); % take data from D and use
% class labels as given in W
% other information in A is preserved
W = d; % return result in output variable W
else
error('Illegal call') % this should not happen
end
return
|
github
|
jacksky64/imageProcessing-master
|
reject.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/reject.m
| 3,470 |
utf_8
|
e28c512648bc1dc90ebb01253058ff9d
|
%REJECT Compute the error-reject trade-off curve
%
% E = REJECT(D);
% E = REJECT(A,W);
%
% INPUT
% D Classification result, D = A*W
% A Dataset
% W Cell array of trained classifiers
%
% OUTPUT
% E Structure storing the error curve and information needed for plotting
%
% DESCRIPTION
% E = REJECT(D) computes the error-reject curve of the classification
% result D = A*W, in which A is a dataset and W is a classifier. E is
% a structure storing the error curve in E.ERROR. Use PLOTE(E) for
% plotting the result.
%
% E = REJECT(A,W) computes a set of error-reject curves for all trained
% classifiers stored in the cell array W.
%
% EXAMPLES
% A - training set, B - test set:
% D = B*NMC(A); E = REJECT(D); PLOTE(E); % Plots a single curve
% E = REJECT(B,A*{NMC,UDC,QDC}); PLOTE(E); % Plots 3 curves
%
% REFERENCES
% 1. R.O. Duda, P.E. Hart, and D.G. Stork, Pattern classification, 2nd edition,
% John Wiley and Sons, New York, 2001.
% 2. A. Webb, Statistical Pattern Recognition, John Wiley & Sons, New York, 2002.
%
% SEE ALSO
% DATASETS, MAPPINGS, PLOTE, ROC, TESTC
% Copyright: R.P.W. Duin, [email protected]
% Faculty of Applied Sciences, Delft University of Technology
% P.O. Box 5046, 2600 GA Delft, The Netherlands
% $Id: reject.m,v 1.3 2007/02/15 10:11:15 davidt Exp $
function e = reject(A,W)
prtrace(mfilename);
% No data, return an untrained mapping.
if (nargin == 0) | (isempty(A))
e = mapping('reject','fixed');
return;
end
compute = 0; % COMPUTE is 1 if the classier W should be applied to A.
name = [];
if (nargin == 2)
if iscell(W)
classfno = length(W); % Number of classifiers, hence error curves.
compute = 1;
elseif ismapping(W) % W is one classifier only.
if ~istrained(W)
error('Classifier should be trained.')
end
D = A*W*classc; % Normalize the outputs of W and apply it to the data A.
classfno = 1;
name = getname(W);
else
error('Second parameter should be a classifier or a cell array of classifiers.')
end
else % Only one input argument.
D = A;
classfno = 1;
end
% Fill the structure E with information needed for plotting.
m = size(A,1);
e.error = zeros(classfno,m+1);
% m+1 for storing error of 0 size dataset
e.std = zeros(classfno,m+1);
e.xvalues = [0:m]/m;;
e.n = 1;
datname = getname(A);
if ~isempty(datname)
e.title = ['Reject curve for the ' datname];
end
e.xlabel= 'Reject';
e.ylabel= 'Error';
e.plot = 'plot';
e.names = name;
for j=1:classfno
if (compute)
w = W{j};
if ~istrained(w)
error('Classifier should be trained.')
end
D = A*w*classc; % Normalize the outputs of W and apply it to A.
e.names = char(e.names,getname(w));
end
% Compare the classification result with the actual labels.
% N is a 0/1 vector pointing to all distinct/equal labels.
[err,n] = nlabcmp(labeld(D),getlab(D));
% A trick: if D consists of one column, as before returned by
% FISHERC in case of a 2-class problem.
% May be they don't exist anymore in PRTools, but once they did
% and may be they pop up again.
if (size(D,2) == 1)
D = [D 1-D];
end
% Sort the objects, starting from the closest to the decision
% boundary to the furthest away.
[y,J] = sort(max(+D,[],2));
% 1/0 in N corresponds now to objects correctly/wrongly classified.
n = 1-n(J)';
e.error(j,:) = [err err-cumsum(n)]/m;
end
if (classfno > 1)
e.names(1,:) = [];
end
return;
|
github
|
jacksky64/imageProcessing-master
|
rejectc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/rejectc.m
| 2,045 |
utf_8
|
5edd5997a9b5130d788a7e1c2c935433
|
%REJECTC Construction of a rejecting classifier
%
% WR = REJECTC(A,W,FRAC,TYPE)
%
% INPUT
% A Dataset
% W Trained or untrained classifier
% FRAC Fraction to be rejected. Default: 0.05
% TYPE String with reject type: 'ambiguity' or 'outlier'.
% 'a' and 'o' are supported as well. Default is 'a'.
%
% OUTPUT
% WR Rejecting classifier
%
% EXAMPLE
% a = gendatb
% w = ldc(a);
% v = rejectc(a,w,0.2);
% scatterd(a);
% plotc(w);
% plotc(v,'r')
%
% DESCRIPTION
% This command extends an arbitrary classifier with a reject option. If WR
% is used for classifying a dataset B, then D = B*WR has C+1 columns
% ('features'), one for every class in A and an additional one that takes
% care of the rejection: a NaN for numeric labels (classnames in A) or en
% empty string for string labels.
% NOTE: Objects that are rejected are not counted as an error in TESTC. The
% classification error estimated by TESTC just considers the total number
% of objects for wich B*WR*LABELD has a correct classname and neglects all
% others. So by rejection the error estimate by TESTC may increase,
% decrease or stay equal.
%
% SEE ALSO
% DATASETS, MAPPINGS, LABELD, TESTC, REJECTM
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function w_out = rejectc(a,w,frac,type)
if nargin < 4, type = 'a'; end
if nargin < 3, frac = 0.05; end
ismapping(w);
isdataset(a);
if isuntrained(w), w = a*w; end
istrained(w);
conv = getout_conv(w);
if isstr(getlablist(a))
rejname = '';
else
rejname = NaN;
end
switch(type)
case{'a','ambiguity'}
w_out = w*classc*rejectm(a*w*classc,frac,rejname);
case{'o','outlier'}
conv = getout_conv(w);
if conv > 1
w = setout_conv(w,conv-2);
elseif conv == 1
error('Outlier reject not (yet) supported for this classifier')
end
w_out = w*rejectm(a*w,frac,rejname);
otherwise
error('Unknown reject type')
end
|
github
|
jacksky64/imageProcessing-master
|
gendatk.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/gendatk.m
| 3,686 |
utf_8
|
7b5a0540b3986a375806e98dd13c0cf5
|
%GENDATK K-Nearest neighbor data generation
%
% B = GENDATK(A,N,K,S)
%
% INPUT
% A Dataset
% N Number of points (optional; default: 50)
% K Number of nearest neighbors (optional; default: 1)
% S Standard deviation (optional; default: 1)
%
% OUTPUT
% B Generated dataset
%
% DESCRIPTION
% Generation of N points using the K-nearest neighbors of objects in the
% dataset A. First, N points of A are chosen in a random order. Next, to each
% of these points and for each direction (feature), a Gaussian-distributed
% offset is added with the zero mean and the standard deviation: S * the mean
% signed difference between the point of A under consideration and its K
% nearest neighbors in A.
%
% The result of this procedure is that the generated points follow the local
% density properties of the point from which they originate.
%
% If A is a multi-class dataset the above procedure is followed class by
% class, neglecting objects of other classes and possibly unlabeled objects.
%
% If N is a vector of sizes, exactly N(I) objects are generated
% for class I. Default N is 100 objects per class.
%
% SEE ALSO
% DATASETS, GENDATP
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: gendatk.m,v 1.4 2007/04/23 12:49:29 duin Exp $
function B = gendatk(A,N,k,stdev)
prtrace(mfilename);
if (nargin < 4)
prwarning(3,'Standard deviation of the added Gaussian noise is not specified, assuming 1.');
stdev = 1;
end
if (nargin < 3)
prwarning(3,'Number of nearest neighbors to be used is not specified, assuming 1.');
k = 1;
end
if (nargin < 2)
prwarning(3,'Number of samples to generate is not specified, assuming 50.');
N = []; % This happens some lines below.
end
if (nargin < 1)
error('No dataset found.');
end
A = dataset(A);
A = setlablist(A); % remove empty classes first
[m,n,c] = getsize(A);
prior = getprior(A);
if isempty(N),
N = repmat(50,1,c); % 50 samples are generated.
end
N = genclass(N,prior); % Generate class frequencies according to the priors.
lablist = getlablist(A);
B = [];
labels = [];
% Loop over classes.
for j=1:c
a = getdata(A,j); % The j-th class.
[D,I] = sort(distm(a));
I = I(2:k+1,:); % Indices of the K nearest neighbors.
alf = randn(k,N(j))*stdev; % Normally distributed 'noise'.
nu = ceil(N(j)/size(a,1)); % It is possible that NU > 1 if many objects have to be generated.
J = randperm(size(a,1));
J = repmat(J,nu,1)';
J = J(1:N(j)); % Combine the NU repetitions of J into one column vector.
b = zeros(N(j),n);
% Loop over features.
for f = 1:n
% Take all objects given by J, consider feature F.
% Their K nearest neighbors are given by I(:,J)
% We reshape them as a N(j) by K matrix (N(j) is the length of J)
% Compute all differences between them and the original objects
% Multiply these differences by the std dev stored in alf
% Transpose and sum over the K neighbors, normalize by K
% Transpose again and add to the original objects
b(:,f) = a(J,f) + sum(( ( a(J,f)*ones(1,k) - ...
reshape(+a(I(:,J),f),k,N(j))' ) .* alf' )' /k, 1)';
end
B = [B;b];
labels = [labels; repmat(lablist(j,:),N(j),1)];
end
B = dataset(B,labels,'prior',A.prior);
%B = set(B,'featlab',getfeatlab(A),'name',getname(A),'featsize',getfeatsize(A));
%DXD. Added this exception, because else it's going to complain
% that the name is not a string.
B = set(B,'featlab',getfeatlab(A),'featsize',getfeatsize(A));
if ~isempty(getname(A))
B = setname(B,getname(A));
end
return;
|
github
|
jacksky64/imageProcessing-master
|
nusvc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/nusvc.m
| 4,575 |
utf_8
|
efaf4b65ce42bc988eab73dc28fea2c0
|
%NUSVC Support Vector Classifier: NU algorithm
%
% [W,J,NU] = NUSVC(A,KERNEL,NU)
% W = A*SVC([],KERNEL,NU)
%
% INPUT
% A Dataset
% KERNEL - Untrained mapping to compute kernel by A*(A*KERNEL) during
% training, or B*(A*KERNEL) during testing with dataset B.
% - String to compute kernel matrices by FEVAL(KERNEL,B,A)
% Default: linear kernel (PROXM([],'p',1));
% NU Regularization parameter (0 < NU < 1): expected fraction of SV
% (optional; default: max(leave-one-out 1_NN error,0.01))
%
% OUTPUT
% W Mapping: Support Vector Classifier
% J Object indices of support objects
% NU Actual nu_value used
%
% DESCRIPTION
% Optimizes a support vector classifier for the dataset A by quadratic
% programming. The difference with the standard SVC routine is the use and
% interpretation of the regularisation parameter NU. It is an upperbound
% for the expected classification error. By default NU is estimated by the
% leave-one-error of the 1_NN rule. For NU = NaN an automatic optimisation
% is performed using REGOPTC.
%
% If KERNEL = 0 it is assumed that A is already the kernelmatrix (square).
% In this case also a kernel matrix B should be supplied at evaluation by
% B*W or MAP(B,W).
%
% There are several ways to define KERNEL, e.g. PROXM([],'r',1) for a
% radial basis kernel or by USERKERNEL for a user defined kernel.
%
% SEE ALSO
% MAPPINGS, DATASETS, SVC, NUSVO, PROXM, USERKERNEL, REGOPTC
% Copyright: S.Verzakov, [email protected]
% Based on SVC byby: D. de Ridder, D. Tax, R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: nusvc.m,v 1.6 2010/06/25 09:50:40 duin Exp $
function [W,J,nu,C,alginf] = nusvc(a,kernel,nu,Options)
prtrace(mfilename);
if nargin < 4
Options = [];
end
DefOptions.mean_centering = 1;
DefOptions.pd_check = 1;
DefOptions.bias_in_admreg = 1;
DefOptions.allow_ub_bias_admreg = 1;
DefOptions.pf_on_failure = 1;
DefOptions.multiclass_mode = 'single';
Options = updstruct(DefOptions,Options,1);
if nargin < 3
nu = [];
prwarning(3,'Regularization parameter nu set to NN error\n');
end
if nargin < 2 | isempty(kernel)
kernel = proxm([],'p',1);
end
if nargin < 1 | isempty(a)
W = mapping(mfilename,{kernel,nu,Options});
elseif (~ismapping(kernel) | isuntrained(kernel)) % training
pd = 1; % switches, fixed here.
mc = 1;
islabtype(a,'crisp');
isvaldfile(a,1,2); % at least 1 object per class, 2 classes
a = testdatasize(a,'objects');
[m,k,c] = getsize(a);
nlab = getnlab(a);
% if isempty(nu), nu = max(testk(a,1),0.01); end
if isempty(nu)
nu = 2*min(max(testk(a,1),0.01),(0.8*min(classsizes(a))/size(a,1)));
end
% The SVC is basically a 2-class classifier. More classes are
% handled by mclassc.
if c == 2 % two-class classifier
if (isnan(nu)) % optimize trade-off parameter
defs = {proxm([],'p',1),[],[]};
parmin_max = [0,0;0.001,0.999;0,0]; % kernel and Options can not be optimised
[W,J,nu,C,alginf] = regoptc(a,mfilename,{kernel,nu,Options},defs,[2],parmin_max,testc([],'soft'));
else
% Compute the parameters for the optimization:
y = 3 - 2*nlab;
if ~isequal(kernel,0)
if mc
u = mean(a);
b = a -ones(m,1)*u;
else
b = a;
u = [];
end
K = b*(b*kernel);
% Perform the optimization:
[v,J,nu,C] = nusvo(+K,y,nu,Options);
s = b(J,:);
insize = k;
else % kernel is already given!
K = min(a,a'); % make sure kernel matrix is symmetric
% Perform the optimization:
[v,J,nu,C] = nusvo(+K,y,nu,Options);
u = [];
s = [];
insize = size(K,2); % ready for kernel inputs
end
% Store the results, use SVC for execution
W = mapping('svc','trained',{u,s,v,kernel,J},getlablist(a),insize,2);
W = cnormc(W,a);
W = setcost(W,a);
alginf.svc_type = 'nu-SVM';
alginf.kernel = kernel;
alginf.C = C;
alginf.nu = nu;
alginf.nSV = length(J);
alginf.classsizes = [nnz(y==1), nnz(y==-1)];
alginf.pf = isnan(C);
end
else % multi-class classifier:
[W,J,nu,C,alginf] = mclassc(a,mapping(mfilename,{kernel,nu,Options}),'single');
end
W = setname(W,'Support Vector Classifier (nu version)');
end
return;
|
github
|
jacksky64/imageProcessing-master
|
prarff.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prarff.m
| 3,226 |
utf_8
|
b9a5520deaa586036751cc082ae2f646
|
%PRARFF COnvert ARFF file into PRTools dataset
%
% A = PRARFF(FILE)
%
% INPUT
% FILE ARFF file
%
% OUTPUT
% A Dataset in PRTools format
%
% DESCRIPTION
% ARFF files as used in WEKA are converted into PRTools format. In case
% they don't fit (non-numeric features, varying feature length) an error is
% generated.
%
% SEE ALSO
% DATASETS
function a = prarff(file)
if nargin < 1 | exist(file) ~= 2
error('file not found');
end
t = txtread(file);
c = cell2str(t);
k = 0;
nodata = 1;
for j=1:length(c);
if nodata
[s,u] = strtok(c{j});
if strcmp(s,'@relation')
name = strtrim(u);
end
if strcmp(s,'@attribute')
k = k+1;
u = strrep(u,'''','');
[featlab{k},u] = strtok(u);
if strcmp(featlab{k},'class')
featlab(k) = [];
k = k-1;
% skip as we determine lablist from data field
% u = strrep(u,'{','{''');
% u = strrep(u,'}','''}');
% u = strrep(u,',',''',''');
% eval(['lablist = ' u]);
else
if ~any(strcmp(strtrim(u),{'numeric','integer','real'}))
warning(['Non-numeric attributes are not supported ' ...
file ' ' u]);
a = [];
return
end
end
end
if strcmp(s,'@data')
nodata = 0;
form = [repmat('%e,',1,k) '%s'];
a = zeros(length(c)-j,k);
m = 0;
end
else
if length(find(c{j}==',')) == k
m = m+1;
x = sscanf(c{j},form);
a(m,:) = x(1:k);
labels{m} = char(x(k+1:end))';
elseif length(find(c{j}==',')) == k-1 % unlabeled?
m = m+1;
x = sscanf(c{j},form);
a(m,:) = x(1:k);
labels{m} = '';
else
error('Data size doesn''t match number of attributes')
end
end
end
a = dataset(a,labels);
a = setfeatlab(a,featlab);
a = setname(a,name);
return
%STR2CELL String to cell conversion
%
% C = STR2CELL(S)
%
% INPUT
% S String
%
% OUTPUT
% A Cell array
%
% DESCRIPTION
% The string S is broken into a set of strings, one for each line. Each of
% them is place into a different element of the cell araay C
function c = cell2str(s)
if nargin < 1 | ~ischar(s)
error('No input string found')
end
s = strrep([s char(10)],char([10 13]),char(10));
s = strrep(s,char([13 10]),char(10));
s = strrep(s,char([10 10]),char(10));
s = strrep(s,char(13),char(10));
n = [0 strfind(s,char(10))];
c = cell(length(n-1),1);
for j=1:length(n)-1
c{j} = s(n(j)+1:n(j+1)-1);
end
if isempty(c{end})
c(end) = [];
end
%TXTREAD Read text file
%
% A = TXTREAD(FILENAME,N,START)
%
% INPUT
% FILENAME Name of delimited ASCII file
% N Number of elements to be read (default all)
% START First element to be read (default 1)
%
% OUTPUT
% A String
%
% DESCRIPTION
% Reads the total file as text string into A
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function a = txtread(file,n,nstart)
if nargin < 3, nstart = 1; end
if nargin < 2 | isempty(n), n = inf; end
fid = fopen(file);
if (fid < 0)
error('Error in opening file.')
end
a = fscanf(fid,'%c',n);
fclose(fid);
return
%
|
github
|
jacksky64/imageProcessing-master
|
prmemory.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/prmemory.m
| 1,969 |
utf_8
|
4831b62875e22b1bfcfc7f3d412afe7e
|
%PRMEMORY Set/get size of memory usage
%
% N = PRMEMORY(N)
%
% N : The desired / retrieved maximum size data of matrices (in
% matrix elements)
%
% DESCRIPTION
% This retoutine sets or retrieves a global variable GLOBALPRMEMORY that
% controls the maximum size of data matrices in PRTools. Routines like
% KNNC, KNN_MAP, PARZEN_MAP and TESTP make use of it by computing
% additional loops and avoiding to define very large distance matrices.
% The default for this maximum size is set to 10000000. For most
% computers there is no need to reduce it. There is not much speed up
% to be expected if it is enlarged.
%
% PRMEMORY gives also the number of elements for which a conversion from
% datafiles to datasets is approved.
%
% This facility is illustrated by the following example, using the
% routine PRMEM.
%
% Assume that an array of the size [M x K] has to be computed. The
% numbers of LOOPS and ROWS are determined which are needed such that
% ROWS*K < GLOBALPRMEMORY (a global variable that is initialized in this
% routine, if necessary). The final number of rows for the last loop
% is returned in LAST.
%
% EXAMPLES
% [M,K] = size(A);
% [LOOPS,ROWS,LAST] = prmem(M,K);
% if (LOOPS == 1)
% RESULT = < compute the result based on A >
% else
% RESULT = 0;
% for J =1:LOOPS
% if (J == LOOPS), N = LAST; else N = ROWS; end
% NN = (J-1)*ROWS;
% RESULT = RESULT + < compute a partial result based on A(NN+1:NN+N,:) >
% end
% end
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: prmemory.m,v 1.2 2007/04/13 09:30:54 duin Exp $
function n_out = prmemory(n_in)
prtrace(mfilename)
persistent GLOBALPRMEMORY;
if (isempty(GLOBALPRMEMORY))
GLOBALPRMEMORY = 10000000;
end
if nargin > 0
GLOBALPRMEMORY = n_in;
end
if nargout > 0
n_out = GLOBALPRMEMORY;
elseif nargin == 0
disp(GLOBALPRMEMORY)
end
return;
|
github
|
jacksky64/imageProcessing-master
|
im_scale.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/im_scale.m
| 1,217 |
utf_8
|
523e0781344f11a37de848be741dc80c
|
%IM_SCALE Scale all binary images in a datafile to a giving fraction of pixels 'on'
%
% B = IM_SCALE(A,P)
% B = A*IM_SCALE([],P)
%
% B is a zoomed in / out version of A such that about a fraction
% P of the image pixels is 'on' (1).
%
% SEE ALSO
% DATASETS, DATAFILES, IM_BOX, IM_CENTER
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function b = im_scale(a,p)
prtrace(mfilename);
if nargin < 2 | isempty(p), p = 0.5; end
if nargin < 1 | isempty(a)
b = mapping(mfilename,'fixed',{p});
b = setname(b,'Image bounding box');
elseif isdataset(a)
error('Command cannot be used for datasets as it may change image size')
elseif isdatafile(a)
isobjim(a);
b = filtim(a,mfilename,{p});
b = setfeatsize(b,getfeatsize(a));
elseif isa(a,'double') | isa(a,'dip_image') % here we have a single image
sca = sqrt(p/mean(a(:)));
sa = size(a);
c = imresize(double(a),round(sca*sa),'nearest');
sc = size(c);
d = abs(floor((sc - sa)/2));
if sca < 1
b = zeros(size(a));
b(d(1)+1:d(1)+sc(1),d(2)+1:d(2)+sc(2)) = c;
else
b = c(d(1)+1:d(1)+sa(1),d(2)+1:d(2)+sa(2));
end
end
return
|
github
|
jacksky64/imageProcessing-master
|
kcentres.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/kcentres.m
| 5,769 |
utf_8
|
f5d8e03cc086b9c56daea98db515307e
|
%KCENTRES Finds K center objects from a distance matrix
%
% [LAB,J,DM] = KCENTRES(D,K,N)
%
% INPUT
% D Distance matrix between, e.g. M objects (may be a dataset)
% K Number of center objects to be found (optional; default: 1)
% N Number of trials starting from a random initialization
% (optional; default: 1)
%
% OUTPUT
% LAB Integer labels: each object is assigned to its nearest center
% J Indices of the center objects
% DM A list of distances corresponding to J: for each center in J
% the maximum distance of the objects assigned to this center.
%
% DESCRIPTION
% Finds K center objects from a symmetric distance matrix D. The center
% objects are chosen from all M objects such that the maximum of the
% distances over all objects to the nearest center is minimized. For K > 1,
% the results depend on a random initialization. The procedure is repeated
% N times and the best result is returned.
%
% If N = 0, initialisation is not random, but done by a systematic
% selection based on a greedy approach.
%
% SEE ALSO
% HCLUST, KMEANS, EMCLUST, MODESEEK
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
% $Id: kcentres.m,v 1.5 2008/07/03 09:08:43 duin Exp $
function [labels,Jopt,dm] = kcentres(d,k,n)
if (nargin < 3) | isempty(n)
n = 1;
prwarning(4,'Number of trials not supplied, assuming one.');
end
if (nargin < 2) | isempty(k)
k = 1;
prwarning(4,'Number of centers not supplied, assuming one.');
end
if(isdataset(d))
d = +d;
prwarning(4,'Distance matrix is convert to double.');
end
[m,m2] = size(d);
if ( ~issym(d,1e-12) | any(diag(d) > 1e-14) )
error('Distance matrix should be symmetric and have zero diagonal')
end
% checking for a zero diagonal
t = eye(m) == 1;
if(~all(d(t)==0))
error('Distance matrix should have a zero diagonal.')
end
if (k == 1)
dmax = max(d);
[dm,Jopt] = min(dmax);
labels = repmat(1,m,1);
return;
end
if k > m
error('Number of centres should not exceed number of objects')
end
% We are here only if K (> 1) centers are to be found.
% Loop over number of trials.
dmax = max(max(d));
dopt = inf;
s = sprintf('k-centres, %i attempts: ',n);
prwaitbar(n,s,n>1);
if n == 0
nrep = 1;
else
nrep = n;
end
for tri = 1:nrep
prwaitbar(n,tri,[s int2str(tri)]);
if n == 0
M = kcentresort(d,k); % systematic initialisation
else
M = randperm(m); M = M(1:k); % Random initializations
end
J = zeros(1,k); % Center objects to be found.
% Iterate until J == M. See below.
while 1,
[dm,I] = min(d(M,:));
% Find K centers.
for i = 1:k
JJ = find(I==i);
if (isempty(JJ))
%JJ can be empty if two or more objects are in the same position of
% feature space in dataset
J(i) = 0;
else
% Find objects closest to the object M(i)
[dummy,j,dm] = kcentres(d(JJ,JJ),1,1);
J(i) = JJ(j);
end
end
J(find(J==0)) = [];
k = length(J);
if k == 0
error('kcentres fails as some objects are identical: add some noise')
end
if (length(M) == k) & (all(M == J))
% K centers are found.
[dmin,labs] = min(d(J,:));
dmin = max(dmin);
break;
end
M = J;
end
% Store the optimal centers in JOPT.
if (dmin <= dopt)
dopt = dmin;
labels = labs';
Jopt = J;
end
end
prwaitbar(0)
% Determine the best centers over the N trials.
dm = zeros(1,k);
for i=1:k
L = find(labels==i);
dm(i) = max(d(Jopt(i),L));
end
return;
%KCENTRESORT Sort objects given by dissimilarity matrix
%
% N = KCENTRESORT(D,P,CRIT)
%
% INPUT
% D Square dissimilarity matrix, zeros on diagonal
% P Number of prototypes to be selected
% CRIT 'dist' or 'centre'
%
% OUTPUT
% N Indices of selected prototypes
%
% DESCRIPTION
% Sort objects given by square dissim matrix D using a greedy approach
% such that the maximum NN distance from all objects (prototypes)
% to the first K: max(min(D(:,N(1:K),[],2)) is minimized.
%
% This routines tries to sample the objects such that they are evenly
% spaced judged from their dissimilarities. This may be used as
% initialisation in KCENTRES. It works reasonably, but not very good.
%
% SEE ALSO
% KCENTRES
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function N = kcentresort(d,p,crit);
d = +d;
m = size(d,1);
if nargin < 3, crit = 'dist'; end
if nargin < 2 | isempty(p), p = m; end
L = [1:m];
N = zeros(1,p);
[dd,n] = min(max(d,[],2)); % this is the first (central) prototype
e = d(:,n); % store here the distances to the nearest prototype (dNNP)
f = min(d,repmat(e,1,m)); % replace distances that are larger than dNNP by dNNP
N(1) = n; % ranking of selected prototypes
L(n) = []; % candidate prototypes (all not yet selected objects)
for k=2:p % extend prototype set
if strcmp(crit,'centre')
[dd,n] = min(max(f(L,L),[],1)); % This selects the next prototype out of candidates in L
e = min([d(:,L(n)) e],[],2); % update dNNP
f = min(d,repmat(e,1,m)); % update replacement of distances that are larger
% than dNNP by dNNP
elseif strcmp(crit,'dist')
[dd,n] = max(mean(d(N(find(N > 0)),L)));
else
error('Illegal crit')
end
N(k) = L(n); % update list of selected prototypes
L(n) = []; % update list of candidate prototypes
end
|
github
|
jacksky64/imageProcessing-master
|
bagcc.m
|
.m
|
imageProcessing-master/Matlab PRTools/prtools_com/prtools/bagcc.m
| 3,054 |
utf_8
|
82d80a12e773b00901ef371565572def
|
%BAGCC Combining classifier for classifying bags of objects
%
% DBAG = BAGCC(DOBJ,COMBC)
% DBAG = DOBJ*BAGCC([],COMBC)
%
% INPUT
% DOBJ Dataset, classification matrix, output of some base classifier
% COMBC Combiner, e.g. MAXC (default VOTEC)
%
% OUTPUT
% DBAG Dataset, classification matrix for the bags in DOBJ
%
% DESCRIPTION
% This routine combines object classification results of bags of objects
% stored in DOBJ. It is assumed that the current labels of DOBJ are bag
% identifiers and defining objects belonging to the same bag. Objects of
% the same bag are combined by COMBC into a single classification result
% and returned by DBAG.
%
% DBAG gets as many objects as there are bags defined for DOBJ. Effectively
% the first object of every bag in DOBJ is replaced by the combined result
% and other objects of that bag are deleted. DBAG has the same feature
% labels (most likely the class names) as DOBJ and stores as object
% identifiers the bag identifiers stored in the label list of DOBJ.
% A possible multi-labeling definition of DOBJ is preserved.
%
% This routine is called by BAGC where needed.
%
% SEE ALSO
% DATASETS, BAGC, MULTI-LABELING
% Copyright: R.P.W. Duin, [email protected]
% Faculty EWI, Delft University of Technology
% P.O. Box 5031, 2600 GA Delft, The Netherlands
function [dbag,id] = bagcc(dobj,combc)
if nargin < 2 | isempty(combc), combc = votec; end
if nargin < 1 | isempty(dobj)
% define the mapping
dbag = mapping(mfilename,'untrained',{combc});
dbag = setname(dbag,'Bag combiner');
else % execution
% we should have a proper dataset
isdataset(dobj);
% the class names are the bag indentifiers
bagnames = classnames(dobj);
% retrieve datasize, and number of sets c
[m,k,c] = getsize(dobj);
% get number of objects for every set
s = classsizes(dobj);
% dobj is a classification matrix, so its features point to classes
featlab = getfeatlab(dobj);
% reserve spave for the result
dbag = dataset(zeros(c,k));
% space the object identifiers of the first object per bag
id = zeros(c,1);
t = sprintf('Combining %i bags: ',c);
prwaitbar(c,t);
% run over all bags
for j=1:c
prwaitbar(c,j,[t int2str(j)]);
% get the objects in the bag
y = seldat(dobj,j);
% the identifier of the first object
id(j) = getident(y(1,:));
%create a dataset with all objects in the bag concatenated horizontally
y = +y';
y = dataset(y(:)');
% give the the proper class labels
y = setfeatlab(y,repmat(featlab,s(j),1));
% now classifier combiners can be used
dbag(j,:) = y*combc;
end
prwaitbar(0);
% find the first objects of every set
J = findident(dobj,id);
% and replace them by the bag combining result
% so object labels become bag labels
dbag = setdata(dobj(J,:),dbag);
% give columns the classnames
dbag = setfeatlab(dbag,featlab);
% use set bag names as bag identifiers
dbag = setident(dbag,bagnames);
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.