
%Reads a square color image and ROTATES it clockwise by angle theta (in radians).
clear;load flag.mat;N=size(X,1);theta=pi/6;%angle of rotation.
%Zero-pad image to odd size if image size is even:
Y(N,N,1:3)=0;if(2*floor(N/2)==N);X(N+1,N+1,:)=0;end;Y(N+1,N+1,1:3)=0;
X=(X-min(min(min(X))))/(max(max(max(X)))-min(min(min(X))));
figure,imagesc(X),axis off,title('Original image')
SN=round(sqrt(2)*N);X(SN,SN,:)=0;Y(SN,SN,:)=0;%Zero-pad to accommodate rotated image.
A=[cos(theta),sin(theta);-sin(theta),cos(theta)];%Rotation matrix.
I=[floor([0:N^2-1]/N)',mod([0:N^2-1],N)']+1;IS=(N+1)/2;JS=round(IS*sqrt(2));
I=I-IS;J=round(I*A);I=I+IS;J=J+JS;%center image for rotation about its center.
X1=X(:,:,1);X2=X(:,:,2);X3=X(:,:,3);Y1=Y(:,:,1);Y2=Y(:,:,2);Y3=Y(:,:,3);
Y1(SN*(J(:,1)-1)+J(:,2))=X1(SN*(I(:,1)-1)+I(:,2));%MATLAB hack: Represent matrix by
Y2(SN*(J(:,1)-1)+J(:,2))=X2(SN*(I(:,1)-1)+I(:,2));%unwrapping to vector and using that.
Y3(SN*(J(:,1)-1)+J(:,2))=X3(SN*(I(:,1)-1)+I(:,2));%Nearest-neighbor interpolation.
Y(:,:,1)=Y1;Y(:,:,2)=Y2;Y(:,:,3)=Y3;
figure,imagesc(Y),axis off,title('Rotated image')

