% Psych 221 Final Project
% Stereo Imaging
% AJ Minich, Ajminich@stanford.edu
% Winter 2008

% DESCRIPTION
% Takes an image and creates an anaglyph image, assuming you are wearing 3D glasses.
% Controls: x_variation, y_variation, threshold, left/right color screen,
%  scattering

function image_3D = anaglyph(image_name);

% Parameters
x_variation = 8;   % horizontal separation between images
y_variation = 2;    % vertical separation between images
threshold = 255;   % threshold below which we can consider an image to have color

% Screens - depends on what kind of glasses you're using
left_screen = [0 1 1];     % cyan
right_screen = [1 0 0];    % red

scattering = 0;     % rough distance between pixels in the separated image

% Get image data
image_data = imread(image_name);

% Extract dimensions
image_dimensions = size(image_data);
image_height = image_dimensions(1);
image_width = image_dimensions(2);
image_colorspace = image_dimensions(3);

% Convert the image to grayscale
intensities = color2gray(image_data);           % for threshold purposes
grayscale_image = color2shadow(image_data);

% Make initial assignment to output image
left_overlay = grayscale_image;
right_overlay = grayscale_image;

% If intensity is below the 'threshold' parameter, leave out the pixel
for current_y = 1:image_height,
    for current_x = 1:image_width,
       
        if(intensities(current_y,current_x) <= threshold)
            % Left image
            if(round(rand(1)*scattering) == 0)
                left_overlay(current_y,current_x,1) = grayscale_image(current_y,current_x,1) * left_screen(1);
                left_overlay(current_y,current_x,2) = grayscale_image(current_y,current_x,2) * left_screen(2);
                left_overlay(current_y,current_x,3) = grayscale_image(current_y,current_x,3) * left_screen(3);
            end

            % Right image
            if(round(rand(1)*scattering) == 0)
                right_overlay(current_y,current_x,1) = grayscale_image(current_y,current_x,1) * right_screen(1);
                right_overlay(current_y,current_x,2) = grayscale_image(current_y,current_x,2) * right_screen(2);
                right_overlay(current_y,current_x,3) = grayscale_image(current_y,current_x,3) * right_screen(3);
            end
        end
        
    end
end

% Shift the images by the x and y variations
left_x_extend = [left_overlay zeros(image_height,x_variation,3)];
left_xy_extend = [left_x_extend; zeros(y_variation, image_width + x_variation, 3)];

right_x_extend = [zeros(image_height,x_variation,3) right_overlay];
right_xy_extend = [zeros(y_variation, image_width + x_variation, 3); right_x_extend];

overlay = left_xy_extend + right_xy_extend;

x_coordinates = (x_variation + 1) : (image_width - x_variation);
y_coordinates = (y_variation + 1) : (image_height - y_variation);

image_3D = overlay(y_coordinates, x_coordinates, 1:end);
