种子填充算法

来源:互联网 发布:seo蜘蛛精有没有用 编辑:程序博客网 时间:2024/03/28 21:36

1、递归填充

    考虑四连通区域,坐标系x轴朝右为正,y轴朝下为正

 

void Fill4(CPoint point, int nOldColor, int nNewColor)
{
    
if(GetPixel(point) == nOldColor)
    
{
        
//填充左边的点 
        CPoint ptLeft = point;
        ptLeft.x 
= point.x - 1;
        
if(GetPixel(ptLeft) == nOldColor)
        
{
            Fill4(ptLeft, nOldColor, nNewColor);
        }

        
//填充右边的点
        CPoint ptRight = point;
        ptRight.x 
= point.x + 1;
        
if(GetPixel(ptRight) == nOldColor)
        
{
            Fill4(ptRight, nOldColor, nNewColor);
        }

        
//填充下边的点
        CPoint ptBottom = point;
        ptBottom.y 
= point.y + 1;
        
if(GetPixel(ptBottom) == nOldColor)
        
{
            Fill4(ptBottom, nOldColor, nNewColor);
        }

        
//填充右边的点
        CPoint ptTop = point;
        ptTop.y 
= point.y - 1;
        
if(GetPixel(ptTop) == nOldColor)
        
{
            Fill4(ptTop, nOldColor, nNewColor);
        }

    }

}

 递归算法效率比较低,当点的数量比较大的时候就能看出来速度慢了,在VC环境下默认的栈大小是1M,在project->setting->link的output中可以修改栈的大小,/statck:size

2、非递归算法

    原理是一样的,种子象素先入栈,然后找上下左右,如此循环,但效率就高多了,本来我用的是CArray来保存这些点,但点的数量有百万的时候CArray的处理速度也跟不上了,这里我开辟了一块足够大的空间,然后在这块内存里操作,速度就快多了,但是会造成空间浪费,但用完之后就删掉了

 

void Fill4(CPoint point, int nOldColor, int nNewColor)
{
    CPoint
* pPoint = new CPoint[ENOUGHSIZE];
    memset(pPoint, 
0sizeof(CPoint) * ENOUGHSIZE);
    
//种子象素入栈
    int nNum  = 0;
    pPoint[nNum
++= point;
    
int i = 0;
    
while(i <= nNum)
    
{
        
//部分省略
        
//填充左边的点
        if(GetPixel(ptLeft) == nOldColor)
        
{
            SetPixel(ptLeft, nNewColor);
            pPoint[nNum
++= ptLeft;
        }

        
//填充右边的点
        ......
        
//填充上边的点
        ......
        
//填充下边的点
        ......
        i
++;
    }

    
if(pPoint != NULL)
    
{
        delete[] pPoint;
        pPoint 
= NULL;
    }

}

扫描线填充算法的效率比较高,但是对于任意图形,还不知道怎么个写法,望知道的朋友赐教,先谢谢了

原创粉丝点击