clc;    % Clear the command window.
close all;  % Close all figures (except those of imtool.)
clear;  % Erase all existing variables.
workspace;  % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 20;

%===============================================================================
% Read in demo image.
% folder = pwd;
% baseFileName = 'Being-Human.jpg';
% 
% Get the full filename, with path prepended.
% fullFileName = fullfile(folder, baseFileName);
% 
% if ~exist(fullFileName, 'file')
%   Didn't find it there.  Check the search path for it.
%   fullFileName = baseFileName; % No path this time.
%   if ~exist(fullFileName, 'file')
%     Still didn't find it.  Alert user.
%     errorMessage = sprintf('Error: %s does not exist.', fullFileName);
%     uiwait(warndlg(errorMessage));
%     return;
%   end
% end
rgbcamera = videoinput('kinect',1,'RGB_640x480');
rgbImage = getsnapshot(rgbcamera);
% Get the dimensions of the image.  
% numberOfColorChannels should be = 1 for a gray scale image, and 3 for an RGB color image.
[rows, columns, numberOfColorChannels] = size(rgbImage);

if numberOfColorChannels > 1
  % It's not really gray scale like we expected - it's color.
  % Use weighted sum of ALL channels to create a gray scale image.
  grayImage = rgb2gray(rgbImage); 
  % ALTERNATE METHOD: Convert it to gray scale by taking only the green channel,
  % which in a typical snapshot will be the least noisy channel.
  % grayImage = grayImage(:, :, 2); % Take green channel.
else
  grayImage = rgbImage; % It's already gray.
end

% Display the original color image.
subplot(2, 2, 1);
imshow(grayImage);
axis on;
title('Original Color Image', 'FontSize', fontSize, 'Interpreter', 'None');

% Enlarge figure to full screen.
set(gcf, 'Units', 'Normalized', 'Outerposition', [0, 0, 1, 1]);

% Let's compute and display the histogram.
[pixelCount, grayLevels] = imhist(grayImage);
subplot(2, 2, 2); 

% The white bin is so huge that it suppresses the other bins, so set it to the nex highest
pixelCount(end) = pixelCount(end-1);
bar(grayLevels, pixelCount, 'BarWidth', 1); % Plot it as a bar chart.
grid on;
title('Histogram of gray scale image', 'FontSize', fontSize, 'Interpreter', 'None');
xlabel('Gray Level', 'FontSize', fontSize);
ylabel('Pixel Count', 'FontSize', fontSize);
xlim([0 grayLevels(end)]); % Scale x axis manually.

% Threshold the image.
thresholdValue = 100;
binaryImage = grayImage < thresholdValue;

% Draw line on histogram at the threshold value.
line([thresholdValue, thresholdValue], ylim, 'Color', 'r', 'LineWidth', 2);

% Fill holes
binaryImage = imfill(binaryImage, 'holes');

% Display the mask image.
subplot(2, 2, 3);
imshow(binaryImage);
axis on;
title('Binary Image', 'FontSize', fontSize, 'Interpreter', 'None');

% Find the topmost pixel in the mask
topRows = rows * ones(1, columns);
for col = 1 : columns
  thisTopRow = find(binaryImage(:, col), 1, 'first');
  if ~isempty(thisTopRow)
    topRows(col) = thisTopRow;
  end
end

% Display the top rows.
subplot(2, 2, 4);
imshow(rgbImage);
hold on;
plot(1:columns, topRows, 'b-', 'LineWidth', 2);
axis on;
title('Color Image with Top Rows', 'FontSize', fontSize, 'Interpreter', 'None');