Discrete Fourier transform implementation gives better result than OpenCV DFT

We implemented DFT and wanted to test it with OpenCV. The results are different.

  • our DFT results are in order from smallest to largest, whereas OpenCV results are not in any order.
  • the first (0th) value is the same for both calculations, since in this case the complex part is 0 (since e ^ 0 = 1, in the formula). Other values ​​are different, for example, OpenCV results contain negative values, while ours do not.

This is our DFT implementation:

// complex number
std::complex<float> j;
j = -1;
j = std::sqrt(j);
std::complex<float> result;
std::vector<std::complex<float>> fourier; // output

// this->N = length of contour, 512 in our case
// foreach fourier descriptor
for (int n = 0; n < this->N; ++n)
{
    // Summation in formula
    for (int t = 0; t < this->N; ++t)
    {
        result += (this->centroidDistance[t] * std::exp((-j*PI2 *((float)n)*((float)t)) / ((float)N)));
    }

    fourier.push_back((1.0f / this->N) * result);
}

      

and this is how we calculate the DFT with OpenCV:

std::vector<std::complex<float>> fourierCV; // output
cv::dft(std::vector<float>(centroidDistance, centroidDistance + this->N), fourierCV, cv::DFT_SCALE | cv::DFT_COMPLEX_OUTPUT);

      

The centroidDistance variable is calculated in the previous step.

Note: please avoid answers that say use OpenCV instead of your own implementation.

+3


source to share


1 answer


You forgot to initialize result

for each iteration n

:



for (int n = 0; n < this->N; ++n)
{
    result = 0.0f;    // initialise `result` to 0 here <<<

    // Summation in formula
    for (int t = 0; t < this->N; ++t)
    {
        result += (this->centroidDistance[t] * std::exp((-j*PI2 *((float)n)*((float)t)) / ((float)N)));
    }

    fourier.push_back((1.0f / this->N) * result);
}

      

+4


source







All Articles