那里有大量的示例实现。Google 是你的朋友 :)
编辑
以下是该过程的伪代码(非常类似于在 2D 中进行卷积)。我相信有更聪明的方法来做到这一点:
// grayscale image, binary mask
void morph(inImage, outImage, kernel, type) {
// half size of the kernel, kernel size is n*n (easier if n is odd)
sz = (kernel.n - 1 ) / 2;
for X in inImage.rows {
for Y in inImage.cols {
if ( isOnBoundary(X,Y, inImage, sz) ) {
// check if pixel (X,Y) for boundary cases and deal with it (copy pixel as is)
// must consider half size of the kernel
val = inImage(X,Y); // quick fix
}
else {
list = [];
// get the neighborhood of this pixel (X,Y)
for I in kernel.n {
for J in kernel.n {
if ( kernel(I,J) == 1 ) {
list.add( inImage(X+I-sz, Y+J-sz) );
}
}
}
if type == dilation {
// dilation: set to one if any 1 is present, zero otherwise
val = max(list);
} else if type == erosion {
// erosion: set to zero if any 0 is present, one otherwise
val = min(list);
}
}
// set output image pixel
outImage(X,Y) = val;
}
}
}
以上代码基于此tutorial(查看页尾源码)。
EDIT2:
list.add(inImage(X+I-sz, Y+J-sz));
我们的想法是,我们想在位于 (X,Y) 的当前图像像素上叠加以 sz(掩码的一半大小)为中心的内核掩码(大小为 nxn),然后只得到像素的强度其中掩码值为 1(我们将它们添加到列表中)。一旦提取了该像素的所有邻居,我们将输出图像像素设置为该列表的最大值(最大强度)以进行扩张,并设置最小值以进行侵蚀(当然这仅适用于灰度图像和二进制掩码)
上述语句中 X/Y 和 I/J 的索引均假定从 0 开始。
如果您愿意,您始终可以用掩码的一半大小(从 -sz 到 +sz)重写 I/J 的索引,只需稍作更改(我链接到的教程使用的方式)...
示例:
考虑这个放置并以像素 (X,Y) 为中心的 3x3 内核掩码,看看我们如何遍历它周围的邻域:
--------------------
| | | | sz = 1;
-------------------- for (I=0 ; I<3 ; ++I)
| | (X,Y) | | for (J=0 ; J<3 ; ++J)
-------------------- vect.push_back( inImage.getPixel(X+I-sz, Y+J-sz) );
| | | |
--------------------