% %%ROTATE LEG SEGMENT
clc; % Clear command window.
close all; % Close all figure windows except those created by imtool.
imtool close all; % Close all figure windows created by imtool.
workspace; % Make sure the workspace panel is showing.
filename = input('Enter image file name: ', 's');
legsegment = input('Enter leg segment (Coxa, Femur, Tibia, Tarsus): ', 's');
%
% Convert TIFF to PNG
a = imread(filename);
newfilename=strrep(filename, 'tif', 'png');
imwrite(a , newfilename);
%
% Show cropped image
I1=imread(newfilename);
imshow(I1);
set(gcf, 'Position', get(0,'Screensize')); % Maximize figure.
% Select points to register
message = sprintf('Click Data Cursor and select points while holding alt.\nRight click and Export data to workspace. Click OKAY and Hit ENTER when finished');
uiwait(msgbox(message));
%
% Hit ENTER to continue.
pause
p1=cursor_info(1,2).Position;
p2=cursor_info(1,1).Position;
p11=[1000,4608];
p22=[6000,4608];
[imR imC] = size(I1);
%
% The image points are in "image coordinates, with (1,1) at top left.
% Flip these into cartesion form, with (0,0) in the bottom left.
paddy=@(p)[p(1),imR-p(2)];
p1 = paddy(p1);
p2 = paddy(p2);
p11 = paddy(p11);
p22 = paddy(p22);
%
% Create our objects, from real and imaginary axis points. p1(1,1) is x,
% p1(1,2) is y of the cartesian. This forms complex points, c1 which is x+yi.
% These are the original points
c1 = complex(p1(1,1),p1(1,2));
c2 = complex(p2(1,1),p2(1,2));
% These are the rotated points
c11 = complex(p11(1,1),p11(1,2));
c22 = complex(p22(1,1),p22(1,2));
%
% Create the "A" matrix
A = zeros(4,4);
A(1,1) = real(c1);
A(1,2) = -imag(c1);
A(2,1) = real(c2);
A(2,2) = -imag(c2);
A(1,3) = 1;
A(2,3) = 1;
A(3,1) = imag(c1);
A(3,2) = real(c1);
A(4,1) = imag(c2);
A(4,2) = real(c2);
A(3,4) = 1;
A(4,4) = 1;
%
% Set up the b matrix
b = zeros(4,1);
b(1,1) = real(c11);
b(2,1) = real(c22);
b(3,1) = imag(c11);
b(4,1) = imag(c22);
%
% Solve for X =
x = A\b;
% the x vector now has r, and t...
r = complex(x(1,1),x(2,1));
% Convert to degrees
R=angle(r);
angleDegrees=R*180/pi;
%
% Rotate our leg segment
I3 = imrotate(I1,angleDegrees,'bilinear','crop');
figure;
% Display
subplot(1,2,1);
imshow(I1);
subplot(1,2,2);
imshow(I3);
%
% change to correct file name
rotnewfilename = strcat('rot', newfilename);
imwrite(I3, rotnewfilename);
end