%% How an Image is a vector
% This page describes how one can think of a digital images as a vector in a vector space.  Essentially, one rearranges the pixel values from the rectangular shape of an image into a one-diminsional list of real numbers (usually integers in [0,255].

%% The Image Function
% The MATLAB function "image.m" creates an image from a matrix.  You pass it the matrix, scaled to have values in [0,1], and it converts each entry in the matrix to a color.  Since any color can basically be thought of as a combination of three primary colors (red-green-blue), you can create a full color image by creating a "3-dimensional matrix", or cube. 
RandomColorMatrix = 255*rand(4,4,3)
figure;
%% A random color matrix (3 different matrices, stacked like pancakes) 
image(1/255*RandomColorMatrix);


%% A random greyscale matrix (1 random matrix, copied and stacked) 
% A random can be seen in several different, but really equivalent ways.  The first is as either a red, green or blue sheet.  MyColors will be a "black matrix" filled with zeros, RandomMatrix is filled with random numbers in [0,1]. 
RandomMatrix = round(255*rand(4,4))

%% In red
MyColors = zeros(4,4,3);
MyColors(:,:,1) = RandomMatrix; 
figure;
image(1/255*MyColors);

%% In green
MyColors = zeros(4,4,3);
MyColors(:,:,2) = RandomMatrix;
figure;
image(1/255*MyColors);

%% In blue
MyColors = zeros(4,4,3);
MyColors(:,:,3) = RandomMatrix;
figure;
image(1/255*MyColors);

%% In grey
MyColors = zeros(4,4,3);
MyColors(:,:,1) = RandomMatrix;
MyColors(:,:,2) = RandomMatrix;
MyColors(:,:,3) = RandomMatrix;
figure;
image(1/255*MyColors);

%% Linear combinations of color
% Any color can be thought of as a kind of "linear combination" of three basis colors, red, green and blue.  For example, if 
zero_matrix = zeros(4,4,3);
red = zero_matrix;
	red(:,:,1) = ones(4);
green = zero_matrix;
	green(:,:,2) = ones(4);
blue = zero_matrix;
	blue(:,:,3) = ones(4);
% then white is 
% To see this color we can map the three components of the vector to the three color components expected by the image function (after scaling appropriately). 

%% White as the linear combination 
white = 255*red + 255*green + 255*blue;
figure;
image(1/255*MyColors);


%% Animations of many linear combinations

%Prepare the new file.
	Vid = VideoWriter('deform_blue');
	open(Vid);
	h =  []; % Initial handle to plot
	k = 1; % Index of snapshot
	MyFig = figure; hold on; 
	axis off
	set(gca,'nextplot','replacechildren','visible','off')

% Let the coefficient of the blue vector vary from 0 to 255, and plot the results
for c = 0:255
	FunnyColor = 45*red + 35*green + c*blue;
	MaxValue = max(max(max(FunnyColor)));
	image(1/MaxValue*FunnyColor);
	frame = getframe(MyFig);
 	writeVideo(Vid,frame);
end
close(Vid);

	




