# MFC最大连通域如何提取？

0

```int CMyDlg::scanline(int startX,int startY,int height, int width,int nWidth, BYTE *ScanImage)
{
BYTE *Mark;
Mark=ScanImage;
int x,y,cur_x, cur_y,state = 0;
int nHead=0, nTail=0,CurCount=0, MaxCount=0;
CPoint curArea[1000],maxArea[1000]={0},temp[1000],Queue[1000];
int QUEUECOUNT=height;
for (y=startY;y<height-startY;y++)
{
for (x=startX;x<width-startX;x++)
{
if((ScanImage[y*nWidth+x]==0)&& (Mark[y * nWidth + x] == 0))
{
//1.进队
Queue[nTail].x = x;
Queue[nTail++].y = y;
nTail = nTail % QUEUECOUNT;
Mark[y * nWidth + x] =1;
if (nTail == nHead)
{
return -1;
}
//2.出队
{
//2.1 记录坐标
curArea[CurCount].x= cur_x;
curArea[CurCount++].y= cur_y;
//2.2 增加个数
//left
if ((cur_x >= startX + 1) &&
(ScanImage[cur_y * nWidth + cur_x - 1] == 0)&& (Mark[cur_y * nWidth + cur_x - 1] == 0))
{
Queue[nTail].x= cur_x - 1;
Queue[nTail++].y= cur_y;
nTail = nTail % QUEUECOUNT;
Mark[cur_y * nWidth + cur_x - 1] = 1;
if (nTail == nHead)
{
return -1;
}
}
//right
if ((cur_x < startX + nWidth - 1)&&
(ScanImage[cur_y * nWidth + cur_x + 1] == 0)&& (Mark[cur_y * nWidth + cur_x + 1] == 0))
{
Queue[nTail].x = cur_x + 1;
Queue[nTail++].y = cur_y;
nTail = nTail % QUEUECOUNT;
Mark[cur_y * nWidth + cur_x + 1] = 1;
if (nTail == nHead)
{
return -1;
}
}
//bottom
if ((cur_y < startY + height - 1) &&
(ScanImage[(cur_y + 1)* nWidth + cur_x] ==0)&& (Mark[(cur_y + 1)* nWidth + cur_x] == 0))
{
Queue[nTail].x= cur_x;
Queue[nTail++].y = cur_y + 1;
nTail = nTail % QUEUECOUNT;
Mark[(cur_y + 1)* nWidth + cur_x] = 1;
if (nTail == nHead)
{
return -1;
}
}
// top
if ((cur_y >=startY + 1)&&
(ScanImage[(cur_y - 1)* nWidth + cur_x] ==0)&& (Mark[(cur_y - 1)* nWidth + cur_x] == 0))
{
Queue[nTail].x= cur_x;
Queue[nTail++].y= cur_y - 1;
nTail = nTail % QUEUECOUNT;
Mark[(cur_y - 1)* nWidth + cur_x] = 1;
if (nTail == nHead)
{
return -1;
}
}
}
//3. 判断当前最多
if (CurCount > MaxCount)
{
//交换数据
*temp = *maxArea;
*maxArea=*curArea;
*curArea=*temp;
MaxCount = CurCount;
CurCount = 0;
state = 1;
}
else
{
CurCount = 0;
}
}
}
}

if(state == 0)
{
return 2;
}
//4.找到最大区域，将所有点变成灰色
for (x = 0; x < MaxCount; x++)
{
ScanImage[maxArea[x].y * nWidth + maxArea[x].x] = 128;
}

}```

您需要登录以后才能回答，未注册用户请先注册