且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测图像中的对象的实例?

更新时间:2021-09-12 09:06:22

a href =http://***.com/revisions/8591515/1>最初发布此为gimme-da-codez问题,显示绝对没有努力,我去给你代码。我将一般性地描述一下方法,一路上有提示,你可以找出确切的代码来做。

Since you originally posted this as a 'gimme-da-codez' question, showing absolutely no effort, I'm not going to give you the code. I will describe the approach in general terms, with hints along the way and it's up to you to figure out the exact code to do it.

首先,如果你有一个模板,较大的图片,并且您想在图片中找到该模板的实例,始终认为互相关 。无论您是处理1D信号(在信号处理中称为匹配滤波器)还是2D图像,理论都是一样的。

Firstly, if you have a template, a larger image, and you want to find instances of that template in the image, always think of cross-correlation. The theory is the same whether you're processing 1D signals (called a matched filter in signal processing) or 2D images.


  • 将图片与已知模板互相关联,可在模板完全匹配的任何地方提供峰值。查找函数 normxcorr2 并了解文档中的示例。

  • 找到峰值后,您必须考虑原始图片中实际位置的偏移量。该偏移与使 N 点信号与 M 点信号互相关的事实导致 N + M -1 点输出。这应该是清楚的一旦你读了互相关,但你也应该看看我上面提到的文档中的例子来得到一个想法。

  • Cross-correlating an image with a known template gives you a peak wherever the template is an exact match. Look up the function normxcorr2 and understand the example in the documentation.
  • Once you find the peak, you'll have to account for the offset from the actual location in the original image. The offset is related to the fact that cross-correlating an N point signal with an M point signal results in an N + M -1 point output. This should be clear once you read up on cross-correlation, but you should also look at the example in the doc I mentioned above to get an idea.

一旦你做了这两个,那么其余的是微不足道的,只是涉及化妆品的你的结果。这是我在检测到上述对象之后的结果。

Once you do these two, then the rest is trivial and just involves cosmetic dressing up of your result. Here's my result after detecting the object following the above.

这里有几个代码提示,让你去。

Here's a few code hints to get you going. Fill in the rest wherever I have ...

%#read & convert the image
imgCol  = imread('http://i.stack.imgur.com/tbnV9.jpg');
imgGray = rgb2gray(img);
obj     = rgb2gray(imread('http://i.stack.imgur.com/GkYii.jpg'));

%# cross-correlate and find the offset
corr           = normxcorr2(...); 
[~,indx]       = max(abs(corr(:))); %# Modify for multiple instances (generalize)
[yPeak, xPeak] = ind2sub(...);
corrOffset     = [yPeak - ..., xPeak - ...]; 

%# create a mask
mask      = zeros(size(...));
mask(...) = 1;
mask      = imdilate(mask,ones(size(...)));

%# plot the above result
h1 = imshow(imgGray);
set(h1,'AlphaData',0.4)
hold on
h2 = imshow(imgCol);
set(h2,'AlphaData',mask)