Code covered by the BSD License  

Highlights from
Image Quality - Index Analysis GUI

image thumbnail

Image Quality - Index Analysis GUI

by

 

29 Apr 2013 (Updated )

This GUI measures the image quality/error between 2 or more images (original,test1/test2/.../testn).

imanalysis_gui(varargin)
function varargout = imanalysis_gui(varargin)

%=========================================================================%
% IMANALYSIS_GUI

% 02-03/2013 - Development
% 23/04/2013 - Version 0.97 aka "dirty"     (release date)
% 22/05/2013 - Version 1.02 aka "sturdy"    (a lot less prone to errors)
% 06/08/2013 - Version 1.14 aka "wingy"     (fixed a bug: RMSE: nomaps)
% 11/09/2013 - Version 1.25 aka "liberated" (fixed a bug: ERGAS: nomaps,ws) 

% Author: Aristidis D. Vaiopoulos

% Description:
% GUI that enables the user to calculate 8 image indices:
% 1) Bias, 2) CC (Correlation Coefficient), 3) DIV (Difference in Variance)
% 4) ED (Entropy Difference), 5) ERGAS, 6) UIQI, 7) RASE and 8) RMSE.

% The scope of this GUI is to measure the image quality/error between 2 
% (original/reference image, processed/distorted image) or more images.

% The image quality is estimated and quantified by the respective 8 image
% indices which are calculated locally (in a neighborhood). User can 
% specify the size of the neighborhood, by setting the FOCAL SIZE parameter 
% accordingly.

% User can opt to calculate any number of the 8 indices for 2 or more
% images (batch mode). So it can be characterized as a batch image index
% analysis tool. The index analysis results are written in an Excel file,
% named "Focal image analysis.xls" in the same folder. Every index result 
% is written in its homonymous spreadsheet. If there is no Microsoft Excel 
% installed in the current computer, the index analysis results are written
% in a *.CSV file.

% If the user wishes to study and visualize how each index has performed
% locally, he can check the button "Export index maps", which results in
% outputting every index map for every TEST (processed) image.

% Despite the fact that this program has been initially designed in order 
% to evaluate satellite imagery, all of the 8 above indices can be used for
% digital images of any origin (although some of them are specialized for 
% quality assessment in satellite datasets). Basically, this program is an
% enhanced version of this submission:

% http://www.mathworks.com/matlabcentral/fileexchange/32637

% There are 2 major improvements compared to the above submission:
% 1) The ability to calculate and evaluate every index locally in the image
% 2) The form of this program: GUI vs. script (previous)

% Usage:
% 0) Add to path the folder that includes imanalysis_gui function. Also add
% all subfolders which are in the same folder with imanalysis_gui.m + fig.
% This can be done quickly (and temporarily) by running install_temp.m.
% 1) Run the GUI by typing imanalysis_gui in Matlab's command window.
% 2) Load your original (reference) image by clicking the ORIGINAL button.
% 3) Load your test(s) (processed) image(s) by clicking the TEST(s) button.
% 4) You can set the output folder, by clicking the 'Set' pushbutton.
% However, you may find it useful that by default the program outputs to
% the folder containing the original image.
% 5) Choose which indices you want the program to calculate. You can select
% all indices at once, by pushing the 'All' button, under 'Select:' text.
% 6) You may want to change the FOCAL_SIZE parameter, which as mentioned,
% specifies the size of the neighborhood or "window" (filter) in which each
% index will be calculated. The larger the focal size, the more the
% computations, the more the required time. Usually, we use a neighborhood
% of 7 or 9. It is best to input an odd value in this parameter.
% 7) Optionally, you can check the export index maps button, if you want
% the program to output the "index maps" for each index and test image. If
% you work with georeferenced imagery, you will probably want to check the 
% export georeference button as well.
% 8) Press the 'Analyze!' button. 
% 9) The program performs index analysis with your options. Messages should
% appear in the command window, which state its current task. When all
% calculations have finished, an Excel (or CSV - read above) file is
% created with the results. If you wanted to export the index maps, you can 
% find them in the newly created folder 'Index maps' (which will be in the 
% same folder with the GUI).

% Important Facts:
% 1) You can use 2D (grayscale) or 3D (color with 3 or more bands) imagery. 
% 2) Every TEST image must have the exact same resolution and dimensions 
% with the ORIGINAL image.
% 3) The ED index is always calculated after conversion to 8bits.

% Compatibility:
% Oldest version known to have full compatibility: R2011a.
% Older versions than R2011a should work if the export index maps option is
% off. If you have an older version of Matlab, but want to export the index
% maps, then you can download the geotiffwrite function from FEX, and 
% modify this code accordingly, so it works for you.

% Requirements:
% Image processing toolbox
% Mapping toolbox (geotiffwrite)

% Citation:
% A. D. Vaiopoulos, "Developing Matlab scripts for image analysis and 
% quality assessment", Proc. SPIE 8181, 81810B (2011);
% Link of the above paper:
% http://dx.doi.org/10.1117/12.897806
%=========================================================================%

% Suppress the following compiler messages:
%#ok<*INUSD,*DEFNU,*INUSL,*NASGU>

% BEGIN CODE

% IMANALYSIS_GUI MATLAB code for imanalysis_gui.fig
% IMANALYSIS_GUI, by itself, creates a new IMANALYSIS_GUI or raises the 
% existing singleton*.
%
% H = IMANALYSIS_GUI returns the handle to a new IMANALYSIS_GUI or the 
% handle to the existing singleton*.
%
% IMANALYSIS_GUI('CALLBACK',hObject,eventData,handles,...) calls the local
% function named CALLBACK in IMANALYSIS_GUI.M with the given input arguments.
%
% IMANALYSIS_GUI('Property','Value',...) creates a new IMANALYSIS_GUI or raises the
% existing singleton*.  Starting from the left, property value pairs are
% applied to the GUI before imanalysis_gui_OpeningFcn gets called.  An
% unrecognized property name or invalid value makes property application
% stop.  All inputs are passed to imanalysis_gui_OpeningFcn via varargin.
%
% *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
% instance to run (singleton)".
%
% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help imanalysis_gui

% Last Modified by GUIDE v2.5 16-Feb-2013 19:30:18

% Begin initialization code - DO NOT EDIT
gui_Singleton = 1;
gui_State = struct('gui_Name',       mfilename, ...
                   'gui_Singleton',  gui_Singleton, ...
                   'gui_OpeningFcn', @imanalysis_gui_OpeningFcn, ...
                   'gui_OutputFcn',  @imanalysis_gui_OutputFcn, ...
                   'gui_LayoutFcn',  [] , ...
                   'gui_Callback',   []);
if nargin && ischar(varargin{1})
    gui_State.gui_Callback = str2func(varargin{1});
end

if nargout
    [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
else
    gui_mainfcn(gui_State, varargin{:});
end
% End initialization code - DO NOT EDIT


% --- Executes just before imanalysis_gui is made visible.
function imanalysis_gui_OpeningFcn(hObject, eventdata, handles, varargin)
% This function has no output args, see OutputFcn.
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
% varargin   command line arguments to imanalysis_gui (see VARARGIN)

% !! Getting all handles here is impossible !!

% Show a welcome message on first initialization.
if ~isfield(handles, 'init')
    handles.init = 1;
    disp('Welcome! Initializing the GUI...');
else
    handles.init = handles.init + 1;
end
% Get abs and export maps variables
abias = get(handles.absbias,'Value');
adiv = get(handles.absdiv,'Value');
aent = get(handles.absentropy,'Value');
emaps = get(handles.exportmaps_check,'Value');
% Disable abs and exportgeoreference (if export maps is false)
if abias == not(1)    
    set(handles.absbias,'Enable','off')
end
if adiv == not(1)    
    set(handles.absdiv,'Enable','off')
end
if aent == not(1)    
    set(handles.absentropy,'Enable','off')
end
if emaps == not(1)    
    set(handles.exportgeoreference_check,'Enable','off')
end
%% Code for background image
% This creates the 'background' axes
ha = axes('units','normalized', ...
'position',[0 0 1 1]);

% Move the background axes to the bottom
uistack(ha,'bottom');

% Load in a background image and display it using the correct colors
I=imread('hcsagrinio.jpg');
hi = imagesc(I);
colormap gray

% Turn the handlevisibility off so that we don't inadvertently plot into the axes again
% Also, make the axes invisible
set(ha,'handlevisibility','off','visible','off')

% set(hi,'alphadata',.5)
%%
% Display initialization message once
if isfield(handles, 'init') && handles.init == 1;
    disp('GUI is ready! :)');
    pause(3/7);
    clc
    disp('========================')
    disp('Image Index Analysis GUI')
    disp('========================') 
    disp(' ')
end

% Choose default command line output for imanalysis_gui
handles.output = hObject;

% Update handles structure
guidata(hObject, handles);

% UIWAIT makes imanalysis_gui wait for user response (see UIRESUME)
% uiwait(handles.figure1);


% --- Outputs from this function are returned to the command line.
function varargout = imanalysis_gui_OutputFcn(hObject, eventdata, handles)  
% varargout  cell array for returning output args (see VARARGOUT);
% hObject    handle to figure
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure
varargout{1} = handles.output;


% --- Executes on button press in bias_check.
function bias_check_Callback(hObject, eventdata, handles)
% hObject    handle to bias_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of bias_check

% It is it checked? If yes/no, enable/disable respectively the abs checkbox
bval = get(hObject,'Value');
if bval == false
    set(handles.absbias,'Enable','off')
    set(handles.absbias,'Value',0)
else
    set(handles.absbias,'Enable','on')
end


% --- Executes on button press in cc_check.
function cc_check_Callback(hObject, eventdata, handles)
% hObject    handle to cc_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of cc_check


% --- Executes on button press in div_check.
function div_check_Callback(hObject, eventdata, handles)
% hObject    handle to div_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of div_check

% It is it checked? If yes/no, enable/disable respectively the abs checkbox
bval = get(hObject,'Value');
if bval == false
    set(handles.absdiv,'Enable','off')
    set(handles.absdiv,'Value',0)
else
    set(handles.absdiv,'Enable','on')
end


% --- Executes on button press in entropy_check.
function entropy_check_Callback(hObject, eventdata, handles)
% hObject    handle to entropy_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of entropy_check

% It is it checked? If yes/no, enable/disable respectively the abs checkbox
bval = get(hObject,'Value');
if bval == false
    set(handles.absentropy,'Enable','off')
    set(handles.absentropy,'Value',0)
else
    set(handles.absentropy,'Enable','on')
end

% --- Executes on button press in ergas_check.
function ergas_check_Callback(hObject, eventdata, handles)
% hObject    handle to ergas_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of ergas_check


% --- Executes on button press in q_check.
function q_check_Callback(hObject, eventdata, handles)
% hObject    handle to q_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of q_check


% --- Executes on button press in rase_check.
function rase_check_Callback(hObject, eventdata, handles)
% hObject    handle to rase_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of rase_check


% --- Executes on button press in rmse_check.
function rmse_check_Callback(hObject, eventdata, handles)
% hObject    handle to rmse_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of rmse_check


% --- Executes on button press in loadorig_push.
function loadorig_push_Callback(hObject, eventdata, handles)
% hObject    handle to loadorig_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Prevent user from double clicking the button causing "race" bug 
set(hObject,'Enable','off')

% UI for ORIGINAL data input
[filename, pathname] = uigetfile(...
{'*.bmp; *.gif; *.jpg; *.png; *.tif',...
'Image Files (*.bmp *.gif *.jpg *.png *.tif )';
'*.*',  'All Files'}, ...
'Select the ORIGINAL Dataset');

% Get handles
handles = guidata(imanalysis_gui);
% Store original filename and path
handles.filename = filename;
handles.pathname = pathname;
% Change listbox function
set(handles.filenameorig_list,'string',filename);
% Assume that this is the desired output folder
sof = pathname;
sof = sof(1:end-1);
handles.sof = sof;
set(handles.outf_list,'string',sof);
% Update handles
guidata(imanalysis_gui,handles);
% Callback has been executed, user can reclick if he/she wants
set(hObject,'Enable','on')

% --- Executes on button press in loadtest_push.
function loadtest_push_Callback(hObject, eventdata, handles)
% hObject    handle to loadtest_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Prevent user from double clicking the button causing "race" bug 
set(hObject,'Enable','off')

% UI for TEST data input
[filenames, pathnames] = uigetfile(...
{'*.bmp; *.gif; *.jpg; *.png; *.tif',...
'Image Files (*.bmp *.gif *.jpg *.png *.tif )';
'*.*',  'All Files'}, ...
'Multiselect','on',...
'Select TEST Dataset(s)');

set(handles.ctestdata_push,'enable','off')
% If user hasn't cancelled data entry...
if pathnames ~= 0
    % Get handles
    handles = guidata(imanalysis_gui);
    % Store test filenames and paths
    if ~iscell(filenames)
        filenames = {filenames};
    end
    pathnames = {pathnames};
    % Force pathname size = filenames
    pathnames = repmat(pathnames,[1 length(filenames)]);
    % Has user input data previously?
    if isfield(handles, 'filenames')
        % Additional test data
        handles.filenames = [handles.filenames filenames];
        handles.pathnames = [handles.pathnames pathnames];
    else % he/she hasn't 
        handles.filenames = filenames;
        handles.pathnames = pathnames;
    end
    % Change listbox function
    set(handles.filenametest_list,'string',handles.filenames);
    % Update handles
    guidata(imanalysis_gui,handles);
end
% Callback has been executed, user can reclick if he/she wants
set(hObject,'Enable','on')
set(handles.ctestdata_push,'enable','on')

% --- Executes on selection change in filenametest_list.
function filenametest_list_Callback(hObject, eventdata, handles)
% hObject    handle to filenametest_list (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns filenametest_list contents as cell array
%        contents{get(hObject,'Value')} returns selected item from filenametest_list


% --- Executes during object creation, after setting all properties.
function filenametest_list_CreateFcn(hObject, eventdata, handles)
% hObject    handle to filenametest_list (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function ergasratio_edit_Callback(hObject, eventdata, handles)
% hObject    handle to ergasratio_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of ergasratio_edit as text
%        str2double(get(hObject,'String')) returns contents of ergasratio_edit as a double


% --- Executes during object creation, after setting all properties.
function ergasratio_edit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to ergasratio_edit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on selection change in filenameorig_list.
function filenameorig_list_Callback(hObject, eventdata, handles)
% hObject    handle to filenameorig_list (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns filenameorig_list contents as cell array
%        contents{get(hObject,'Value')} returns selected item from filenameorig_list


% --- Executes during object creation, after setting all properties.
function filenameorig_list_CreateFcn(hObject, eventdata, handles)
% hObject    handle to filenameorig_list (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in exportmaps_check.
function exportmaps_check_Callback(hObject, eventdata, handles)
% hObject    handle to exportmaps_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of exportmaps_check

handles = guidata(imanalysis_gui);
bval = get(hObject,'Value');
if bval == false
    set(handles.exportgeoreference_check,'Enable','off')
    set(handles.exportgeoreference_check,'Value',0)
else
    set(handles.exportgeoreference_check,'Enable','on')
end

% --- Executes on button press in exportgeoreference_check.
function exportgeoreference_check_Callback(hObject, eventdata, handles)
% hObject    handle to exportgeoreference_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of exportgeoreference_check


% --- Executes on button press in selectall_push.
function selectall_push_Callback(hObject, eventdata, handles)
% hObject    handle to selectall_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Check every index
set(handles.bias_check,'value',1);
set(handles.cc_check,'value',1);
set(handles.div_check,'value',1);
set(handles.entropy_check,'value',1);
set(handles.ergas_check,'value',1);
set(handles.q_check,'value',1);
set(handles.rase_check,'value',1);
set(handles.rmse_check,'value',1);
set(handles.absbias,'value',1);
set(handles.absdiv,'value',1);
set(handles.absentropy,'value',1);
% Enable abs
set(handles.absentropy,'enable','on');
set(handles.absbias,'enable','on');
set(handles.absdiv,'enable','on');
set(handles.absentropy,'enable','on');


% --- Executes on button press in selectnone_push.
function selectnone_push_Callback(hObject, eventdata, handles)
% hObject    handle to selectnone_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Uncheck every index
set(handles.bias_check,'value',0);
set(handles.cc_check,'value',0);
set(handles.div_check,'value',0);
set(handles.entropy_check,'value',0);
set(handles.ergas_check,'value',0);
set(handles.q_check,'value',0);
set(handles.rase_check,'value',0);
set(handles.rmse_check,'value',0);
set(handles.absbias,'value',0);
set(handles.absdiv,'value',0);
set(handles.absentropy,'value',0);
% Disable abs
set(handles.absentropy,'enable','off');
set(handles.absbias,'enable','off');
set(handles.absdiv,'enable','off');
set(handles.absentropy,'enable','off');

function focusedit_Callback(hObject, eventdata, handles)
% hObject    handle to focusedit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of focusedit as text
%        str2double(get(hObject,'String')) returns contents of focusedit as a double


% --- Executes during object creation, after setting all properties.
function focusedit_CreateFcn(hObject, eventdata, handles)
% hObject    handle to focusedit (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function msg1_Callback(hObject, eventdata, handles)
% hObject    handle to msg1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of msg1 as text
%        str2double(get(hObject,'String')) returns contents of msg1 as a double


% --- Executes during object creation, after setting all properties.
function msg1_CreateFcn(hObject, eventdata, handles)
% hObject    handle to msg1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end



function msg2_Callback(hObject, eventdata, handles)
% hObject    handle to msg2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: get(hObject,'String') returns contents of msg2 as text
%        str2double(get(hObject,'String')) returns contents of msg2 as a double


% --- Executes during object creation, after setting all properties.
function msg2_CreateFcn(hObject, eventdata, handles)
% hObject    handle to msg2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: edit controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in globalall.
function globalall_Callback(hObject, eventdata, handles)
% hObject    handle to globalall (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Check everything
set(handles.bias_check,'value',1);
set(handles.cc_check,'value',1);
set(handles.div_check,'value',1);
set(handles.entropy_check,'value',1);
set(handles.ergas_check,'value',1);
set(handles.q_check,'value',1);
set(handles.rase_check,'value',1);
set(handles.rmse_check,'value',1);
set(handles.absbias,'value',1);
set(handles.absdiv,'value',1);
set(handles.absentropy,'value',1);
set(handles.exportmaps_check,'value',1);
set(handles.exportgeoreference_check,'value',1);
set(handles.opres_check,'value',1);
set(handles.psnd_check,'value',1);
% Enable abs and exportgeoreference
set(handles.absentropy,'enable','on');
set(handles.absbias,'enable','on');
set(handles.absdiv,'enable','on');
set(handles.absentropy,'enable','on');
set(handles.exportgeoreference_check,'Enable','on')

% --- Executes on button press in globalnone.
function globalnone_Callback(hObject, eventdata, handles)
% hObject    handle to globalnone (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Uncheck everything
set(handles.bias_check,'value',0);
set(handles.cc_check,'value',0);
set(handles.div_check,'value',0);
set(handles.entropy_check,'value',0);
set(handles.ergas_check,'value',0);
set(handles.q_check,'value',0);
set(handles.rase_check,'value',0);
set(handles.rmse_check,'value',0);
set(handles.absbias,'value',0);
set(handles.absdiv,'value',0);
set(handles.absentropy,'value',0);
set(handles.exportmaps_check,'value',0);
set(handles.exportgeoreference_check,'value',0);
set(handles.opres_check,'value',0);
set(handles.psnd_check,'value',0);
% Disable abs and exportgeoreference
set(handles.absentropy,'enable','off');
set(handles.absbias,'enable','off');
set(handles.absdiv,'enable','off');
set(handles.absentropy,'enable','off');
set(handles.exportgeoreference_check,'Enable','off');

% --- Executes on button press in psnd_check.
function psnd_check_Callback(hObject, eventdata, handles)
% hObject    handle to psnd_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of psnd_check


% --- Executes on button press in opres_check.
function opres_check_Callback(hObject, eventdata, handles)
% hObject    handle to opres_check (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of opres_check


% --- Executes on button press in absdiv.
function absdiv_Callback(hObject, eventdata, handles)
% hObject    handle to absdiv (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of absdiv


% --- Executes on button press in absentropy.
function absentropy_Callback(hObject, eventdata, handles)
% hObject    handle to absentropy (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of absentropy


% --- Executes on button press in absbias.
function absbias_Callback(hObject, eventdata, handles)
% hObject    handle to absbias (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of absbias


% --- Executes on button press in ctestdata_push.
function ctestdata_push_Callback(hObject, eventdata, handles)
% hObject    handle to ctestdata_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

set(handles.loadtest_push,'enable','off')
% Prevent user from double clicking the button causing "race" bug 
set(hObject,'Enable','off')
% Reset test listbox
% Get handles
handles = guidata(imanalysis_gui);
% Remove files and paths
if isfield(handles,'filenames')
    handles = rmfield(handles,'filenames');
    handles = rmfield(handles,'pathnames');
end
% Change listbox function
set(handles.filenametest_list,'string','Waiting for test data...');
% Update handles
guidata(imanalysis_gui,handles);
% Callback has been executed, user can reclick if he/she wants
set(hObject,'Enable','on')
set(handles.loadtest_push,'enable','on')

% --- Executes on button press in about_push.
function about_push_Callback(hObject, eventdata, handles)
% hObject    handle to about_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

nbits = computer;
if nbits(end-1:end) == '64' %#ok<STCMP>
    nbits = '64';
else
    nbits = '32';
end

msg0 =  {'========================'
         'Image Index Analysis GUI'
         '========================' 
         ' '
         ' '
         'Measures Image Quality/Error'
         'via local Index calculation.'
         ' '
         'Programmed and designed by'
         'Aristidis D. Vaiopoulos.'
         ' '
         ' '
         ['Architecture: ',nbits,' bits.']
         ' '
         'Version 1.25 - Liberated ;-)'
         'September 2013'
         ' '
         ' '
         ' '};
msg0 = char(msg0);   
msgbox( msg0,'Program info:' )

% --- Executes on selection change in outf_list.
function outf_list_Callback(hObject, eventdata, handles)
% hObject    handle to outf_list (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hints: contents = cellstr(get(hObject,'String')) returns outf_list contents as cell array
%        contents{get(hObject,'Value')} returns selected item from outf_list


% --- Executes during object creation, after setting all properties.
function outf_list_CreateFcn(hObject, eventdata, handles)
% hObject    handle to outf_list (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.
%       See ISPC and COMPUTER.
if ispc && isequal(get(hObject,'BackgroundColor'), get(0,'defaultUicontrolBackgroundColor'))
    set(hObject,'BackgroundColor','white');
end


% --- Executes on button press in setoutfol_push.
function setoutfol_push_Callback(hObject, eventdata, handles)
% hObject    handle to setoutfol_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Prevent user from double clicking the button causing "race" bug 
set(hObject,'Enable','off')
% Get handles
handles = guidata(imanalysis_gui);
% Get output directory
if isfield(handles,'filename')
    sof = uigetdir(handles.pathname);
else
    sof = uigetdir;
end
handles.sof = sof;
% Change listbox function
set(handles.outf_list,'string',sof);
% Update handles
guidata(imanalysis_gui,handles);
% Callback has been executed, user can reclick if he/she wants
set(hObject,'Enable','on')

% --- Executes on button press in showfpaths_radio.
function showfpaths_radio_Callback(hObject, eventdata, handles)
% hObject    handle to showfpaths_radio (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of showfpaths_radio

% Prevent user from double clicking the button causing "race" bug 
set(hObject,'Enable','off')
% Get handles
handles = guidata(imanalysis_gui);
% Get button value
bval = get(handles.showfpaths_radio,'value');
% Show/Hide paths, as user demands
if bval ~= not(false) % LOL (if bval is false...)
    % Hide paths
    if isfield(handles,'pathname') % ORIG
        % Change listbox function
        set(handles.filenameorig_list,'string',[handles.filename]);
    end
    if isfield(handles,'pathnames') % TEST(s)
        % Change listbox function
        set(handles.filenametest_list,'string',[handles.filenames]);
    end
else
    % Show paths
    if isfield(handles,'pathname') % ORIG
        % Change listbox function
        a = [ char(handles.pathname) char(handles.filename) ];
        b = cellstr(a);
        set(handles.filenameorig_list,'string',b);
    end
    if isfield(handles,'pathnames') % TEST(s)
        % Change listbox function
        a = [ char(handles.pathnames') char(handles.filenames') ];
        b = cellstr(a);
        set(handles.filenametest_list,'string',b);
    end
end
% Update handles
guidata(imanalysis_gui,handles);    
% Callback has been executed, user can reclick if he/she wants
set(hObject,'Enable','on')

% --- Executes on button press in analyze_push.
function analyze_push_Callback(hObject, eventdata, handles)  
% hObject    handle to analyze_push (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

% Prevent user from double clicking the button causing "race" bug 
set(hObject,'Enable','off')
% Start program
tic;
% Get handles
handles = guidata(imanalysis_gui);
% Ensure that both inputs are present
if  ~isfield(handles,'pathname') | ~isfield(handles,'pathnames') ...
                                 | ( handles.filename == 0 ) %#ok<OR2>
    msg1 = ['You must input both ORIGINAL and TEST data in order to '...
                           'perform index analysis.'];
    msgbox(msg1,'Error t1:')
    return;
end
% Get user absolute value options (avv: absolute value vector)
avv = zeros(3,1);
avv(1) = get(handles.absbias,'value');
avv(2) = get(handles.absdiv,'value');
avv(3) = get(handles.absentropy,'value');
% Get user index output option (iov: index options vector)
iov = zeros(8,1);
iov(1) = get(handles.bias_check,'value');
iov(2) = get(handles.div_check,'value');
iov(3) = get(handles.cc_check,'value');
iov(4) = get(handles.entropy_check,'value');
iov(5) = get(handles.ergas_check,'value');
iov(6) = get(handles.q_check,'value');
iov(7) = get(handles.rase_check,'value');
iov(8) = get(handles.rmse_check,'value');
siov = sum(iov,1);
ciov = cumsum(iov,1);
% Ensure that user selects at least 1 index
if  siov == 0
    msg2 = 'You must select at least 1 index.';
    msgbox(msg2,'Error t2:')
    return;
end
% Freeze GUI
set(handles.setoutfol_push,'Enable','off')
set(handles.ctestdata_push,'Enable','off')
set(handles.focusedit,'Enable','off')
set(handles.analyze_push,'Enable','off')
set(handles.ergasratio_edit,'Enable','off')
set(handles.opres_check,'Enable','off')
set(handles.psnd_check,'Enable','off')
set(handles.globalnone,'Enable','off')
set(handles.globalall,'Enable','off')
set(handles.exportgeoreference_check,'Enable','off')
set(handles.exportmaps_check,'Enable','off')
set(handles.loadtest_push,'Enable','off')
set(handles.loadorig_push,'Enable','off')
set(handles.absbias,'Enable','off')
set(handles.absentropy,'Enable','off')
set(handles.absdiv,'Enable','off')
set(handles.selectnone_push,'Enable','off')
set(handles.selectall_push,'Enable','off')
set(handles.rmse_check,'Enable','off')
set(handles.rase_check,'Enable','off')
set(handles.q_check,'Enable','off')
set(handles.ergas_check,'Enable','off')
set(handles.entropy_check,'Enable','off')
set(handles.div_check,'Enable','off')
set(handles.cc_check,'Enable','off')
set(handles.bias_check,'Enable','off')
% GUI is now frozen

% Respect old variables flnames and impaths
flnames = [handles.filename handles.filenames];
flnames = flnames';
% Store image paths to variable impaths
nin = length(handles.filenames);
impaths = cell(nin+1,1);
impaths(1) = {[handles.pathname handles.filename]};
for n = 1:nin
    impaths(n+1) = {[char(handles.pathnames(n)) char(handles.filenames(n))]};
end

% Get focal size (window size)
ws = str2double( get(handles.focusedit,'string') );
% Get ergas ratio
% Here I use eval instead of str2double, because user might want to input
% fraction instead of a decimal value 
resratio = eval( get(handles.ergasratio_edit,'string') );
% Get map output option
mo = get(handles.exportmaps_check,'value');
if mo == 1;
    gtw = get(handles.exportgeoreference_check,'value');
end
disp(' ')
disp('>>> Please wait. Working.....')
disp(' ')

disp('Parsing Original image...')

orig = imread(char(impaths(1)));
disp('Original image parsed.')
disp(' ')
% Find number of bands
sizi = size(orig);
if max(size(size(orig))) == 2
    bands = 1;
else
    bands = sizi(1,3);
end

% Preallocation
% Indices per band
bias        = zeros(bands,nin+1);
cc          = ones(bands,nin+1);
div         = zeros(bands,nin+1);
Epb         = zeros(bands,nin+1);
ergas_pb    = zeros(bands,nin+1);
qs          = ones(bands,nin+1);
rase_pb     = zeros(bands,nin+1);
rmses       = zeros(bands,nin+1);
% Average indices
av_bias     = zeros(1,nin+1);
av_cc       = ones(1,nin+1);
av_div      = zeros(1,nin+1);
Eav         = zeros(1,nin+1);
av_ergas    = zeros(1,nin+1);
av_q        = ones(1,nin+1);
av_rase     = zeros(1,nin+1);
av_rmse     = zeros(1,nin+1);
% Total indices (whole image)
Etl         = zeros(1,nin+1);
ergas_tl    = zeros(1,nin+1);
rase_tl     = zeros(1,nin+1);

% Find if the function progressbar exists, if the user wishes to use it
% fp = 0;
% p_ex = 0;
% if ~exist('p') || p ~= 0 %#ok<EXIST>
%     p = 1;
%     p_ex = exist('progressbar.m'); %#ok<EXIST>
% end
% if p_ex == 2
%     fp = 1;
% end
% 
% if p ~= 0 && fp == 0 
%     disp('*Cannot find progressbar.m')
%     disp('*Estimated time left will not be shown.')
%     disp(' ')
% end
p = true;
fp = true;
try
    progressbar
catch err %#ok<NASGU>
    fp = false;
    disp('*Cannot find progressbar.m')
    disp('*Estimated time left will not be shown.')
    disp(' ')
end

%%
% Main calculations

if p == 1 && fp == 1 
    progressbar
end

% Check for int16 data
i16 = 0;
% Check for class equality
cne = 0;
clo = class(orig);
% User does not want index maps
if mo == 0;

    for m = 2:nin+1
        disp(' ')
        disp(['Parsing Test image # ', num2str(m-1),'...']) 
        test = imread(char(impaths(m)));
        disp(['Test image # ', num2str(m-1), ' parsed.'])
        disp(['Analyzing Test image # ', num2str(m-1), '....'])  
        disp(' ')
        if iov(1) == 1
            disp(['-Calculating index ',num2str(ciov(1)),...
                                 ' of ',num2str(siov),': Bias...'])
            [bias(:,m), av_bias(m)]         = bias3d(orig,test,ws,avv(1));
            disp('-Bias has been computed.')
        end
        if iov(2) == 1
            disp(['-Calculating index ',num2str(ciov(2)),...
                                 ' of ',num2str(siov),': DIV...'])
            [div(:,m), av_div(m)]           = div3d(orig,test,ws,avv(2));
            disp('-DIV has been computed.')
        end
        if iov(3) == 1
            disp(['-Calculating index ',num2str(ciov(3)),...
                                 ' of ',num2str(siov),': CC...'])
            [cc(:,m), av_cc(m)]             = ccc3d(orig,test,ws);
            disp('-CC has been computed.')
        end
        if iov(4) == 1
            disp(['-Calculating index ',num2str(ciov(4)),...
                                 ' of ',num2str(siov),': Entropy Diff....'])
            % If image class = int16, convert to unint16 or double if needed
            if strcmp( class(orig),'int16' ) %#ok<STISA>
                if min(orig(:)) >= 0
                    i16 = 1;
                    orig = uint16(orig);
                    test = uint16(test);
                else
                    i16 = 2;
                    orig = double(orig);
                    test = double(test);
                end
            end
            clt = class(test);
            if ~strcmp( class(orig), class(test)  )
                cne = 1;
                orig = double(orig);
                test = double(test);
            end
            [Epb(:,m), Eav(m)]              = ediff3d(orig,test,ws,0,avv(3));
            % Return to original class
            if i16 ~= 0
                orig = int16(orig);
                test = int16(test);
            end
            if cne == 1;
                orig = cast(orig,clo);
                test = cast(test,clt);
            end        
            disp('-Entropy Diff has been computed.')
        end
        if iov(5) == 1
            disp(['-Calculating index ',num2str(ciov(5)),...
                                 ' of ',num2str(siov),': ERGAS...'])
            [ergas_pb(:,m), ~, ergas_tl(m)] = ergas3d(orig,test,resratio,ws);
            disp('-ERGAS has been computed.')
        end
        if iov(6) == 1
            disp(['-Calculating index ',num2str(ciov(6)),...
                                 ' of ',num2str(siov),': Q...'])
            [qs(:,m), av_q(m)]              = q3d(orig,test,ws);
            disp('-Q has been computed.')
        end
        if iov(7) == 1
            disp(['-Calculating index ',num2str(ciov(7)),...
                                 ' of ',num2str(siov),': RASE...'])
            [rase_pb(:,m), ~, rase_tl(m)]   = rase3d(orig,test,ws);
            disp('-RASE has been computed.')
        end
        if iov(8) == 1
            disp(['-Calculating index ',num2str(ciov(8)),...
                                 ' of ',num2str(siov),': RMSE...'])
            [rmses(:,m), av_rmse(m), ~]     = rmse3d(orig,test,ws);
            disp('-RMSE has been computed.')
        end
        % Since nin is relatively small, this check does not decrease
        % significantly the execution time.
        if p == 1 && fp == 1
            progressbar((m-1)/nin)
        end

    end

end
% User demands index map output but does not care for georeference
if mo == 1 && gtw == 0
    
    % Fake a referencing array 
    R =  [
           0         -10
          10           0
      403670     4350900];
    % Fake a geokeytag
    load geokeytag.mat
  
    warning off MATLAB:mkdir:DirectoryExists
    % Set map output folder
    smof = [ handles.sof '\Index Maps' ]; 
    mkdir(smof)
    for m = 2:nin+1
        disp(' ')
        disp(['Parsing Test image # ', num2str(m-1),'...']) 
        test = imread(char(impaths(m)));
        disp(['Test image # ', num2str(m-1), ' parsed.'])
        disp(['Analyzing Test image # ', num2str(m-1), '....'])  
        disp(' ')
        if iov(1) == 1
            disp(['-Calculating index ',num2str(ciov(1)),...
                                 ' of ',num2str(siov),': Bias...'])
            [bias(:,m), av_bias(m), bmaps]  = bias3d(orig,test,ws,avv(1));
            geotiffwrite([smof '\Bias ' char(flnames(m)) '.tif'],...
                       bmaps,R,'GeoKeyDirectoryTag',GTT_GKDT);
            clear bmaps
            disp('-Bias has been computed.')
        end
        if iov(2) == 1
            disp(['-Calculating index ',num2str(ciov(2)),...
                                 ' of ',num2str(siov),': DIV...'])
            [div(:,m), av_div(m), dmaps]  = div3d(orig,test,ws,avv(2));
            geotiffwrite([smof '\DIV ' char(flnames(m)) '.tif'],...
                       dmaps,R,'GeoKeyDirectoryTag',GTT_GKDT);
            clear dmaps
            disp('-DIV has been computed.')
        end
        if iov(3) == 1
            disp(['-Calculating index ',num2str(ciov(3)),...
                                 ' of ',num2str(siov),': CC...'])
            [cc(:,m), av_cc(m), ccmaps]  = ccc3d(orig,test,ws);
            geotiffwrite([smof '\CC ' char(flnames(m)) '.tif'],...
                       ccmaps,R,'GeoKeyDirectoryTag',GTT_GKDT);
            clear ccmaps
            disp('-CC has been computed.')
        end
        if iov(4) == 1
            disp(['-Calculating index ',num2str(ciov(4)),...
                                 ' of ',num2str(siov),': Entropy Diff....'])
            % If image class = int16, convert to unint16 or double if needed
            if strcmp( class(orig),'int16' ) %#ok<STISA>
                if min(orig(:)) >= 0
                    i16 = 1;
                    orig = uint16(orig);
                    test = uint16(test);
                else
                    i16 = 2;
                    orig = double(orig);
                    test = double(test);
                end
            end
            clt = class(test);
            if ~strcmp( class(orig), class(test)  )
                cne = 1;
                orig = double(orig);
                test = double(test);
            end
            [Epb(:,m), Eav(m), edmaps]      = ediff3d(orig,test,ws,0,avv(3));
            % Return to original class
            if i16 ~= 0
                orig = int16(orig);
                test = int16(test);
            end
            if cne == 1;
                orig = cast(orig,clo);
                test = cast(test,clt);
            end
            geotiffwrite([smof '\Entropy Diff ' char(flnames(m)) '.tif'],...
                           edmaps,R,'GeoKeyDirectoryTag',GTT_GKDT);
            clear edmaps
            disp('-Entropy Diff has been computed.')
        end
        if iov(5) == 1
            disp(['-Calculating index ',num2str(ciov(5)),...
                                 ' of ',num2str(siov),': ERGAS...'])
            [ergas_pb(:,m), ergas_mpb, ergas_tl(m), ergas_map] = ...
                                                ergas3d(orig,test,resratio,ws);
            geotiffwrite([smof '\ERGAS_MPB ' char(flnames(m)) '.tif'],...
                           ergas_mpb,R,'GeoKeyDirectoryTag',GTT_GKDT);
            geotiffwrite([smof '\ERGAS ' char(flnames(m)) '.tif'],...
                           ergas_map,R,'GeoKeyDirectoryTag',GTT_GKDT);           
            clear ergas_mpb ergas_map
            disp('-ERGAS has been computed.')
        end
        if iov(6) == 1
            disp(['-Calculating index ',num2str(ciov(6)),...
                                 ' of ',num2str(siov),': Q...'])
            [qs(:,m), av_q(m), qmaps]       = q3d(orig,test,ws);
            geotiffwrite([smof '\Q ' char(flnames(m)) '.tif'],...
                           qmaps,R,'GeoKeyDirectoryTag',GTT_GKDT);           
            clear qmaps
            disp('-Q has been computed.')
        end
        if iov(5) == 1
            disp(['-Calculating index ',num2str(ciov(7)),...
                                 ' of ',num2str(siov),': RASE...'])
            [rase_pb(:,m), rase_mpb, rase_tl(m), rase_map] = ...
                                              rase3d(orig,test,ws);
            geotiffwrite([smof '\RASE_MPB ' char(flnames(m)) '.tif'],...
                           rase_mpb,R,'GeoKeyDirectoryTag',GTT_GKDT);
            geotiffwrite([smof '\RASE ' char(flnames(m)) '.tif'],...
                           rase_map,R,'GeoKeyDirectoryTag',GTT_GKDT);           
            clear rase_mpb rase_map
            disp('-RASE has been calculated.')
        end
        if iov(8) == 1
            disp(['-Calculating index ',num2str(ciov(8)),...
                                 ' of ',num2str(siov),': RMSE...'])
            [rmses(:,m), av_rmse(m), rmaps] = rmse3d(orig,test,ws);
            geotiffwrite([smof '\RMSE ' char(flnames(m)) '.tif'],...
                           rmaps,R,'GeoKeyDirectoryTag',GTT_GKDT);           
            clear rmaps
            disp('-RMSE has been calculated.');
        end
        disp(' ')
        % Since nin is relatively small, this check does not decrease
        % significantly the execution time.
        if p == 1 && fp == 1
            progressbar((m-1)/nin)
        end

    end

end

% User demands index map output with proper georeference
if mo == 1 && gtw == 1
  
    warning off MATLAB:mkdir:DirectoryExists
    % Set map output folder
    smof = [ handles.sof '\Index Maps' ]; 
    mkdir(smof)
    for m = 2:nin+1
        disp(' ')
        disp(['Parsing Test image # ', num2str(m-1),'...']) 
        test = imread(char(impaths(m)));
        disp(['Test image # ', num2str(m-1), ' parsed.'])
        disp(['Analyzing Test image # ', num2str(m-1), '....'])  
        disp(' ')
        if iov(1) == 1
            disp(['-Calculating index ',num2str(ciov(1)),...
                                 ' of ',num2str(siov),': Bias...'])
            [bias(:,m), av_bias(m), bmaps]  = bias3d(orig,test,ws,avv(1));
            geotiffclone(char(impaths(m)),...
                  [smof '\Bias ' char(flnames(m))],bmaps);
            clear bmaps
            disp('-Bias has been computed.')
        end
        if iov(2) == 1
            disp(['-Calculating index ',num2str(ciov(2)),...
                                 ' of ',num2str(siov),': DIV...'])
            [div(:,m), av_div(m), dmaps]    = div3d(orig,test,ws,avv(2));
            geotiffclone(char(impaths(m)),...
                  [smof '\DIV ' char(flnames(m))],dmaps);
            clear dmaps
            disp('-DIV has been computed.')
        end
        if iov(3) == 1
            disp(['-Calculating index ',num2str(ciov(3)),...
                                 ' of ',num2str(siov),': CC...'])
            [cc(:,m), av_cc(m), ccmaps]     = ccc3d(orig,test,ws);
            geotiffclone(char(impaths(m)),...
                  [smof '\CC ' char(flnames(m))],ccmaps);
            clear ccmaps
            disp('-CC has been computed.')
        end
        if iov(4) == 1
            disp(['-Calculating index ',num2str(ciov(4)),...
                                 ' of ',num2str(siov),': Entropy Diff....'])        
            % If image class = int16, convert to unint16 or double if needed
            if strcmp( class(orig),'int16' ) %#ok<STISA>
                if min(orig(:)) >= 0
                    i16 = 1;
                    orig = uint16(orig);
                    test = uint16(test);
                else
                    i16 = 2;
                    orig = double(orig);
                    test = double(test);
                end
            end
            clt = class(test);
            if ~strcmp( class(orig), class(test)  )
                cne = 1;
                orig = double(orig);
                test = double(test);
            end
            [Epb(:,m), Eav(m), edmaps]      = ediff3d(orig,test,ws,0,avv(3));
            % Return to original class
            if i16 ~= 0
                orig = int16(orig);
                test = int16(test);
            end
            if cne == 1;
                orig = cast(orig,clo);
                test = cast(test,clt);
            end
            geotiffclone(char(impaths(m)),...
                  [smof '\Entropy Diff ' char(flnames(m))],edmaps);
            clear edmaps
            disp('-Entropy Diff has been computed.')
        end
        if iov(5) == 1
            disp(['-Calculating index ',num2str(ciov(5)),...
                                 ' of ',num2str(siov),': ERGAS...'])
            [ergas_pb(:,m), ergas_mpb, ergas_tl(m), ergas_map] = ...
                                            ergas3d(orig,test,resratio,ws);
            geotiffclone(char(impaths(m)),...
                  [smof '\ERGAS_MPB ' char(flnames(m))],ergas_mpb);
            geotiffclone(char(impaths(m)),...
                  [smof '\ERGAS ' char(flnames(m))],ergas_map);         
            clear ergas_mpb ergas_map
            disp('-ERGAS has been computed.')
        end
        if iov(6) == 1
            disp(['-Calculating index ',num2str(ciov(6)),...
                                 ' of ',num2str(siov),': Q...'])
            [qs(:,m), av_q(m), qmaps]       = q3d(orig,test,ws);
            geotiffclone(char(impaths(m)),...
                  [smof '\Q ' char(flnames(m))],qmaps);         
            clear qmaps
            disp('-Q has been computed.')
        end
        if iov(7) == 1
            disp(['-Calculating index ',num2str(ciov(7)),...
                                 ' of ',num2str(siov),': RASE...'])
            [rase_pb(:,m), rase_mpb, rase_tl(m), rase_map] = ...
                                              rase3d(orig,test,ws);
            geotiffclone(char(impaths(m)),...
                  [smof '\RASE_MPB ' char(flnames(m))],rase_mpb);        
            geotiffclone(char(impaths(m)),...
                  [smof '\RASE ' char(flnames(m))],rase_map);               
            clear rase_mpb rase_map
            disp('-RASE has been calculated.')
        end
        if iov(8) == 1
            disp(['-Calculating index ',num2str(ciov(8)),...
                                 ' of ',num2str(siov),': RMSE...'])
            [rmses(:,m), av_rmse(m), rmaps] = rmse3d(orig,test,ws);
            geotiffclone(char(impaths(m)),...
                  [smof '\RMSE ' char(flnames(m))],rmaps);         
            clear rmaps
            disp('-RMSE has been calculated.');
        end
        disp(' ')
        % Since nin is relatively small, this check does not decrease
        % significantly the execution time.
        if p == 1 && fp == 1
            progressbar((m-1)/nin)
        end

    end

end

disp('-Focal Image index analysis completed.')
disp(' ')

ttime = toc;

disp(['>>> Elapsed time: ', num2str(ttime),' seconds. <<<'])
disp(' ')
%%
% Write excel file with all index analysis results

disp('-Preparing Excel Output...')
% Disable AddSheet Warning
warning off MATLAB:xlswrite:AddSheet
% Band count
cbnd    = num2cell(1:bands)';
cbnda   = [ {'BAND #'}; cbnd ; cell(1,1) ; {'AVERAGE'} ];
cbndt   = [ {'BAND #'}; cbnd ; cell(1,1) ; {'TOTAL'} ];
e_line =  cell(1,nin+1);
% Prepare cell per index
% Bias
cbiass = [ flnames' ; num2cell(bias); e_line; num2cell(av_bias)];
cbiass = [ cbnda, cbiass ];
% DIV
cdivs = [ flnames' ; num2cell(div); e_line; num2cell(av_div)];
cdivs = [ cbnda, cdivs ];
% CC
cccs = [ flnames' ; num2cell(cc); e_line; num2cell(av_cc)];
cccs = [ cbnda, cccs ];
% Entropy
centropys = [ flnames' ; num2cell(Epb); e_line; num2cell(Eav) ];
%             e_line   ; num2cell(Etl)                      ];
centropys = [ cbnda, centropys ];
% ERGAS
cergass = [ flnames' ; num2cell(ergas_pb); e_line; num2cell(ergas_tl)];
%            e_line  ; num2cell(ergas_tl)                    ];
cergass = [ cbndt, cergass ];
% Q
cqss = [ flnames' ; num2cell(qs); e_line; num2cell(av_q)];
cqss = [ cbnda, cqss ];
% RASE
crases = [ flnames' ; num2cell(rase_pb); e_line; num2cell(rase_tl)];
%            e_line ; num2cell(rase_tl)                  ];
crases = [ cbndt, crases ];
% RMSE
crmses = [ flnames' ; num2cell(rmses); e_line; num2cell(av_rmse)];
crmses = [ cbnda, crmses ];

% Determine if the system has Microsoft Excel installed..
csvmode = false;
try
   Excel = actxserver('excel.application'); %#ok<NASGU>
catch exc   %#ok<NASGU>
   csvmode = true;
   disp('-Cannot establish connection with Excel.')
   disp('-The indices values will be written in *.CSV format.')
   disp(' ')
end
% Output Results
if csvmode == false
    % Excel file name
    if ~exist( 'excel_name' ) %#ok<EXIST>
        excel_name = 'Focal Image Index Analysis.xls';
    end
    % Prepare output directory
    sof = handles.sof;
    excel_name = [ sof '\' excel_name ];
    % Write every index in the homonymous excel spreadsheet
    if iov(1) == 1
        xlswrite( excel_name, cbiass,       'Bias')
    end
    if iov(2) == 1
        xlswrite( excel_name, cdivs,        'DIV')
    end
    if iov(3) == 1
        xlswrite( excel_name, cccs,         'CC')
    end
    if iov(4) == 1
        xlswrite( excel_name, centropys,    'Entropy Diff')
    end
    if iov(5) == 1
        xlswrite( excel_name, cergass,      'ERGAS')
    end
    if iov(6) == 1
        xlswrite( excel_name, cqss,         'Q')
    end
    if iov(7) == 1
        xlswrite( excel_name, crases,       'RASE')
    end
    if iov(8) == 1
        xlswrite( excel_name, crmses,       'RMSE')
    end

    disp('-All indices have been written successfully in Excel file.')
    disp(' ')
else
    csv_name = 'Focal Image Index Analysis.csv';
    % Prepare output directory
    sof = handles.sof;
    csv_name = [ sof '\' csv_name ];
    e_line2 =  cell(1,nin+2);
    % Make one massive csv file
    if iov(1) == 1
        header = {'Bias'};
        header = repmat(header,[1 nin+2]);
        csvindices = [ header; cbiass; e_line2; e_line2 ];
    end
    if iov(2) == 1
        header = {'DIV'};
        header = repmat(header,[1 nin+2]);
        if ciov(2) > 1
            csvindices = [ csvindices; header; cdivs; e_line2; e_line2 ];
        else
            csvindices = [ header; cdivs; e_line2; e_line2 ];
        end
    end
    if iov(3) == 1
        header = {'CC'};
        header = repmat(header,[1 nin+2]);
        if ciov(3) > 1
            csvindices = [ csvindices; header; cccs; e_line2; e_line2 ];
        else
            csvindices = [ header; cccs; e_line2; e_line2 ];
        end
    end
    if iov(4) == 1
        header = {'Entropy Diff'};
        header = repmat(header,[1 nin+2]);
        if ciov(4) > 1
            csvindices = [ csvindices; header; centropys; e_line2; e_line2 ];
        else
            csvindices = [ header; centropys; e_line2; e_line2 ];
        end
    end
    if iov(5) == 1
        header = {'ERGAS'};
        header = repmat(header,[1 nin+2]);
        if ciov(5) > 1
            csvindices = [ csvindices; header; cergass; e_line2; e_line2 ];
        else
            csvindices = [ header; cergass; e_line2; e_line2 ];
        end
    end
    if iov(6) == 1
        header = {'Q'};
        header = repmat(header,[1 nin+2]);
        if ciov(6) > 1
            csvindices = [ csvindices; header; cqss; e_line2; e_line2 ];
        else
            csvindices = [ header; cqss; e_line2; e_line2 ];
        end
    end
    if iov(7) == 1
        header = {'RASE'};
        header = repmat(header,[1 nin+2]);
        csvindices = [ csvindices; header; crases; e_line2; e_line2 ];
    end
    if iov(8) == 1
        header = {'RMSE'};
        header = repmat(header,[1 nin+2]);
        if ciov(7) > 1
            csvindices = [ csvindices; header; crmses; e_line2; e_line2 ];
        else
            csvindices = [ header; crmses; e_line2; e_line2 ];
        end
    end
    % Write the massive .csv
    dlmcell( csv_name,          csvindices, ';')

    disp('-All indices have been written successfully in .CSV file.')
    disp(' ')
end
%%
% Thaw GUI (unfreeze)
set(handles.setoutfol_push,'Enable','on')
set(handles.ctestdata_push,'Enable','on')
set(handles.focusedit,'Enable','on')
set(handles.analyze_push,'Enable','on')
set(handles.ergasratio_edit,'Enable','on')
set(handles.opres_check,'Enable','on')
set(handles.psnd_check,'Enable','on')
set(handles.globalnone,'Enable','on')
set(handles.globalall,'Enable','on')
set(handles.exportgeoreference_check,'Enable','on')
set(handles.exportmaps_check,'Enable','on')
set(handles.loadtest_push,'Enable','on')
set(handles.loadorig_push,'Enable','on')
set(handles.absbias,'Enable','on')
set(handles.absentropy,'Enable','on')
set(handles.absdiv,'Enable','on')
set(handles.selectnone_push,'Enable','on')
set(handles.selectall_push,'Enable','on')
set(handles.rmse_check,'Enable','on')
set(handles.rase_check,'Enable','on')
set(handles.q_check,'Enable','on')
set(handles.ergas_check,'Enable','on')
set(handles.entropy_check,'Enable','on')
set(handles.div_check,'Enable','on')
set(handles.cc_check,'Enable','on')
set(handles.bias_check,'Enable','on')
%
% Play sound
psnd = get(handles.psnd_check,'value');
if psnd == true
    if exist('computer_standing_by.wav','file')
        [y,Fs] = wavread('computer_standing_by.wav');
    else
        load gong.mat;
    end
    sound(y, Fs);
end
% Open results (on windows systems)
opres = get(handles.opres_check,'value');
if opres == true
    if ispc
        if csvmode == false
            winopen(excel_name)
        else
            winopen(csv_name)
        end
    end
end
disp('=== Job:Done! ===')
disp(' ')
% Callback has been executed, user can reclick if he/she wants
set(hObject,'Enable','on')

% END OF CODE

Contact us