Main Content

このページの内容は最新ではありません。最新版の英語を参照するには、ここをクリックします。

ハフ変換

Image Processing Toolbox™ は、ハフ変換関数を使用してイメージ内の線を検出する関数をサポートしています。

関数 hough は標準ハフ変換 (SHT) を実装します。ハフ変換は、線のパラメトリック表現を使用して線を検出するように設計されています。

rho = x*cos(theta) + y*sin(theta)

変数 rho は線に垂直なベクトルに沿った原点から線までの距離です。theta は X 軸とこのベクトルとの間の角度です。関数 hough は行と列がそれぞれ rhotheta の値に対応するパラメーター空間行列を生成します。

ハフ変換の後、関数 houghpeaks を使用してパラメーター空間でのピーク値を検出できます。ピークは入力イメージ内の潜在的な線を表します。

ハフ変換でのピークを特定してからは、関数 houghlines を使用してそのピークに対応する線分の端点を検出できます。この関数は線分内の小さな切れ目を自動的に埋めます。

Hough を使用したイメージ内の線の検出

この例では、Hough 変換を使用してイメージ内の線を検出する方法を説明します。

イメージをワークスペースに読み取ります。この例では説明をわかりやすくするために、イメージを回転します。イメージを表示します。

I = imread('circuit.tif');
rotI = imrotate(I,33,'crop');
imshow(rotI)

Figure contains an axes object. The axes object contains an object of type image.

関数 edge を使用してイメージ内のエッジを検出します。

BW = edge(rotI,'canny');
imshow(BW);

Figure contains an axes object. The axes object contains an object of type image.

edge によって返されたバイナリ イメージのハフ変換を計算します。

[H,theta,rho] = hough(BW);

関数 hough によって返された変換 H を表示します。

figure
imshow(imadjust(rescale(H)),[],...
       'XData',theta,...
       'YData',rho,...
       'InitialMagnification','fit');
xlabel('\theta (degrees)')
ylabel('\rho')
axis on
axis normal 
hold on
colormap(gca,hot)

Figure contains an axes object. The axes object with xlabel theta blank (degrees), ylabel rho contains an object of type image.

関数 houghpeaks を使用してハフ変換行列 H 内のピークを検出します。

P = houghpeaks(H,5,'threshold',ceil(0.3*max(H(:))));

ピークを示す変換イメージの上に重ね合わせてプロットします。

x = theta(P(:,2));
y = rho(P(:,1));
plot(x,y,'s','color','black');

Figure contains an axes object. The axes object with xlabel theta blank (degrees), ylabel rho contains 2 objects of type image, line. One or more of the lines displays its values using only markers

関数 houghlines を使用してイメージ内の線を検出します。

lines = houghlines(BW,theta,rho,P,'FillGap',5,'MinLength',7);

元のイメージに線を重ね合わせて表示するプロットを作成します。

figure, imshow(rotI), hold on
max_len = 0;
for k = 1:length(lines)
   xy = [lines(k).point1; lines(k).point2];
   plot(xy(:,1),xy(:,2),'LineWidth',2,'Color','green');

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

   % Determine the endpoints of the longest line segment
   len = norm(lines(k).point1 - lines(k).point2);
   if ( len > max_len)
      max_len = len;
      xy_long = xy;
   end
end
% highlight the longest line segment
plot(xy_long(:,1),xy_long(:,2),'LineWidth',2,'Color','red');

Figure contains an axes object. The axes object contains 38 objects of type image, line. One or more of the lines displays its values using only markers