尝试在不使用Matlab / Numpy / etc的情况下对2张图像执行2D互相关

时间:2018-04-28 00:18:06

标签: c# image-processing signal-processing fft cross-correlation

我正在尝试在C#中对这两个图像执行交叉关联:
ImageTemplate
Matlab说结果应该是这样的:Matlab result
但这是我的结果:My result

这是我的交叉关联功能:

public static Signal2D CrossCorrelation2D(Signal2D signal, Signal2D pulse) {
    return InverseFFT2D(FFT2D(signal) * FFT2D(pulse).GetConjugate());
}

这是我的FFT2D:

public static Signal2D FFT2D(Signal2D signal) {
    Signal2D result = new Signal2D(signal.Height, signal.Width);
    for (int i = 0; i < result.Height; i++)
        result[i] = new ComplexNumber[signal[i].Length];
    //rows
    for (int n = 0; n < signal.Height; n++) {
        result[n] = FFT(signal[n]);
    }
    //columns
    for (int i = 0; i < signal[0].Length; i++) {
        ComplexNumber[] col = new ComplexNumber[signal.Height];
        for (int j = 0; j < col.Length; j++) {
            col[j] = result[j][i];
        }
        col = FFT(col);
        for (int j = 0; j < col.Length; j++) {
            result[j][i] = col[j];
        }
    }
    return result;
}

这是我的FFT:

public static Signal FFT(Signal signal) {
    int N = signal.Length;
    if (N == 1)
        return signal;
    if ((N & (N - 1)) != 0)
        throw new ArgumentOutOfRangeException("signal length must be a power of 2");
    Signal evenArr = new Signal(N / 2);
    Signal oddArr = new Signal(N / 2);
    for (int i = 0; i < N / 2; i++) {
        evenArr[i] = signal[2 * i];
    }
    evenArr = FFT(evenArr);
    for (int i = 0; i < N / 2; i++) {
        oddArr[i] = signal[2 * i + 1];
    }
    oddArr = FFT(oddArr);
    Signal result = new Signal(N);
    for (int k = 0; k < N / 2; k++) {
        double w = -2.0 * k * Math.PI / N;
        ComplexNumber wk = new ComplexNumber(Math.Cos(w), Math.Sin(w));
        ComplexNumber even = evenArr[k];
        ComplexNumber odd = oddArr[k];
        result[k] = even + (wk * odd);
        result[k + N / 2] = even - (wk * odd);
    }
    return result;
}

这是我的信号乘法(使用逐点乘法):

public static Signal2D operator* (Signal2D a, Signal2D b) {
    if (a.Height != b.Height || a.Width != b.Width)
        throw new ArgumentException("Sizes must be equal");
    Signal2D result = new Signal2D(a.Height, a.Width);
    for (int y = 0; y < a.Height; y++) {
        for (int x = 0; x < a.Width; x++) {
            result[y][x] = a[y][x] * b[y][x];
        }
    }
    return result;
}

感谢任何帮助,谢谢。

编辑:我将matlab图像保留为1023的原始大小1023并覆盖了我的结果。看起来我可能已经在结果,我只是不确定Matlab如何填充图像。 Overlayed results(红色是我结果中的白色部分,灰色是我结果中的黑色部分。黑色/白色来自Matlab)

0 个答案:

没有答案