function s = rect( img, metric )
% Find minimal bounding rectangle for each object
% 
% This code is only available for academic non-commercial use. 
% If you are using this code, please give a reference to:
% Zhang, Q., R. Skjetne, I. Metrikin, and S. Løset, “Image Processing for
% Ice Floe Analyses in Broken-ice Model Testing.” Cold Regions Science and
% Technology, Vol. 111, pp. 27-38, 2015.
%
% Input data:
% img:   input binary image
% metric:(OPTIONAL)single letter character flag which
%        denotes the use of minimal area or perimeter as the
%        metric to be minimized. metric may be either 'a' or 'p',
%        capitalization is ignored. Any other contraction of 'area'
%        or 'perimeter' is also accepted.
%        DEFAULT: 'a'    ('area')
% 
% Output data:
% s:      structure data, includes: Vertice, Center, Area, Perimeter 
%
%    Copyright:     NTNU, Department of Marine Technology
%    Project:	    Arctic DP, RCN no.199567
%    Author:        Qin Zhang
%    Date created:  2013.07.26  Qin Zhang.
%    Revised:      	2015.05.12


% bw=im2bw(img, graythresh(img));

% default for metric
if (nargin<3) || isempty(metric)
  metric = 'a';
elseif ~ischar(metric)
  error 'metric must be a character flag if it is supplied.'
else
  % check for 'a' or 'p'
  metric = lower(metric(:)');
  ind = strmatch(metric,{'area','perimeter'});
  if isempty(ind)
    error 'metric does not match either ''area'' or ''perimeter'''
  end
  
  % just keep the first letter.
  metric = metric(1);
end

[label, num] = bwlabel(img, 4);
s = [];
for i = 1 : num
    [r, c] = find(label == i);
    [rectx, recty, a, p] = minboundrect(c, r, 'a');   % minimal bounding rectangle
    cenx = sum(rectx(1 : 4)) / 4;
    ceny = sum(recty(1 : 4)) / 4;
    c = [cenx, ceny];   % center
    v = [rectx, recty];   % vertice
    
    s0 = struct('Vertices', v, 'Center', c, 'Area', a, 'Perimeter', p);
    s = [s; s0];
    
end

