How to straighten a tilted square shape in an imag

2019-03-01 06:14发布

问题:

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:

which should be rotated to give the following output image:

回答1:

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

AFTER



回答2:

One way:

I = imread('img.jpg');
I = rgb2gray(I);
Ibw = I<threshold; %find the good threshold
se = strel('square',sizesquare); %find the good size for the strel function.
Ibw = imdilate(Ibw,se); %fill the hole 
imshow(Ibw);

stat = regionprops(Ibw,'Extrema'); %extrema detection of the image.
point = stat.Extrema;
hold on
for i = 2:2:length(stat.Extrema)
    x = point(i,1);
    y = point(i,2);
    plot(x,y,'o');
    text(x,y,num2str(i),'color','w')
end
%construct the triangle that will help us to determine the shift angle.
P2 = [point(8,1),point(2,2)];
P1 = [point(8,1),point(8,2)];
P0 = [point(2,1),point(2,2)];

ang = atan2(abs(det([P2-P0;P1-P0])),dot(P2-P0,P1-P0))*180/pi

close all
imshow(imrotate(I,-ang))

STEP 1

STEP 2

STEP 3