资源描述:
《Hough变换直线检测MatLab代码》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、Hough变换直线检测MatLab代码一.functionImg_hough=hough_s(Img,bw)%该函数实现hough变换提取直线的功能。%输入图像x,运行之后直接画出直线。%选择进行Hough变换的图像行%Img为原图像;bw为边缘图像%%[H,W,D]=size(Img);Img_hough=Img;ifD==1 channel=Img_hough; Img_hough=cat(3,channel,channel,channel);end[M,N]=size(bw);%求出图像大
2、小。%%dtheta=1;drho=1;md=ceil((N+round(sqrt(M^2+N^2)))/drho);%确定网格的最大区域。ma=ceil(180/dtheta);numrhotheta=zeros(md,ma);%产生计数矩阵。coordrhotheta=cell(1,1);%para=cell(1,3);�ll数组相当于c语言中的指针,可动态的改变大小。fori=1:md forj=1:ma coordrhotheta{i,j}=[]; endend%产生空网格。
3、ymin=5;ymax=M-4;fori=ymin:ymax forj=1:N ifbw(i,j)==1 fork=1:ma rho=round((j*cos(dtheta*k*pi/180)+i*sin(dtheta*k*pi/180))/drho); %根据直线的法线式表示,计算出平面上不同点的hough变换值。 rho=rho+ceil(N/drho);%可能的最大负值。
4、 numrhotheta(rho+1,k)=numrhotheta(rho+1,k)+1; %将hough变换值相应位置的计数值加1。 coordrhotheta{rho+1,k}=[coordrhotheta{rho+1,k};[i,j]]; %记录hough变换值相应位置对应的点的坐标。 end end endend%%figure;imshow(Img);ho
5、ldonnum=8;fori=1:num [y1,col1]=max(numrhotheta); [y2,col]=max(y1); row=col1(col); %求出hough变换值最大值的坐标。 numrhotheta(row,col)=0; %为了避免重复计算,将计算过的点置0。 rhood=1; chood=0; top=max(row-rhood,1); down=min(row+rhood,md); left=max(col-chood,1);
6、 right=min(col+chood,ma); numrhotheta(top:down,left:right)=0; % nds=coordrhotheta{row,col}; nds=[]; forr=top:down forc=left:right nds=[nds;coordrhotheta{r,c}]; end end Img_hough=draw(Img_hough,nds);endimwrite(mat2gra
7、y(numrhotheta),'numrhotheta.bmp') 二.RGB=imread('gantrycrane.png');I=rgb2gray(RGB);%converttointensityBW=edge(I,'canny');%extractedges[H,T,R]=hough(BW,'RhoResolution',0.5,'ThetaResolution',0.5);%displaytheoriginalimagesubplot(2,1,1);imshow(RGB);title('ga
8、ntrycrane.png');%displaythehoughmatrixsubplot(2,1,2);imshow(imadjust(mat2gray(H)),'XData',T,'YData',R,...'InitialMagnification','fit');title('Houghtransformofgantrycrane.png');xlabel('theta'),ylabel('rho');axison,axisnor