Search code examples
matlabimage-processingimage-rotation

How to straighten a tilted square shape in an image?


How can I straighten a tilted square shape in an image? I do not know the angle with which it is tilted and the code must calculate it and then rotate it automatically.

For example, I have the following image:

input_image

which should be rotated to give the following output image:

output_image


Solution

  • A simple way using only the top and bottom corners. Note that this approach relies on the upper and lower most corners:

    i = imread('sq.jpg');
    i_bw = im2bw(i)==0;
    % Modify the strel as required
    se = strel('square', 10);
    i_ed = imopen(i_bw, se);
    
    limits = sum(i_ed, 2);
    
    top_y = find(limits>0, 1);
    bottom_y = find(limits>0, 1, 'last');
    top_x = round(mean(find(i_ed(top_y, :)>0)));
    bottom_x = round(mean(find(i_ed(bottom_y, :)>0)));    
    
    slope = -1 * (top_y - bottom_y)/(top_x - bottom_x);
    rot_angle = 2 * pi * atan(slope);
    
    i2 = imrotate(i, -rot_angle);
    imshow(i2)
    

    BEFORE BEFORE_SQ

    AFTER AFTER_SQ