function b = image_boundary ( filename )

%*****************************************************************************80
%
%% image_boundary() extracts the boundary between black and white image regions.
%
%  Discussion:
%
%    If the image is not black and white, this function converts it to
%    a black and white version.  The intensity dividing level in im2bw()
%    is 0.5, but this can be adjusted to other values between 0 and 1 if
%    the initial result is not satisfactory.
%
%    It is important that the image is simple, having only one dividing
%    line between black and white.  As it turns out, this implies that the
%    image must have a black background that extends to the picture limits.
%    MATLAB will see any white pixels on the picture limits as being "next to"
%    phantom black pixels, and will generate a border there, which is
%    almost certainly not what you want.  Thus, this function can correctly
%    handle a white filled circle on a black background, but will get "confused"
%    by a black filled circle on a white background.   Moreover, a circle
%    drawn by a black line on a white background will produce THREE boundary
%    lines, only one of which will be returned by this function: the 
%    picture limits will be a boundary, and the black line of the circle
%    will generate two black/white boundaries, on the inside and on the
%    outside of the circle.  So don't do that.
%
%  Licensing:
%
%    This code is distributed under the MIT license.
%
%  Modified:
%
%    01 August 2015
%
%  Author:
%
%    John Burkardt
%
%  Reference:
%
%    Alessandra Agostini, Chiara Piazzola,
%    Mesh Generation with FreeFem++ and Triangle,
%    Master's degree presentation,
%    University of Verona, 2014.
%
%  Input:
%
%    string FILENAME, the name of an image file to be processed.
%
%  Output:
%
%    integer B(*,2), a list of pixels that form the first black and
%    white boundary detected in the image.
%
  im = imread ( filename );

  [ m, n, nc ] = size ( im );

  fprintf ( 1, '\n' );
  fprintf ( 1, '  Image "%s"\n', filename );
  fprintf ( 1, '  Image size %d rows by %d columns, %d colors.\n', m, n, nc );
%
%  Convert the image to black and white, if necessary.
%
  if ( 1 < nc )
    im = im2bw ( im, 0.5 );
    fprintf ( 1, '  Image converted to black and white.\n' );
%
%  Now might be a good time to display the converted image...
%
    if ( false )
      imshow ( im );
    end

  end
%
%  BWBOUNDARIES traces the region boundaries in a black and white image.
%
  bcell = bwboundaries ( im );
%
%  bcell is actually a cell array.
%  Assuming there is only one connected boundary between black and white 
%  regions, then we just need to extract the contents of the first cell
%  as a standard MATLAB array of Nx2 pixel coordinates.
%
  b = bcell{1};

  return
end
