单色位图的联通性

1、问题描述

     读取一张单色位图,输出位图中有几个联通区域,每个联通区域的像素的个数。

如图像:

                   

 输出:

                12
                81
                52
               133

(输出顺序可能不一样)。

2、代码

/*++++++++++++++++++++++++++++++++
+	单色位图的联通性
+
+author:zhouyong			2013-5-1 14:56
++++++++++++++++++++++++++++++++++++++++*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *vis;
char *pho;
int width,height;
int dx[]={-1,-1,-1,0,0,1,1,1};
int dy[]={-1,0,1,-1,1,-1,0,1};

void bfs(int x,int y,int &count);
int main()
{
	FILE *fp;
	char tmp;
	int count;
	fp=fopen("in.bmp","rb");
	
	fseek(fp,18,SEEK_CUR);
	fread(&width,4,1,fp);//偏移18字节,长度4字节,位图宽度
	fread(&height,4,1,fp);//偏移22字节,长度4字节,位图高度
	printf("width:%d height:%d \n",width,height);
	fseek(fp,0x3e,SEEK_SET);//二值图像数据的偏移
	pho=(char *)malloc(sizeof(char)*width*height);//存储图像的每一个像素点
	vis=(char *)malloc(sizeof(char)*width*height);
	memset(vis,0,sizeof(char)*width*height);
	
	int i,j,k;
	for(i=height-1;i>=0;i--)
	{
		for(j=0;j<width/8;j++)
		{
			fread(&tmp,1,1,fp);
			for(k=0;k<8;k++)
			{
				if(tmp&(1<<(7-k)))
					pho[i*width+j*8+k]=1;
				else
					pho[i*width+j*8+k]=0;
			}
		}
	}
	
	for(i=0;i<height;i++)
	{
		for(j=0;j<width;j++)
		{
			if(!vis[i*width+j]&&pho[i*width+j]==0)
			{
				count=0;
				bfs(i,j,count);
				printf("%d \n",count);
			}
			
		}
		
	}
	fclose(fp);
	return 0;
}

void bfs(int x,int y,int &count)
{
	if(x>=0&&x<height&&y>=0&&y<width&&!vis[x*width+y]&&pho[x*width+y]==0)
	{
		vis[x*width+y]=1;
		count++;
		for(int i=0;i<8;i++)//向8个领域延伸,找出联通区域的个数。
			bfs(x+dx[i],y+dy[i],count);
	}
}


 

发布了35 篇原创文章 · 获赞 9 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/ZHOUYONGXYZ/article/details/8872990
今日推荐