原理部分:https://blog.youkuaiyun.com/qq_25847123/article/details/73744575
代码:
#include <iostream>
#include<vector>
#include<iomanip>
using namespace std;
#define picX 6
#define picY 6
typedef struct _coord
{
int x;
int y;
}COORD;
int originPic[picX][picY] = {
{0,0,0,0,0,0},
{0,1,0,0,0,0},
{0,1,1,1,0,0},
{0,0,1,1,0,0},
{0,0,1,0,0,0},
{0,0,0,0,0,0}
};
vector<COORD> structEle;//存放结构元素的位置
void init()
{
COORD pos[] = { {0,-1},{1,0},{0,0} };
for (auto p : pos)
structEle.push_back(p);
}
void output(int data[picX][picY]);
//膨胀
void expand()
{
int dst[picX][picY] = { 0 };
for (int i = 0; i < picX; i++)
{
for (int j = 0; j < picY; j++)
{
if (originPic[i][j] == 1)
{
for (auto p : structEle)
{
int dsX = i + p.x;
int dsY = j + p.y;
if (dsX >= 0 && dsX<picX && dsY >= 0 && dsY<picY) //防止越界
dst[dsX][dsY] = 1;
}
}
}
}
output(dst);
}
//腐蚀
void corrosion()
{
int dst[picX][picY] = { 0 };
for (int i = 0; i < picX; i++)
{
for (int j = 0; j < picY; j++)
{
//
if (originPic[i][j] == 1)
{
bool bAllBlack = true;
for (auto p : structEle)
{
int dsX = i + p.x;
int dsY = j + p.y;
if (dsX >= 0 && dsX < picX && dsY >= 0 && dsY < picY) //防止越界
{
if (originPic[dsX][dsY] == 0)
bAllBlack = false;
}
}
if (bAllBlack)
dst[i][j] = 1;
}
}
}
output(dst);
}
int main() {
init();
//expand();
corrosion();
system("pause");
return 0;
}
void output(int data[picX][picY])
{
for (int i = 0; i < picX; i++)
{
for (int j = 0; j < picY; j++)
cout << setw(4) << data[i][j];
cout << endl;
}
}