www.gusucode.com > IPCV_Eval_Kit_R2019a_0ce6858工具箱源码程序matlab > IPCV_Eval_Kit_R2019a_0ce6858/code/demo_files/I5_03_1_myOCRpreprop__rotation_correction.m

    %% 僥僉僗僩偺孹偒偺廋惓
clc;close all;imtool close all;clear;

%% 僥僗僩夋憸偺嶌惉
x = imread('text.png');
I = uint8(x(5:60,5:end-40)*255);
I = imrotate(I, 30, 'bicubic');     % 斀帪寁夞傝偵30搙夞揮
figure; imshow(I);

%% 夋憸偺傏偐偟 
BW = imdilate(logical(I), strel('disk',4));  
figure; imshow(BW);

%% Hough曄姺偟丄妏搙傪媮傔丄媡夞揮曗惓
%      H:     僴僼曄姺峴楍
%      theta: x幉抣 : 妏搙(亱)   -90亱乣89亱  惓偺X幉偵懳偟偰帪寁夞傝偵掕媊
%      rho  : y幉抣
[H,theta,rho] = hough(BW);
peak = houghpeaks(H, 1)        % 僺乕僋偺揰偺theta偲rho偺斣崋慻
%% 娭悢 houghlines 傪巊偭偰専弌偝傟偨慄偺昞帵
lines = houghlines(BW, theta, rho, peak);      %lines丗 point1, point2, theta, rho 傪帩偮峔憿懱
% 尦偺僀儊乕僕偵廳偹偰慄傪僾儘僢僩
hold on
xy = [lines.point1; lines.point2];   %   xy : [x1 y1; x2 y2]
plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');
hold off

%% 媡夞揮偟偰曗惓
if theta(peak(1,2)) > 0
    ang = 90 - theta(peak(1,2));
else
    ang = -1 * (90 + theta(peak(1,2)));
end
Irot = imrotate(I, -1 * ang, 'bicubic');     %ang暘媡夞揮
imtool(Irot);

%% 偝傜偵丄椞堟偺壓偺晹暘偺墢傊丄捈慄傪嬤帡偟偰孹偒傪嵞廋惓
BW2 = imdilate(logical(Irot), strel('disk',4)); 
[C, Ind] = max(flipud(BW2));
Ind(Ind == 1) = [];                       %暥帤偑側偄楍傪嶍彍
y = polyfit(0:(size(Ind,2)-1), Ind, 1);   %捈慄傪僼傿僥傿儞僌
ang2 = atan(y(1)) * (180/pi);             %捈慄偺孹偒偐傜妏搙傪寁嶼
Irot2 = imrotate(Irot, -1 * ang2, 'bicubic');      %ang2偺妏搙傪媡夞揮
imtool(Irot2);

%% [暿偺曽朄] Hough曄慜偵僄僢僕専弌
BWedge = edge(BW);
figure; imshow(BWedge);

%% Hough曄姺偟丄妏搙傪媮傔丄媡夞揮曗惓
[H,theta,rho] = hough(BWedge);
peak = houghpeaks(H, 1)        % 僺乕僋偺揰偺theta偲rho偺斣崋慻
if theta(peak(1,2)) > 0
    ang = 90 - theta(peak(1,2));
else
    ang = -1 * (90 + theta(peak(1,2)));
end
Irot2 = imrotate(I, -1 * ang, 'bicubic');    %ang暘媡夞揮
imtool(Irot2);

%%
% This is modified version of the following example.
% http://www.mathworks.com/help/releases/R2014a/vision/examples/text-rotation-correction.html
%
% Copyright 2014 The MathWorks, Inc.