如何拉直图像中倾斜的方形?

How to straighten a tilted square shape in an image?

如何拉直图像中倾斜的方形? 我不知道它倾斜的角度,代码必须计算它然后自动旋转它。

比如我有下面的图片:

应将其旋转以提供以下输出图像:

一种方式:

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))

第 1 步

第 2 步

第 3 步

一种仅使用顶角和底角的简单方法。请注意,此方法依赖于最上角和最下角:

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)

之前

之后