Matlab 의 gradient 함수와 del2 함수에 대한 분석 및 C 코드 변환은 GVF 의 Matlab 코드를 분석하는 과정에서 이루어졌다. GVF란 Gradient Vector Flow 의 약자로써, http://iacl.ece.jhu.edu/projects/gvf/ 에서 자세한 정보를 얻을 수 있다.

---------------------------------------------------------------------------------------

Matlab 에서 'help gradient' 라고 치면 다음과 같이 출력된다.

>> help gradient
GRADIENT Approximate gradient.
    [FX,FY] = GRADIENT(F) returns the numerical gradient of the
    matrix F. FX corresponds to dF/dx, the differences in the
    x (column) direction. FY corresponds to dF/dy, the differences
    in the y (row) direction. The spacing between points in each
    direction is assumed to be one. When F is a vector, DF = GRADIENT(F)
    is the 1-D gradient.
    (이하 생략)

뭐... 대충 읽어보면 입력 F를 받아서 그것의 x 방향, y 방향으로의 미분값을 각각 구하여 FX와 FY에 저장한다는 내용이다. 아래 Matlab 코드를 보자.


위의 코드를 C/C++ 로 변환하는 것은 쉽다. 위의 빨간색 글씨를 쓰는, 그런 코드 이해가 어려운 거시지 이해만 했다면 C 코드 쓰는 것이야 어려울 턱이 있나.. ^^;

코드는 다음과 같다. 대충 보고 이해하기를...

void Gradient(IEFloatImage& img, IEFloatImage& fx, IEFloatImage& fy)
{
        register int i, j;

        int w = img.GetWidth();
        int h = img.GetHeight();

        fx.CreateImage(w, h);
        fy.CreateImage(w, h);

        float** pimg = img.GetPixels2D();
        float** pfx  = fx.GetPixels2D();
        float** pfy  = fy.GetPixels2D();

        // x 방향 그래디언트 fx 계산
        for( j = 0 ; j < h ; j++ )
        {
                pfx[j][0]   = pimg[j][1]   - pimg[j][0];
                pfx[j][w-1] = pimg[j][w-1] - pimg[j][w-2];
        }

        for( j = 0 ; j < h   ; j++ )
        for( i = 1 ; i < w-1 ; i++ )
        {
                pfx[j][i] = (pimg[j][i+1] - pimg[j][i-1])/2.f;
        }

        // y 방향 그래디언트 fy 계산
        for( i = 0 ; i < w ; i++ )
        {
                pfy[0][i]   = pimg[1][i]   - pimg[0][i];
                pfy[h-1][i] = pimg[h-1][i] - pimg[h-2][i];
        }

        for( j = 1 ; j < h-1 ; j++ )
        for( i = 0 ; i < w   ; i++ )
        {
                pfy[j][i] = (pimg[j+1][i] - pimg[j-1][i])/2.f;
        }
}
Posted by kkokkal
: