那里有大量的示例实现.. 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;
}
}
}
以上代码基于本教程(查看页面末尾的源代码)。
编辑2:
list.add(inImage(X+I-sz, Y+J-sz));
这个想法是我们想要在位于 (X,Y) 的当前图像像素上叠加以 sz (掩码的一半大小)为中心的内核掩码(大小为 nxn),然后只获得掩码所在的像素的强度值为 1(我们将它们添加到列表中)。一旦提取了该像素的所有邻居,我们将输出图像像素设置为该列表的最大值(最大强度)用于膨胀,最小用于腐蚀(当然这仅适用于灰度图像和二进制掩码)
两个 X 的索引上述语句中的 /Y 和 I/J 假设从 0 开始。如果您愿意,您可以随时用掩码的一半大小(从 -sz 到 +sz)重写 I/J 的索引小的变化(我链接到的教程的使用方式)......
示例:
考虑这个 3x3 内核掩码放置并以像素 (X,Y) 为中心,看看我们如何遍历它周围的邻域:
--------------------
| | | | 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) );
| | | |
--------------------