关于MATLAB中Hough变换提取直线

,本人正在利用Hough变换进行直线提取,现在已经对图像进行了分割和数学形态学的处理,可是在Hough变换提取直线是怎么都不对,求一个正确的Hough 变换的程序!急啊!先谢谢各位了!附上经数学形态学处理后的照片。目的是把道路的两条边界线提取出来。


  1. clear all
  2. close all
  3. clc
  4. I=imread('2220.jpg');
  5. BW=im2bw(I);
  6. BW=edge(BW,'canny');
  7. % I=imdilate(I,strel('disk',8));
  8. % I=imerode(I,strel('disk',8));
  9. % BW=bwmorph(I,'thin',20);
  10. %%

  11. [H,T,R] = hough(BW);
  12. imshow(H,[],'XData',T,'YData',R,...
  13. 'InitialMagnification','fit');
  14. xlabel('\theta'), ylabel('\rho');
  15. axis on, axis normal, hold on;
  16. P = houghpeaks(H,10,'threshold',ceil(0.3*max(H(:))));
  17. x = T(P(:,2)); y = R(P(:,1));
  18. plot(x,y,'s','color','white');
  19. lines = houghlines(BW,T,R,P,'FillGap',5,'MinLength',7);
  20. figure,imshow(BW), hold on
  21. max_len = 0;
  22. %%

  23. for k = 1:length(lines)
  24. xy = [lines(k).point1; lines(k).point2];
  25. plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');

  26. % Plot beginnings and ends of lines
  27. plot(xy(1,1),xy(1,2),'x','LineWidth',2,'Color','yellow');
  28. plot(xy(2,1),xy(2,2),'x','LineWidth',2,'Color','red');

  29. % Determine the endpoints of the longest line segment
  30. len = norm(lines(k).point1 - lines(k).point2);
  31. Len(k)=len
  32. if ( len > max_len)
  33. max_len = len
  34. xy_long = xy
  35. end
  36. end

  37. % highlight the longest line segment
  38. plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','blue');

  39. %%
  40. [L1 Index1]=max(Len(:))
  41. Len(Index1)=0
  42. [L2 Index2]=max(Len(:))

  43. %%
  44. %
  45. x1=[lines(Index1).point1(1) lines(Index1).point2(1)]
  46. y1=[lines(Index1).point1(2) lines(Index1).point2(2)]
  47. x2=[lines(Index2).point1(1) lines(Index2).point2(1)]
  48. y2=[lines(Index2).point1(2) lines(Index2).point2(2)]

  49. %%
  50. K1=(lines(Index1).point1(2)-lines(Index1).point2(2))/(lines(Index1).point1(1)-lines(Index1).point2(1))
  51. K2=(lines(Index2).point1(2)-lines(Index2).point2(2))/(lines(Index2).point1(1)-lines(Index2).point2(1))
  52. %%
  53. hold on
  54. [m,n] = size(BW); % 尺寸
  55. BW1=zeros(m,n);
  56. b1=y1(1)-K1*x1(1)
  57. b2=y2(1)-K2*x2(1)
  58. for x=1:n
  59. for y=1:m
  60. if y==round(K1*x+b1)|y==round(K2*x+b2)
  61. BW1(y,x)=1;

  62. end

  63. end
  64. end
  65. for x=1:n
  66. for y=1:m

  67. if ceil(K1*x+b1)==ceil(K2*x+b2)
  68. y1=round(K1*x+b1)
  69. BW1(1:y1-1,:)=0;
  70. end
  71. end
  72. end
  73. figure,imshow(BW1)

 

你可能感兴趣的:(matlab)