Main Content

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

パターン マッチング

この例では、2 次元の正規化された相互相関を使用してパターン マッチングとターゲット追跡を行う方法を説明します。ここでは事前定義あるいはユーザー指定されたターゲットと、追跡する類似ターゲットの数を使用して追跡を行います。正規化された相互相関プロットには、設定されたしきい値を値が超えるとターゲットが特定されることが示されます。

はじめに

この例では、正規化された相互相関を使用してビデオ内のターゲット パターンを追跡します。パターン マッチングのアルゴリズムには以下の手順が含まれます。

  • 入力ビデオ フレームとテンプレートのサイズを小さくして、マッチング アルゴリズムで必要となる計算量を最小化します。

  • 周波数領域で、正規化された相互相関を使用して、ビデオ フレーム内のテンプレートを検索します。

  • 最大の相互相関値を見つけることにより、パターンの位置を特定します。

パラメーターの初期化とテンプレートの作成

相互相関用のしきい値およびガウス ピラミッド分解の分解レベルなどの必要な変数を初期化します。

threshold = single(0.99);
level = 2;

ビデオ ファイル リーダーを準備します。

hVideoSrc = VideoReader('vipboard.mp4');

ターゲット イメージと追跡する類似ターゲットの数を指定します。既定の設定では、例では事前定義されたターゲットを使用して、最大 2 個の類似パターンを検出します。変数 useDefaultTarget を false に設定し、新しいターゲットと、マッチする類似ターゲットの数を指定します。

useDefaultTarget = true;
[Img, numberOfTargets, target_image] = ...
  videopattern_gettemplate(useDefaultTarget);

% Downsample the target image by a predefined factor. You do this
% to reduce the amount of computation needed by cross correlation.
target_image = single(target_image);
target_dim_nopyramid = size(target_image);
target_image_gp = multilevelPyramid(target_image, level);
target_energy = sqrt(sum(target_image_gp(:).^2));

% Rotate the target image by 180 degrees, and perform zero padding so that
% the dimensions of both the target and the input image are the same.
target_image_rot = imrotate(target_image_gp, 180);
[rt, ct] = size(target_image_rot);
Img = single(Img);
Img = multilevelPyramid(Img, level);
[ri, ci]= size(Img);
r_mod = 2^nextpow2(rt + ri);
c_mod = 2^nextpow2(ct + ci);
target_image_p = [target_image_rot zeros(rt, c_mod-ct)];
target_image_p = [target_image_p; zeros(r_mod-rt, c_mod)];

% Compute the 2-D FFT of the target image
target_fft = fft2(target_image_p);

% Initialize constant variables used in the processing loop.
target_size = repmat(target_dim_nopyramid, [numberOfTargets, 1]);
gain = 2^(level);
Im_p = zeros(r_mod, c_mod, 'single'); % Used for zero padding
C_ones = ones(rt, ct, 'single');      % Used to calculate mean using conv

正規化された相互相関の局所的最大値を計算する System object を作成します。

hFindMax = vision.LocalMaximaFinder( ...
            'Threshold', single(-1), ...
            'MaximumNumLocalMaxima', numberOfTargets, ...
            'NeighborhoodSize', floor(size(target_image_gp)/2)*2 - 1);

パターンの追跡状態を表示する System object を作成します。

sz = get(0,'ScreenSize');
pos = [20 sz(4)-400 400 300];
hROIPattern = vision.VideoPlayer('Name', 'Overlay the ROI on the target', ...
    'Position', pos);

正規化された相互相関値をプロットする Figure ウィンドウを初期化します。

hPlot = videopatternplots('setup',numberOfTargets, threshold);

ビデオ内のテンプレートの検索

入力ビデオのパターン マッチングを実行するための処理ループを作成します。このループは上記でインスタンス化した System object を使用します。ループは入力ファイルの末尾に達すると停止します。ファイルの末尾は VideoReader オブジェクトによって検出されます。

while hasFrame(hVideoSrc)
    Im = im2gray(im2single(readFrame(hVideoSrc)));

    % Reduce the image size to speed up processing
    Im_gp = multilevelPyramid(Im, level);

    % Frequency domain convolution.
    Im_p(1:ri, 1:ci) = Im_gp;    % Zero-pad
    img_fft = fft2(Im_p);
    corr_freq = img_fft .* target_fft;
    corrOutput_f = ifft2(corr_freq);
    corrOutput_f = corrOutput_f(rt:ri, ct:ci);

    % Calculate image energies and block run tiles that are size of
    % target template.
    IUT_energy = (Im_gp).^2;
    IUT = conv2(IUT_energy, C_ones, 'valid');
    IUT = sqrt(IUT);

    % Calculate normalized cross correlation.
    norm_Corr_f = (corrOutput_f) ./ (IUT * target_energy);
    xyLocation = step(hFindMax, norm_Corr_f);

    % Calculate linear indices.
    linear_index = sub2ind([ri-rt, ci-ct]+1, xyLocation(:,2),...
        xyLocation(:,1));

    norm_Corr_f_linear = norm_Corr_f(:);
    norm_Corr_value = norm_Corr_f_linear(linear_index);
    detect = (norm_Corr_value > threshold);
    target_roi = zeros(length(detect), 4);
    ul_corner = (gain.*(xyLocation(detect, :)-1))+1;
    target_roi(detect, :) = [ul_corner, fliplr(target_size(detect, :))];

    % Draw bounding box.
    Imf = insertShape(Im, 'Rectangle', target_roi, 'Color', 'green');
    % Plot normalized cross correlation.
    videopatternplots('update',hPlot,norm_Corr_value);
    step(hROIPattern, Imf);
end

snapnow

% Function to compute pyramid image at a particular level.
function outI = multilevelPyramid(inI, level)

I = inI;
outI = I;

for i=1:level
    outI = impyramid(I, 'reduce');
    I = outI;
end

end

まとめ

この例では、Computer Vision Toolbox™ を使用してビデオ内でユーザー定義されたパターンを見つけて追跡する方法を説明しました。アルゴリズムはターゲットとテスト対象イメージ間の正規化された周波数領域の相互相関に基づいています。ビデオ プレーヤー ウィンドウには識別されたターゲットの位置を示す入力ビデオが表示されます。また、ターゲットのマッチにメトリクスとして使用される、ターゲットとイメージ間の正規化された相関を示す Figure も表示されます。相関値がしきい値 (青いライン) を超えると入力ビデオ内のターゲットが識別され、その位置が緑の境界ボックスでマークされます。

付録

この例では次の補助関数が使用されています。