function varargout = ImHotelling(varargin)
% Transformation d'Hotelling
% 
% INPUT:
% - image PxQ
%
% OUTPUT:
% - image PxQ
% - matrice (1,P) des valeurs propres (ordre décroissant)
%
% D'apres Digital Image Processing, Gonzalez & Woods, Addison-Wesley 1993
%
% Plugin for OpenIsaac
% version 1
% © 2010-2018 Alain Clément - Université d'Angers

%---------------------------------------------------------------------------------------------------

% Copyright 2007 - 2018 Université d'Angers - Author: Alain Clément
%
% 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 3 of the
% License, or 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.

%---------------------------------------------------------------------------------------------------

% PLUGIN PARAMETERS
if (nargin == 1) && strcmp(varargin{1},'-f')
    % input
	varargout{1} = {'IMG','image'};
    % output
	varargout{2} = {'IMG','image transformée', ...
					'DATA','valeurs propres'};
	return
end	

% INPUT
ObjIMG = varargin{1};

%---------------------------------------------------------------------------------------------------

dimx = IsaacIMG_get(ObjIMG,'DimX');
dimy = IsaacIMG_get(ObjIMG,'DimY');
dimz = IsaacIMG_get(ObjIMG,'DimZ');
X = IsaacIMG_img2mat(ObjIMG,'double');
% transformation entrée [M,N,P] en [MN,P]
XX = reshape(X,dimx*dimy,dimz);
clear X
% moyenne entrée [1,P]
Mx = mean(XX);
% matrice covariance entrée [P,P]
Cx = cov(XX,1);
% vecteurs propres (A [P,P]) et valeurs propres (V [P,P] diagonale)
[A,V]=eig(Cx);
% tri selon les valeurs propres par ordre décroissant
[Vs,Vi] = sort(diag(V),'descend');
EVal = Vs;
EVec = A(:,Vi);
% Transformée de Hotelling (opération matricielle)
YY=(XX-repmat(Mx,dimx*dimy,1))*EVec;
% recalage dynamique vectoriel [0,1] ou 0.5
Ymin = min(min(YY)); % min vectoriel pour P >= 1
Ymax = max(max(YY)); % max vectoriel pour P >= 1
if (Ymin ~= Ymax)
	YY = (YY-Ymin)/(Ymax-Ymin);
else
	YY = repmat(0.5,size(YY));
end	
% transformation [MN,P] en [M,N,P]
Y = reshape(YY,dimy,dimx,dimz);
% suppression de l'espace colorimétrique si il existe
if IsaacIMG_get(ObjIMG,'IsColorSpace')
	ObjIMG = IsaacIMG_set(ObjIMG,'ColorSpace',[]);
end	
ObjIMG = IsaacIMG_mat2img(ObjIMG,Y);

%---------------------------------------------------------------------------------------------------

% OUTPUT
varargout{1} = ObjIMG;
varargout{2} = IsaacDATA('TABN',EVal,'valeurs propres');

