1 01.% 入口图像为 BW,出口图像为f
2 02.%optimize from main_optimize, merely select 2 lines, one has positive
3 03.%slope,the other has negative slope
4 04.clear all,close all
5 05.BW=imread('D:\Images\NEW\img4b9faef664e03.jpg');
6 06.figure,imshow(BW);
7 07.
8 08.BW=rgb2gray(BW);
9 09.%thresh=[0.01,0.17];
10 10.thresh=[0.01,0.10];
11 11.sigma=2;%定义高斯参数
12 12.f = edge(double(BW),'canny',thresh,sigma);
13 13.figure,subplot(121);
14 14.imshow(f,[]);
15 15.title('canny Edge Detect Result');
16 16.
17 17.[H, theta, rho]= hough(f, 0.1);%cos(theta)*x+sin(theta)*y=rho
18 18.%imshow(theta,rho,H,[],'notruesize'),axis on,axis normal
19 19.%xlabel('\theta'),ylabel('rho');
20 20.
21 21.[r,c]=houghpeaks(H,10);
22 22.hold on
23 23.
24 24.
25 25.lines=houghlines(f,theta,rho,r,c);
26 26.
27 27.subplot(122);
28 28.imshow(f,[]),title('Hough Transform Detect Result'),hold on
29 29.nlind=0;%new line index
30 30.st=1;
31 31.%%%%%%%%%求斜率%%%%%%%%%%%%
32 32.for k=1:length(lines)
33 33. %xy=[lines(k).point1;lines(k).point2];
34 34. xielv(k)=(lines(k).point2(1)-lines(k).point1(1))/(lines(k).point2(2)-lines(k).point1(2)+0.0001)
35 35.end
36 36.
37 37.%%%%%%%%%将相同斜率的直线连起来%%%%%%%%%%%%
38 38.k=1;
39 39.while(k<=length(lines))
40 40. if(k~=length(lines))
41 41. k=k+1;
42 42. end
43 43. while(abs(xielv(k)-xielv(k-1))<0.0001)
44 44. k=k+1;
45 45. if(k>length(lines))
46 46. break;
47 47. end
48 48. end
49 49.
50 50. if(abs(xielv(k-1))<0.05||abs(xielv(k-1))>=10)%eliminate horizontal and vertical lines,防治水平线和楼房
51 51. st=k;
52 52. if(k~=length(lines))
53 53. continue;
54 54. end
55 55. end
56 56.
57 57. if(st==length(lines)&&k==st)
58 58. if(abs(xielv(k))>0.05&&abs(xielv(k))<10)
59 59. nlind=nlind+1;
60 60. newlines(nlind)=lines(st);
61 61. newlines(nlind).point2=lines(k).point2;
62 62. newxy=[newlines(nlind).point1;newlines(nlind).point2];
63 63. plot(newxy(:,2),newxy(:,1),'LineWidth',4,'Color',[.6 1.0 .8]);
64 64. end
65 65. break;
66 66. end
67 67.
68 68. %end=k-1,start=st; draw line
69 69. nlind=nlind+1;
70 70. newlines(nlind)=lines(st);
71 71. newlines(nlind).point2=lines(k-1).point2;
72 72. newxy=[newlines(nlind).point1;newlines(nlind).point2];
73 73. plot(newxy(:,2),newxy(:,1),'LineWidth',4,'Color',[.6 1.0 .8]);
74 74.
75 75. st=k;
76 76.end
77 77.
78 78.fprintf('%d lines are detected in sum.\n',nlind);