Main Content

ROI オブジェクトを使用した角度測定ツールの作成

メモ

この例で使用する関数 impoly は推奨されていません。代わりに、新しい関数 drawpolyline および Polyline ROI オブジェクトを使用してください。ポリラインを使用した角度測定ツールの作成を参照してください。

この例では、対話型ツールと ROI オブジェクトを使用して角度測定ツールを作成する方法を説明します。この例では、Figure ウィンドウにイメージを表示し、そのイメージの上に簡単な角度測定ツールを重ね合わせます。角度測定ツールでラインを移動させると、2 つのラインで作られる角度が計算されてタイトルに表示されます。

イメージを引数として受け入れ、Figure ウィンドウのイメージの上に角度測定ツールを表示する関数を作成します。このコードには 2 つ目の関数が含まれており、角度を計算して Figure に表示するコールバック関数として使用します。

function my_angle_measurement_tool(im)
% Create figure, setting up properties
figure("Name","My Angle Measurement Tool",...
      "NumberTitle","off",...
      "IntegerHandle","off")

% Display image in the axes % Display image
imshow(im)

% Get size of image.
m = size(im,1);
n = size(im,2);

% Get center point of image for initial positioning.
midy = ceil(m/2);
midx = ceil(n/2);

% Position first point vertically above the middle.
firstx = midx;
firsty = midy - ceil(m/4);
lastx = midx + ceil(n/4);
lasty = midy;

% Create a two-segment right-angle polyline centered in the image.
h = impoly(gca,[firstx,firsty;midx,midy;lastx,lasty],"Closed",false);
api = iptgetapi(h);
initial_position = api.getPosition()

% Display initial position
updateAngle(initial_position)

% set up callback to update angle in title.
api.addNewPositionCallback(@updateAngle);
fcn = makeConstrainToRectFcn("impoly",get(gca,"XLim"),get(gca,"YLim"));
api.setPositionConstraintFcn(fcn);
%

% Callback function that calculates the angle and updates the title.
% Function receives an array containing the current x,y position of
% the three vertices.
function updateAngle(p)
% Create two vectors from the vertices.
% v1 = [x1 - x2, y1 - y2]
% v2 = [x3 - x2, Y3 - y2]
v1 = [p(1,1)-p(2,1), p(1,2)-p(2,2)];
v2 = [p(3,1)-p(2,1), p(3,2)-p(2,2)];
% Find the angle.
theta = acos(dot(v1,v2)/(norm(v1)*norm(v2)));
% Convert it to degrees.
angle_degrees = (theta * (180/pi));
% Display the angle in the title of the figure.
title(sprintf("(%1.0f) degrees",angle_degrees))

イメージをワークスペースに読み取ります。

I = imread("gantrycrane.png");

角度測定ツールを開き、引数としてイメージを指定します。Figure ウィンドウが開き、イメージの中央に角度測定ツールが直角に表示されます。イメージの角度を測定するには、ポインターをツールのいずれかの頂点に移動します。次の図では、ツールがイメージの角度を測定しています。図のタイトルに表示された角度のサイズに注目してください。

my_angle_measurement_tool(I);

Angle measurement tool appears as two joined line segments over an image. The title of the figure displays the current angle in degrees between the line segments.

関連するトピック