% Suppose that we have a following picture hanging on a blue wall
im = imread('footbalarge.jpg');
%clf;
%image(im);
axis('image');
x_margin = 10;
y_margin = 10;
im = imresize(im,0.20,'bilinear');
wall_picture = zeros([2*y_margin+size(im,1) 2*x_margin+size(im,2) 3]);
wall_picture(:,:,3) = 255;
wall_picture(y_margin+(1:size(im,1)), x_margin+(1:size(im,2)),:)=im;
figure(2);
image(wall_picture/255);
axis('image');
axis('off');
set(gcf,'Color',[0 0 1]);
axis('off');
set(gca,'Color',[0 0 1]);
wall_scale = 1;
% The original is at 0, 0, 0
% We need to specify the virtual camera

zz1=[size(wall_picture,2)/2 0 -100];
zz1=[size(wall_picture,2)*1.5 0 -20];
zz1 = [size(wall_picture,2)/2 size(wall_picture,1)/2 -100];
ccenter=[size(wall_picture,2)/2 size(wall_picture,1)/2 0];

z1 = ccenter - zz1;
z1= z1/norm(z1);
x1=[1 0 0];
x1=x1-(z1*x1')*z1;
x1=x1/norm(x1);
%fprintf(1,'%15.14f ', x1);
%fprintf(1,'\n');
y1=cross(z1', x1');
y1=y1/norm(y1);
y1=y1';

f1=0.5;
ppoint=ccenter+f1*z1;
t1=zz1';
R1=[x1;y1;z1]';

K1=[f1 0 0;0 f1 0; 0 0 1];
P1=K1*[R1' (-R1'*t1)];
figure(1);
lower_left = [0 0 0 1]';
lower_left = P1 * lower_left;
lower_left = lower_left/lower_left(3);
upper_right = [size(wall_picture,2) size(wall_picture,1) 0 1]';
upper_right = P1 * upper_right;
upper_right = upper_right/upper_right(3);

clf;
%set(gca,'XLim',[max(lower_left(1),upper_right(1)) max(lower_left(1),upper_right(1))]);
%set(gca,'YLim',[max(lower_left(2),upper_right(2)) max(lower_left(2),upper_right(2))]);
set(gca,'XLim',[-0.2 0.2]);
set(gca,'YLim',[-0.2 0.2]);
set(gcf,'Color',[1 1 1]);
axis('off');
set(gca,'Color',[1 1 1]);
axis equal;
hold on;
% we randomly pick a point on the wall
points = 0;
while 1,
   Z = 0;
   X = rand * size(wall_picture,2);
   if X < 1,
      X = 1;
   end
   if X > size(wall_picture,2),
      X = size(wall_picture,2);
   end
   
   Y = rand * size(wall_picture,1);
   if Y < 1,
      Y = 1;
   end
   if Y > size(wall_picture,1),
      Y = size(wall_picture,1);
   end
   cam_point = P1 * [X Y Z 1]';
   cam_point = cam_point / cam_point(3);
   h = plot(cam_point(1),cam_point(2),'.');
   pX = floor(X); if pX < 1, pX = 1; end
   pY = floor(Y); if pY < 1, pY = 1; end
   pY = size(wall_picture,1)-pY+1;
      
   set(h,'Color',wall_picture(pY,pX,:)/255);
   %set(h,'MarkerSize',[12]);
   %[xx, yyy, button]=ginput(1);
   %if button == 3,
   %   break;
   %end
   points = points+1;
   if points >= 2000;
      points = 0;
      keyboard;
      figure(1);
   end
   
end

    
   