项目需要用到闭运算对结果做形态学处理,简单实现一个仅供参考。
void Erosion(BYTE* image, BYTE* res, int nHeight, int nWidth)//二值图像膨胀
{
for (int i = 1; i < nHeight - 1; i++)
{
for (int j = 1; j < nWidth - 1; j++)
{
int pos = i*nWidth + j;
int up = pos - nWidth;
int upleft = pos - nWidth - 1;
int upright = pos - nWidth + 1;
int left = pos - 1;
int right = pos + 1;
int downleft = pos + nWidth - 1;
int down = pos + nWidth;
int downright = pos + nWidth + 1;
(image[pos] || image[up] || image[upleft] || image[upright] || image[left] || image[right] || image[downleft] || image[down] || image[downright]) ? res[pos] = 255 : res[pos] = 0;
}
}
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < nWidth; j++)
{
int tmppos = i*nWidth + j;
res[tmppos] = image[tmppos];
}
}
for (int i = 1; i < nHeight - 1; i++)
{
int tmppos1 = i*nWidth;
res[tmppos1] = image[tmppos1];
int tmppos2 = (i + 1)*nWidth - 1;
res[tmppos2] = image[tmppos2];
}
for (int i = nHeight - 1; i < nHeight; i++)
{
for (int j = 0; j < nWidth; j++)
{
int tmppos = i*nWidth + j;
res[tmppos] = image[tmppos];
}
}
}
void Dilation(BYTE* image, BYTE* res, int nHeight, int nWidth)//二值图像腐蚀
{
for (int i = 1; i < nHeight - 1; i++)
{
for (int j = 1; j < nWidth - 1; j++)
{
int pos = i*nWidth + j;
int up = pos - nWidth;
int upleft = pos - nWidth - 1;
int upright = pos - nWidth + 1;
int left = pos - 1;
int right = pos + 1;
int downleft = pos + nWidth - 1;
int down = pos + nWidth;
int downright = pos + nWidth + 1;
(image[pos] && image[up] && image[upleft] && image[upright] && image[left] && image[right] && image[downleft] && image[down] && image[downright]) ? res[pos] = 255 : res[pos] = 0;
}
}
for (int i = 0; i < 1; i++)
{
for (int j = 0; j < nWidth; j++)
{
int tmppos = i*nWidth + j;
res[tmppos] = image[tmppos];
}
}
for (int i = 1; i < nHeight - 1; i++)
{
int tmppos1 = i*nWidth;
res[tmppos1] = image[tmppos1];
int tmppos2 = (i + 1)*nWidth - 1;
res[tmppos2] = image[tmppos2];
}
for (int i = nHeight - 1; i < nHeight; i++)
{
for (int j = 0; j < nWidth; j++)
{
int tmppos = i*nWidth + j;
res[tmppos] = image[tmppos];
}
}
}
void Closeoperations(BYTE* image, BYTE* res, int nHeight, int nWidth)//形态学闭操作
{
BYTE* transition = new BYTE[nHeight*nWidth];
Erosion(image, transition, nHeight, nWidth);
Dilation(transition, res, nHeight, nWidth);
delete[]transition;
}
void Openoperations(BYTE* image, BYTE* res, int nHeight, int nWidth)//形态学开操作
{
BYTE* transition = new BYTE[nHeight*nWidth];
Dilation(image, transition, nHeight, nWidth);
Erosion(transition, res, nHeight, nWidth);
delete[]transition;
}