编辑:2014 年 5 月 2 日
现在了解您要实现的目标,我现在可以帮助您解决问题。由于您是 MATLAB 的初学者,因此我将使用更简单的方法(尽管有更复杂的方法可以帮助您解决这个问题),因为我想演示该算法的工作原理。
您基本上想要实现normxcorr2
,但您只想在模板中包含标记为黑色的像素。您还想跳过搜索图像中非黑色的位置。那样的话,我会一步一步地为你布置算法,然后写一些代码。
- 读入模板并提取那些黑色的像素位置
- 在滑动窗口方式中,对于与搜索图像中的模板大小相同的每个图像块...
- 如果整个图像补丁是白色的,请跳过
- 提取相同的黑色位置
- 仅使用这些位置计算 NCC。
- 输出将是一张地图,其中包含搜索图像中每个位置的 NCC
我不会处理搜索图像中边框像素的情况,因为我假设您希望能够将搜索图像中的某些内容与模板的完整大小进行匹配。
这里有一些假设。让我们假设以下变量:
imTemplate
- 模板图像,比如你给我看的那个
imSearch
- 我们在做这个 NCC 的东西时希望搜索的图像
我还假设每个图像都是二进制的,因为您的帖子标题中有“0 或 1”。
因此,我为您准备了以下代码:
[rowsSearch colsSearch] = size(imSearch); % Get dimensions of search image
[rowsTemp colsTemp] = size(imTemplate); % Get dimensions of template image
mapBlack = imSearch == 0; % Obtain a map of where the black pixels are in the template
numPixelsCompare = sum(mapBlack(:)); % Need to know how many pixels are valid for comparison
% Obtain area of searching within the search image
startSearchRows = 1 + floor(rowsSearch/2);
endSearchRows = rowsSearch - floor(rowsSearch/2);
startSearchCols = 1 + floor(colsSearch/2);
endSearchCols = colsSearch - floor(colsSearch/2);
% Need half the dimensions of each for the template dimensions... you will
% see why we need this later
rowsTempHalf = floor(rowsTemp/2);
colsTempHalf = floor(colsTemp/2);
% Where we will store our NCC calculations
NCCMap = zeros(rowsSearch, colsSearch);
% Because you want to include all of the black pixels in your
% calculations, and these are all the same, the signal you are comparing
% to basically consists of all white pixels.
% Create a vector that consists of all 1s that is the same size as how
% many black pixels exist in the template
compareSignal = ones(numPixelsCompare, 1);
% For each location in the search image (ensuring that the full template
% is inside the image)
for i = startSearchRows : endSearchRows
for j = startSearchCols : endSearchCols
% Grab an image patch that is the same size as the template
% At each location (i,j) this serves as the CENTRE of the image
% patch, and we are grabbing pixels surrounding this centre that
% will create a patch that is the same size as the template
searchBlock = imSearch(i-rowsTempHalf:i+rowsTempHalf, ...
j-colsTempHalf:j+colsTempHalf);
% If all of the pixels are white, skip
if (all(searchBlock == 1))
continue;
end
% Extract only those pixels that are valid in the template
searchPixels = searchBlock(mapBlock);
% Must invert so that black pixels become white
% You mentioned that white pixels are "background"
searchPixels = ~searchPixels;
% Compute NCC for this patch
NCCMap(i,j) = compareSignal'*searchPixels / ...
(sqrt(compareSignal'*compareSignal) * sqrt(searchPixels'*searchPixels));
end
end
如果你对我计算 NCC 的方式有点困惑,那基本上是你习惯的,但我使用向量代数来计算它。这应该有希望给你你想要的。要找到模板匹配的最佳位置,您可以执行以下操作来提取该位置的行和列:
[r,c] = find(NCCMap == max(NCCMap(:)));
我希望这能解决你的问题。它的效率有点低,而且它确实会开始受到更高分辨率的图像的影响,但我想给你一个好的开始,这样你就不会坐在那里试图自己解决问题。
注意:我尚未测试此代码,因为我没有您用来解决此问题的示例搜索图像。希望这会奏效。发表评论,让我知道进展如何。