来自「选择其中图像中的矩形及正方形等感兴趣区域ROI」· 代码 · 共 748 行 · 第 1/3 页

TXT
748
字号
function varargout = imSelectROI(img,varargin)

%--------------------------------------------------------------------------
% This functions displays GUI for selecting square or rectangular part
% of the input image IMG. To perform selection user must click mouse twice:
% at two corners of the selection area.
% User can change the shape at any moment, even when first point is set,
% unless it is not forbidden by additional parameters.
% Use also cam change the way the selection area is calculated
% from the two selected points.
% Depending on the combination of the shape and mode it could be:
%--------------------------------------------------------------------------
% Shape       Mode        Result
% - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
% Rectangle   Free        Rectangle with one corner at first point (P1)
%                         and another corner at second point (P2).
% Rectangle   Centered    Rectangle with its center at first point (P1)
%                         and corner at second point (P2).
% Square      Free        Square of the largest size that can be
%                         fitted into rectangle made by (P1) and (P2)
%                         with one corner at (P1).
% Square      Centered    Square of the largest size that can be
%                         fitted into centered rectangle.
%                         Center of the square is at (P1).
%--------------------------------------------------------------------------
% Behavior of the imSelectROI can be altered by providing additional
% parameters in MatLab well-known ParamName,ParamValue style.
%
% NOTE      This function was developed under MatLab R2006b.
% ====      It requires Image Processing Toolbox to work.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Syntax
% ======
%                   imSelectROI( img, param1, val1, param2, val2, ...)
%             ROI = imSelectROI( img, param1, val1, param2, val2, ...)
% [ ROI, SelImg ] = imSelectROI( img, param1, val1, param2, val2, ...)
%
% Displays GUI and returns:
%
% SelImg - Selected part of the image passed as first parameter.
%          Even if first parameter is a file name (see below).
%
% ROI - structure with fields:
%   ROI.Xmin    - minimal value of X coordinate of the selected area
%   ROI.Xmax    - maximal value of X coordinate of the selected area
%   ROI.Ymin    - minimal value of Y coordinate of the selected area
%   ROI.Ymax    - maximal value of Y coordinate of the selected area
%   ROI.DX      - horizontal size of the selected area
%       ROI.DX = ROI.Xmax - ROI.Xmin + 1
%   ROI.DY      - vertical size of the selected area
%       ROI.DY = ROI.Ymax - ROI.Ymin + 1
%   ROI.Xrange  - same as [ROI.Xmin:ROI.Xmax]
%   ROI.Yrange  - same as [ROI.Ymin:ROI.Ymax]
%
%   Selected part can be retrieved from original image as
%       img( ROI.Xrange, ROI.Yrange, :)
%   This allows to perform selection once and use the same ROI
%   to process series of images (see examples at hte end).
%
% Arguments
% =========
%
% img     Anything that can be passed to IMSHOW as a single parameter.
%         In could be file name or preloaded image.
%         See "help imshow" for more information about the syntaxes.
%
% Parameters
% ==========
%
% AllowedShape  (string): {'Any'} | 'Square' | 'Rectangle'
%
%   This parameter controls shape of the selection.
%   Specifying 'Square' or 'Rectangle' you prevent user from
%   selecting other shape.
%   By specifying 'Any' or omitting 'AllowedShape' at all
%   user is allowed to select any shape.
%
% SelectionMode (string): {'Free'} | 'Centered'
%
%   This parameter controls selection mode.
%   But in this case user still can select other mode.
%
% FastReturn    (string): {'off'} | 'on'
%
%   This parameter controls how the GUI behaves when user finishes
%   seletion. 
%   When 'off' value provided function waits for user to press
%   "DONE" button, allowing user to change selection by
%   "START OVER" button.
%   When 'on' value provided function returns immediately after user
%   makes valid selection of second point. In this case it is also
%   possible to change selection, but only until the second point was
%   NOT selected by user.
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Examples
% ======
% ROI = imSelectROI( 'c:\Image.jpg');
% [ROI,SelImage] = imSelectROI( 'c:\Image.jpg', 'AllowedShape','Square');
%
% % FNames is a cell array of image file names
% ROI = imSelectROI( FNames{1} );
% for i=1:length(FNames)
%     image = imread(FNames{i}); %whole image
%     selection = image( ROI.Xrange, ROI.Yrange, :); %selected area
%     ...
% end
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Additional info
% ===============
%   help imshow     for additional information on what can be passed
%                   to imSelectROI as first argument.
%==========================================================================

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% GUI parameters
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
LBoxWidth       = 0.1;  % width of the ListBoxes in NORMALIZED units
                        % Change this when width of listboxes is too smal
                        % to accomodate its strings or 
                        % to meet your preferences
LBoxHeight      = 44;   % height of the ListBoxes in PIXELS
ScrMargin       = 0.05; % Screen margin for the whole figure
                        % in NORMALIZED units

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Parsing arguments
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% GP.AllowedShapes    = {'Any','Square','Rectangle'};
GP.AllowedShapes    = {'Square','Rectangle'};
GP.SelectionModes   = {'Free','Centered'};
GP.FastReturns      = {'on','off'};

GP.AllowedShape_i   = GetParameterValue('AllowedShape',varargin, 'Any');
GP.SelectionMode_i  = GetParameterValue('SelectionMode',varargin, 'Free');
GP.FastReturn_i     = GetParameterValue('FastReturn',varargin, 'Off');

if any( strcmpi( GP.AllowedShape_i,  {GP.AllowedShapes{:} 'Any'} ) )
    GP.SelectionMode    = GP.SelectionMode_i;
else
    error('%s: Wrong value of "AllowedShape" parameter ("%s")',mfilename,GP.AllowedShape_i);
end

if any( strcmpi( GP.SelectionMode_i, GP.SelectionModes ) )
    GP.AllowedShape     = GP.AllowedShape_i;
else
    error('%s: Wrong value of "SelectionMode" parameter ("%s")',mfilename,GP.SelectionMode_i);
end

%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
% Creating GUI
%~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GP.hFig         = figure(...
    'Name','Select subimage',...
    'NumberTitle','off',...
    'Color',[1 1 1],...
    'WindowStyle','modal',...{normal} | 
    'Pointer','crosshair',... fullcrosshair crosshair
    'Resize','off',...{on} | off
    'Toolbar','none',...
    'Menubar','none');
GP.hImg         = imshow(img);
GP.XLim         = xlim;
GP.YLim         = ylim;
GP.hAxes        = gca;

set(GP.hAxes, 'ActivePositionProperty','OuterPosition');

GP.hPixVal      = impixelinfoval(GP.hFig,GP.hImg);

set(GP.hFig,...
    'Units','normalized',...
    'Position',[ ScrMargin ScrMargin 1-2*ScrMargin 1-2*ScrMargin ]);

GP.hSP          = imscrollpanel(GP.hFig,GP.hImg);

set(GP.hSP,...
    'Units','normalized',...
    'Position',[0 .1 1 .9]);
GP.hSPAPI       = iptgetapi(GP.hSP);
GP.hSPAPI.setMagnification(1);

movegui(GP.hFig, 'east');

GP.hDoneBtn     = uicontrol( 'Style','pushbutton',  'Parent',gcf,   'FontWeight','bold',                'units','normalized',   'position',[1-2.0*LBoxWidth 0 LBoxWidth 0.2], 'string','Done');
GP.hModeLBox    = uicontrol( 'Style','listbox',     'Parent',gcf,   'min',0,    'max',1,    'value',1,  'units','normalized',   'position',[1-3.5*LBoxWidth 0 LBoxWidth 0.2], 'string',GP.SelectionModes);
GP.hShapeLBox   = uicontrol( 'Style','listbox',     'Parent',gcf,   'min',0,    'max',1,    'value',1,  'units','normalized',   'position',[1-4.5*LBoxWidth 0 LBoxWidth 0.2], 'string',GP.AllowedShapes);
GP.hZoomPMenu   = uicontrol( 'Style','popupmenu',   'Parent',gcf,                           'value',5,  'units','normalized',   'position',[1-6.0*LBoxWidth 0 LBoxWidth 0.2], 'string',{'0010%','0025%','0050%','0075%','0100%','0150%','0200%','0250%','0300%','0400%','0500%','0600%','0700%','0800%','0900%','1000%'});
GP.hRedoBtn     = uicontrol( 'Style','pushbutton',  'Parent',gcf,   'FontWeight','bold',                'units','normalized',   'position',[1-7.5*LBoxWidth 0 LBoxWidth 0.2], 'string','Start over');
GP.hStatus      = uicontrol( 'Style','text',        'Parent',gcf,   'FontWeight','bold', 'FontSize',12, 'units','normalized',   'position',[1-9.0*LBoxWidth 0 LBoxWidth 0.2], 'string','');

set(GP.hShapeLBox,  'units','pixels'); p = get(GP.hShapeLBox, 'position'); set(GP.hShapeLBox, 'position',[ p(1)  0               p(3)    LBoxHeight ]);
set(GP.hModeLBox,   'units','pixels'); p = get(GP.hModeLBox,  'position'); set(GP.hModeLBox,  'position',[ p(1)  0               p(3)    LBoxHeight ]);
set(GP.hDoneBtn,    'units','pixels'); p = get(GP.hDoneBtn,   'position'); set(GP.hDoneBtn,   'position',[ p(1)  0               p(3)    LBoxHeight ]);
set(GP.hZoomPMenu,  'units','pixels'); p = get(GP.hZoomPMenu, 'position'); set(GP.hZoomPMenu, 'position',[ p(1)  LBoxHeight-25   p(3)    25         ]);
set(GP.hRedoBtn,    'units','pixels'); p = get(GP.hRedoBtn,   'position'); set(GP.hRedoBtn,   'position',[ p(1)  0               p(3)    LBoxHeight ]);
set(GP.hStatus,     'units','pixels'); q = get(GP.hStatus,    'position'); set(GP.hStatus,    'position',[ q(1)  LBoxHeight+08   p(3)*8  25         ]);

if strcmpi(GP.AllowedShape_i,'Square')
    % Square shape
    set(GP.hShapeLBox, 'Value',1);
    set(GP.hShapeLBox, 'enable','inactive');
    set(GP.hShapeLBox, 'TooltipString','Only square selection allowed');
elseif strcmpi(GP.AllowedShape_i,'Rectangle')
    % Rectangle shape
    set(GP.hShapeLBox, 'Value',2);
    set(GP.hShapeLBox, 'enable','inactive');
    set(GP.hShapeLBox, 'TooltipString','Only rectangular selection allowed');
else
    % Any shape
    set(GP.hShapeLBox, 'Value',2);
    set(GP.hShapeLBox, 'TooltipString','Select shape of your selection');
end

if strcmpi(GP.SelectionMode_i,'Centered')
    set(GP.hModeLBox, 'Value',2);
end

axes(GP.hAxes);
axis image; axis on;

%=========================================================================
% Stroing handles and other data to safe place
%=========================================================================
GP.P1   = [];
GP.P2   = [];
GP.SP1  = [];
GP.SP2  = [];
GP.SW   = [];
GP.SH   = [];
GP.hCrs = [];
GP.hRct = [];
guidata(gcf,GP);

%=========================================================================
% Tuning interface
%=========================================================================
set( gcf,           'WindowButtonUpFcn',    @FigureMouseBtnUp);
set( GP.hZoomPMenu, 'CallBack',             @AdjustZoom);
set( GP.hDoneBtn,   'CallBack',             @SelectionDone);
set( GP.hRedoBtn,   'CallBack',             @StartOver);

set( GP.hShapeLBox, 'CallBack',             @UpdateShapeAndMode);
set( GP.hModeLBox,  'CallBack',             @UpdateShapeAndMode);

iptaddcallback(gcf, 'WindowButtonMotionFcn', @FigureMouseMove);

uiwait;

if ishandle(GP.hFig)
    GP = guidata(gcf);

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?