%% Distingush Hyperspectral Regions Using Spectral Angle Mapper
% Distingush different regions in a hyperspectral data cube by computing the spectral angle distance between each pixel and the endmember spectra of the data cube.
% Read hyperspectral data into the workspace.

hcube = hypercube('jasperRidge2_R198.hdr');

% Identify the number of spectrally distinct bands in the data cube by using  the countEndmembersHFC function.

numEndmembers = countEndmembersHFC(hcube)

% Extract the endmember spectral signatures from the data cube by using the NFINDR algorithm.

endmembers = nfindr(hcube,numEndmembers);

% Plot the spectral signatures of the endmembers. The result shows the 14 spectrally distinct regions in the data cube.

figure
plot(endmembers)
legend('Location','Bestoutside')

% Compute the spectral angular distance between each endmember and the spectra of each pixel in the data cube.

score = zeros(size(hcube.DataCube,1),size(hcube.DataCube,2),numEndmembers);
for i = 1:numEndmembers
    score(:,:,i) = sam(hcube,endmembers(:,i));
end

% Compute the minimum score value from the distance scores obtained for each pixel spectra with respect to all the endmembers. The index of each minimum score identifies the endmember spectra to which a pixel spectra exhibits maximum similarity. An index value, n, at the spatial location (x, y) in the score matrix indicates that the spectral signature of the pixel at spatial location (x, y) in the data cube best matches the spectral signature of the nth endmember.

[~,matchingIndx] = min(score,[],3);

% Estimate an RGB image of the hyperspectral data cube by using the colorize function. Display both the RGB image and the matrix of matched index values.

rgbImg = colorize(hcube,'Method','RGB');
figure('Position',[0 0 1100 500])
subplot('Position',[0 0.15 0.4 0.8])
imagesc(rgbImg)
axis off
title('RGB Image of Hyperspectral Data')
subplot('Position',[0.45 0.15 0.4 0.8])
imagesc(matchingIndx)
axis off
title('Indices of Matching Endmembers')
colorbar

% Copyright 2020 The MathWorks, Inc.