function varargout = RGB2III(varargin)
% Conversion dans l'espace Otha I1I2I3
% Pour image couleur RGB
% 
% INPUT:
% - image 3xQ
%
% OUTPUT:
% - image 3xQ
%
% D'après la thèse de O. Lezoray, Univ. Caen, 2000
% (Ohta Y.I. "Color Information for regions segmentation"
% Computer Graphics and Image Processing, vol13, pp222-241, 1980)			
%
% Plugin for OpenIsaac
% version 1
% © 2011-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 couleur RGB'};
    % output
	varargout{2} = {'IMG','image I1I2I3'};
	return
end	

% INPUT
ObjIMG = varargin{1};

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

if (IsaacIMG_get(ObjIMG,'DimZ') ~= 3)
	error('image incompatible')
end
if ~strcmp(IsaacIMG_get(ObjIMG,'ColorSpaceName') ,'SRGB')
	IsaacMessageWarning('l''image doit être codée en RGB')
end
dimx = IsaacIMG_get(ObjIMG,'DimX');
dimy = IsaacIMG_get(ObjIMG,'DimY');
X = IsaacIMG_img2mat(ObjIMG,'double');
% transformation [M,N,3] en [MN,3]
XX = reshape(X,dimx*dimy,3);
% transformation I1I2I3
YY(:,1) = (XX(:,1) + XX(:,2) + XX(:,3)) / 3;
YY(:,2) = (XX(:,1) - XX(:,3)) / 2;
YY(:,3) = (2 * XX(:,2) - XX(:,1) - XX(:,3)) / 4;
% 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,3] en [M,N,3]
Y = reshape(YY,dimy,dimx,3);
% 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;	
