%HIST_EQUALIZE   Histogram equalization
%
% SYNOPSIS:
%  image_out = hist_equalize(image_in)

% (C) Copyright 1999-2002               Pattern Recognition Group
%     All rights reserved               Faculty of Applied Physics
%                                       Delft University of Technology
%                                       Lorentzweg 1
%                                       2628 CJ Delft
%                                       The Netherlands
%
% Cris Luengo, September 2000.
%  4 December 2001: Catching dfloat bug in dip_histogram.
%  8 March 2002: Catching dfloat bug in dip_histogram in a better way.
%  9 April 2002 (MvG): Replacing dip_histogram() by diphist().


function image_out = hist_equalize(varargin)

d = struct('menu','Point',...
           'display','Histogram equalization',...
           'inparams',struct('name',       {'image_in'},...
                             'description',{'Input image'},...
                             'type',       {'image'},...
                             'dim_check',  {0},...
                             'range_check',{[]},...
                             'required',   {1},...
                             'default',    {'a'}...
                              ),...
           'outparams',struct('name',{'image_out'},...
                              'description',{'Output image'},...
                              'type',{'image'}...
                              )...
           );
if nargin == 1
   s = varargin{1};
   if ischar(s) & strcmp(s,'DIP_GetParamList')
      image_out = d;
      return
   end
end
try
   [image_in] = getparams(d,varargin{:});
catch
   if ~isempty(paramerror)
      error(paramerror)
   else
      error(firsterr)
   end
end

if strcmp(datatype(image_in),'dfloat')
   image_in = dip_image(image_in,'sfloat');
end

nbins = 256;
min_val = min(image_in);
max_val = max(image_in);
interval = (max_val-min_val)/(nbins-1);

% Get normalised cumulative histogram
[histogram, bins] = diphist(image_in,[min_val,max_val],nbins);
histogram = double(histogram);
cumhist = cumsum(histogram);
cumhist = cumhist/cumhist(end)*(nbins-1);
% Catch rounding errors etc. by providing safety margins
bins=[min_val-2*interval,bins,max_val+2*interval];
cumhist=[0,cumhist,255];

% Map pixel values to new values using linear interpolation
% bins -> cumhist
image_out = interp1(bins,cumhist,double(image_in),'*linear');
image_out = dip_image(image_out,'sfloat');
