MATLAB: Does the REGIONPROPS command not return the correct orientation for a square region

Image Processing Toolbox

I am trying to determine the orientation of a square region in a bitmap image relative to the X-axis. I have written the following code to illustrate the limitation of the 'Orientation' property of the REGIONPROPS command:
s = imread('square0.bmp'); %file is attached
imshow(s); %start with a square parallel to x-axis
s15 = imrotate(s, 15); %rotate the image by 15 degrees
figure(2);
imshow(s15);
g = rgb2gray(s15); %convert to greyscale
l = bwlabel(g); %label the regions
p = regionprops(l, 'Orientation', 'MajorAxisLength', 'MinorAxisLength')
%find the orientation of the region
srot = imrotate(s15, -(p.Orientation));
%attempt to rotate the region back to a horizontal position
figure(3);
imshow(srot);
The image is rotated 15 degrees. I then attampt to rotate the square
back to an orientation parallel to the x-axis using the opposite of the
angle calculated by REGIONPROPS. However, the final orientation is not
parallel to the x-axis. The angle of orientationof the rotated figure is 54 degrees. This is clearly not 15 degrees as I expected.

Best Answer

The 'Orientation' property of REGIONPROPS returns a scalar value corresponding to the angle (in degrees) between the x-axis and the major axis of the ellipse that has the same second-moments as the region.
In order to find the angle of rotation of a square, you might want to use the 'Extrema' field of the output of REGIONPROPS. Given the extrema (square corners), you will be able to calculate the angle as in the example below:
s = imread('square0.bmp'); %file is attached
s15 = imrotate(s, 15); %rotate the square 15 degrees
g = rgb2gray(s15); %convert to greyscale
p = regionprops(l, 'Extrema');
sides = p.Extrema(4,:) - p.Extrema(6,:); % Returns the sides of the square triangle that completes the two chosen extrema: Bottom-Right and Left-Bottom
OrientationAngle = rad2deg(atan(-sides(2)/sides(1))) ; % Note the 'minus' sign compensates for the inverted y-values in image coordinates
This illustatres how to find the angle orientation of a rotated square object in all cases (orientation relative to the lower right side of the square). Note that when you run this program the angle returned is not exactly 15 degrees. The reason for this discrepancy is the the angle is computed based on the pixel centers, which usually will not be on the exact X-Y values of the corner, since pixel centers cannot be a fraction of a pixel away from each other.