Hough变换 直线检测原理及其Matlab实现

来源:互联网 发布:淘宝充300抢150的攻略 编辑:程序博客网 时间:2024/06/03 00:32

 霍夫变换直线检测的原理

 

 笛卡尔坐标(x,y坐标)系上的直线y=kx+b 可以在极坐标系上可以用下式表示

                          r=x cosθ + ysinθ ,

其中r为该原点到该直线的距离,θ为该直线和x轴的夹角。

 那么可以通过计算每个点x,y上,假设经过该点的直线与x轴为θ ,然后θ 从(1~180度)进行计算,分别得到不同的r值。

最后统计图片中经过各点,各个角度的直线概率最高的(r,θ)值,

我们认为这个值就是图片中真正的直线对应的r, θ值。 也即图片中直线对应的Normal Line(法线)长度r及其与x轴的夹角θ

 

以下是其Matlab程序实现。以下程序首先读取图片,并得到图片的大小rows,columns.

然后用Counters=zeros(rmax,180)数组用来统计各个r, θ的概率。

找到概率值最高的r, θ.

然后重新遍历图片,当x,y值满足r=x cosθ + ysinθ 时即认为该点是检测到的直线上的点。

 

A=imread('1.bmp');

imshow(A);

A_gray=rgb2gray(A);

 

%Get The Image Size

[rows,columns]=size(A_gray);

 

%define and initiate the Counters.

rmax=round(sqrt(rows^2+columns^2))

Counters=zeros(rmax,180);

 

 

%Begin to count

tic      %-------------start to timing.

for x=1:columns

    for y=1:rows

        if(A_gray(y,x)==0)

            for m=1:180

                r=round(x*cos(m*pi/180)+y*sin(m*pi/180));

                if(r<rmax & r>0)

                    Counters(r,m)=Counters(r,m)+1;

                end

            end

        end%end of if(A_gray(y,x)==0)

    end%end of y=1;rows

end

toc

 

%Get the line max probable,print the r (distance) and angle

tic

CounterMax=0

for i=1:rmax

    for j=1:180

        if(CounterMax<Counters(i,j))

            CounterMax=Counters(i,j);

            iMax=i;%it's the r ,distance from the original to the line.

            jMax=j;%it's the angle bettween the normal line and the x axis.

        end

    end

end

toc

CounterMax

iMax

jMax

Counters(iMax,jMax)

X=iMax/cos(pi*jMax/180)

Y=iMax/sin(pi*jMax/180)

 

%get the line and remove(strip away) the background.

tic

for x=1:columns

    for y=1:rows

        if(A_gray(y,x)==0)

            r=round(x*cos(jMax*pi/180)+y*sin(jMax*pi/180));

            if(r==iMax)

                 %only the dot on the line will be dark.

                 %other dot will be change to be white.

                A_gray(y,x)=80;

            else

                A_gray(y,x)=255;

            end

        else

            A_gray(y,x)=255;

        end

    end

end

toc

 

imshow(A_gray)

原创粉丝点击