%Psych 583B
%Homework 3
%Geoff Boynton

%Set up some general parameters and matrices

cmap = gray(256);  %gray-scale colormap
n = 400;  %number of pixels in each row/column of the images

%Do that meshgrid thing...
[x,y] = meshgrid(linspace(-1,1,n)); 

ang = atan2(y+1e-3,x-1e-3); %polar angle matrix(will range from -pi/2 to pi/2)
rad = sqrt(x.^2+y.^2);      %radius matrix (will range from 0 to 1)

%% Figure 1: The peripheral drift illusion

nCycles = 8;  %number of sawtooth repetitions around the circle.

%use the 'mod' to make a sawtooth as a function of polar angle.  The
%sawtooth will range from 0 to 1.
img1 = mod(ang,2*pi/nCycles)/(2*pi/nCycles);  

%set the outside of the circle to 1 (white)
img1(rad>1) = 1;

%scale the image to range from 0 to 255
img1 = img1*255;

%show the image
figure(1)
image(img1)
colormap(cmap)
axis equal
axis off

%% Figure 2: Same illusion in opposite direction
figure(2)

%note the '1-...' to reverse the ramp
img2 = 1- mod(ang,2*pi/nCycles)/(2*pi/nCycles);  
img2(rad>1) = 1;
img2 = img2*255;

image(img2);
colormap(cmap)
axis equal
axis off

%% Figure 3: Lightness constancy illusion

%Start with a ramp from black to white using the 'x' matrix.  Remember, 'x'
%ranges from -1 to 1.  After scaling, -1 will be black, and 1 will be
%white.
img3 = x;

%Set a rectangle inside the ramp image to zero (which will be mid-level gray)
img3(x> -.8 & x<.8 & y>-.1 & y<.1) = 0;

%scale the image so it ranges from 0 to 255
img3 = (img3+1)*127.5;

%show the image
figure(3)
image(img3)
colormap(cmap)
axis equal
axis off

%% Figure 4: Bonus problem, 'undoing' the lightness constancy illusion.

%We'll start with essentially the same code as for figure 3:

img = x;
img(x<.8 & x> -.8 & y<.5 & y>.3) = 0;  %bar is now in the lower part of the image

%Find the part of the image corresponding to the upper bar:
id = x<.8 & x> -.8 & y>-.5 & y<-.3;

%Inside this bar we'll stick in a ramp that's just like the background, but
%doesn't vary as quickly.  We'll need to choose a scale factor for this
%ramp:
k =.5; %Play with this number to make the bar look uniform.

%Inside the bar (as indexed by 'id'), put in valuse from the background ('x')
%multiplied by the scale factor 'k'.  Since 'x' ranges from -1 to 1, the image
%in the bar will range from -k to k.

img(id) = x(id)*k;

%scale the image so it ranges from 0 to 255
img = (img+1)*127.5;

%show the image
figure(4)
image(img)
colormap(cmap)
axis equal
axis off




