2 guihuacaizi GuiHuaCaiZi 于 2017.09.16 15:04 提问

将canny算法中边缘跟踪函数由递归转化为循环函数,可能改过之后效果没有原函数好,请各位大侠赐教。

原递归函数:

 void TraceEdge(int y, int x, int nThrLow, LPBYTE pResult, int *pMag, SIZE sz)
{
    //对8邻域像素进行查询
    static const int xNum[8] = { 1,1,0,-1,-1,-1,0,1 };
    static const int yNum[8] = { 0,1,1,1,0,-1,-1,-1 };
    LONG yy, xx, k;
    for (k = 0; k<8; k++)
    {
        yy = y + yNum[k];
        xx = x + xNum[k];
        if (pResult[yy*sz.cx + xx] == 128 && pMag[yy*sz.cx + xx] >= nThrLow)
        {
            //该点设为边界点
            pResult[yy*sz.cx + xx] = 255;
            //以该点为中心再进行跟踪
            TraceEdge(yy, xx, nThrLow, pResult, pMag, sz);
        }
    }
}

修改之后的循环函数为:

static const int xNum[8] = { 1,1,0,-1,-1,-1,0,1 };
static const int yNum[8] = { 0,1,1,1,0,-1,-1,-1 };
struct record
{
int a, b;
int state, pre;
record(int a=0,int b=0,/*int yy=0, int xx=0,*/int state=0,int pre=0):a(a),b(b),state(state),pre(pre){}
};

void TraceEdge(int y, int x, int nThrLow, LPBYTE pResult, int *pMag, SIZE sz)
{
int k;
LONG yy, xx;
stack s;
record cur(y,x, 0, 0),now;
while (1)
{
k = 0;
cur.a = y;
cur.b = x;
yy = cur.a + yNum[k];
xx = cur.b + xNum[k];

    if (cur.state < 8)
    {
        for (k = cur.state + 1; k < 8; k++)
        {
            if (pResult[yy*sz.cx + xx] == 128 && pMag[yy*sz.cx + xx] >= nThrLow)
                break;
        }
        if (k < 8)
        {
            now = cur;
            now.state = k;
            now.pre = cur.state;
            yy = cur.a + yNum[k - 1];
            xx = cur.b + xNum[k - 1];
            pResult[yy*sz.cx + xx] = 255;
            s.push(now);
            y = yy;
            x = xx;
            cur.pre = 0;
            for (k = 0; k < 8; k++)
            {
                if (pResult[yy*sz.cx + xx] == 128 && pMag[yy*sz.cx + xx] >= nThrLow)
                    break;
            }
            cur.state = k;
        }
        else
        {
            now = cur;
            now.state = 8;
            now.pre = cur.state;
            yy = y + yNum[cur.state];
            xx = x + xNum[cur.state];
            pResult[yy*sz.cx + xx] = 255;
            s.push(now);
            y = yy;
            x = xx;
            cur.pre = 0;
            for (k = 0; k < 8; k++)
            {
                if (pResult[yy*sz.cx + xx] == 128 && pMag[yy*sz.cx + xx] >= nThrLow)
                    break;
            }
            cur.state = k;
        }
    }
    else
    {
        if (s.empty())
            break;
        cur = s.top();
        s.pop();
    }
}

}


``


Csdn user default icon
上传中...
上传图片
插入图片