C语言实现BMP图像处理(闭运算)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fengxianghui01/article/details/85239193

闭运算可以把比结构元素小的特定图像细节出去,同时保证不产生全局的几何失真。填充比结构元素小的缺口或孔,搭接短的间断而起到连接作用。

运算:也就是先膨胀后腐蚀。

#include <stdio.h>
#include <stdlib.h>
#include <Windows.h>

int main(int* argc, char** argv)
{
	FILE* fp = fopen("./threshold.bmp", "rb");
	if (fp == 0)
		return 0;
	BITMAPFILEHEADER fileHead;
	fread(&fileHead, sizeof(BITMAPFILEHEADER), 1, fp);

	BITMAPINFOHEADER infoHead;
	fread(&infoHead, sizeof(BITMAPINFOHEADER), 1, fp);
	int width = infoHead.biWidth;
	int height = infoHead.biHeight;
	int biCount = infoHead.biBitCount;

	int lineByte = (biCount*width / 8 + 3) / 4 * 4;
	RGBQUAD* pColorTable;
	pColorTable = new RGBQUAD[256];
	fread(pColorTable, sizeof(RGBQUAD), 256, fp);

	unsigned char* pBmpBuf;
	pBmpBuf = new unsigned char[lineByte*height];
	fread(pBmpBuf, lineByte*height, 1, fp);
	fclose(fp);

	// 新图
	FILE* fop = fopen("close.bmp", "wb");
	if (fop == 0)
		return 0;

	// 膨胀操作
	// 初始化
	int t = 0, d = 0, r = 0;
	unsigned char* pBmpBuf2;
	pBmpBuf2 = new unsigned char[lineByte*height];
	for (int i = 0; i < height; ++i){
		for (int j = 0; j < width; ++j){
			*(pBmpBuf2 + i*lineByte + j) = 255;
		}
	}

	for (int i = 1; i < height; ++i){
		for (int j = 0; j < width - 1; ++j){
			t = *(pBmpBuf + i*lineByte + j);       // 当前点
			d = *(pBmpBuf + (i - 1)*lineByte + j); // 下面点
			r = *(pBmpBuf + i*lineByte + j + 1);   // 右边点
			if (t == 0 && d == 0 && r == 0){
				*(pBmpBuf2 + i*lineByte + j) = 0;       // 当前点
			}
		}
	}
	// 结构元素向上反转180度,对最下面一排处理
	for (int j = 0; j < width - 1; ++j){
		t = *(pBmpBuf + j);            // 当前点
		d = *(pBmpBuf + lineByte + j); // 上面点
		r = *(pBmpBuf + j + 1);        // 右边点
		if (t == 0 && d == 0 && r == 0){
			*(pBmpBuf2 + j) = 0;       // 当前点
		}
	}
	// 结构元素向右反转,对最右边一列处理
	for (int i = 1; i < height; ++i){
		t = *(pBmpBuf + i*lineByte + width - 1);
		d = *(pBmpBuf + (i - 1)*lineByte + width - 1);
		r = *(pBmpBuf + i*lineByte + width - 2);
		if (t == 0 && d == 0 && r == 0){
			*(pBmpBuf2 + i*lineByte + width - 1) = 0;       // 当前点
		}
	}

	// 腐蚀操作
	for (int i = 1; i < height; ++i){
		for (int j = 0; j < width - 1; ++j){
			t = *(pBmpBuf2 + i*lineByte + j);       // 当前点
			d = *(pBmpBuf2 + (i - 1)*lineByte + j); // 下面点
			r = *(pBmpBuf2 + i*lineByte + j + 1);   // 右边点
			if (t == 0 && d != 0){
				*(pBmpBuf2 + (i - 1)*lineByte + j) = 0;//下边的置位1
			}
			if (t == 0 && r != 0){
				*(pBmpBuf2 + i*lineByte + j + 1) = 0;//右边的置位1
				j = j + 1;
			}
		}
	}

	fwrite(&fileHead, sizeof(BITMAPFILEHEADER), 1, fop);
	fwrite(&infoHead, sizeof(BITMAPINFOHEADER), 1, fop);
	fwrite(pColorTable, sizeof(RGBQUAD), 255, fop);
	fwrite(pBmpBuf2, lineByte*height, 1, fop);
	fclose(fop);

	system("pause");
	return 0;
}

实验结果:

            原图                             效果图

          

实验结果分析:原图和效果图略微由区别。但效果图似乎和开运算相反了。

猜你喜欢

转载自blog.csdn.net/fengxianghui01/article/details/85239193