canny運算元和hough變換
阿新 • • 發佈:2019-02-15
<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);">Canny運算元在matlab中的應用</span>
BW = edge(I,'canny')指定canny演算法
BW = edge(I,'canny',thresh)中為canny演算法指定敏感閾值,thresh是一個兩值元素,第一個元素是小閾值,第二個元素是大閾值,如果指定一個thresh數值,則該值用來表示大閾值,0.4*thresh用來表示小閾值。如果沒有指定thresh或者thresh為空,edge()函式自動選擇大、小閾值,選擇的thresh與影象的最大梯度幅值有關。
BW = edge(I,'canny',thresh,sigma)中的sigma作為高斯濾波器的標準偏差,預設的sigma值是sqrt(2) ,濾波器的大小根據sigma自動選擇。
Hough變換在matlab中的應用
可以用於在影象中尋找直線、圓及其他簡單形狀的方法。
hough變換檢測直線的matlab程式,如下
[H,theta,rho] = hough(BW);%呼叫hough函式,BW為事先讀取的二值影象。 %用imshow顯示hough變換 figure(3), imshow(imadjust(mat2gray(H)),[],'XData',theta,'YData',rho,... 'InitialMagnification','fit'); xlabel('\theta (degrees)'), ylabel('\rho');%設定座標軸標籤 axis on, axis normal, hold on; colormap(hot) %設定矩陣圖的顏色對映, P = houghpeaks(H,4,'threshold',ceil(0.3*max(H(:))));%呼叫houghpeaks函式,H是hough矩陣,4是峰值個數 x = theta(P(:,2));%P的橫座標 y = rho(P(:,1));%P的縱座標 plot(x,y,'s','color','green'); lines = houghlines(BW,theta,rho,P,'FillGap',30,'MinLength',80);%呼叫houghlines函式 % lines為結構陣列,長度等於找到的線段數,結構中的每一個元素可以看作一條直線,幷包含有下列欄位 % point1:兩元素向量[r1, c1],指定了線段起點的行列座標。 % point2:兩元素向量[r2, c2],指定了線段終點的行列座標。 % theta:與線相關的霍夫變換的以度計量的角度。 % rho:與線相關的霍夫變換的ρ軸位置。 % val1是正的標量,指定了與相同的霍夫變換相關的兩條線段的距離。當兩條線段之間的 % 距離小於指定的值時,函式houghlines把線段合併為一條線段(預設的距離是20個像 % 素)。引數val2是正的標量,指定合併的線是保留還是丟棄。如果合併的線比val2指定 % 的值短,就丟棄(預設值是40)。 figure, imshow(I), hold on max_len = 0; for k = 1:length(lines) x_y = [lines(k).point1; lines(k).point2]; %point1:兩元素向量[r1, c1],指定了線段起點的行列座標。 %point2:兩元素向量[r2, c2],指定了線段終點的行列座標。 plot(x_y(:,1),x_y(:,2),'LineWidth',2,'Color','green'); %xy(:,1)表示xy()的第一列元素,即起點和終點的橫座標 %xy(:,2)表示xy()的第二列元素,即起點和終點的縱座標 % Plot beginnings and ends of lines plot(x_y(1,1),x_y(1,2),'x','LineWidth',2,'Color','yellow');%起點 plot(x_y(2,1),x_y(2,2),'x','LineWidth',2,'Color','red');%終點 % Determine the endpoints of the longest line segment len = norm(lines(k).point1 - lines(k).point2);%計算2範數,即兩個點之間的距離 if ( len > max_len) max_len = len; xy_long = x_y;%把座標點賦給xy_long end end