C++简单实现膨胀腐蚀开闭运算

项目需要用到闭运算对结果做形态学处理,简单实现一个仅供参考。

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;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值