I am experimenting with cv::dft: a 1HZ sinus signal is generated, and displayed in the frequency domain. But for some reason it hasn't got the maximum component at 1Hz. My code is the following:

       const int FRAME_RATE = 20;             //!< sampling rate in [Hz]
       const int WINDOW_SIZE = 256;         
       double len = double(WINDOW_SIZE)/double(FRAME_RATE);   // signal length in seconds
       double Fb = 1./len;                                     // frequency bin in Hz
       // Constructing frequency vector
       std::vector<double> f;
       double freq_step = 0;
       for (int i = 0; i < WINDOW_SIZE; ++i)
          freq_step += Fb;

   // Create time vector
   std::vector<double> t;
   double time_step = 0;
   for(int i = 0; i<WINDOW_SIZE; ++i)
       time_step += 1./double(FRAME_RATE);

   // Creating sin signal with 1Hz period
   std::vector<double> y;
   for(auto val : t)

   // Compute DFT
   cv::Mat fd;
   cv::dft(y, fd, cv::DFT_REAL_OUTPUT);
   fd = cv::abs(fd);

If I plot the signal in time and frequency domain: plot(t, y); plot(f, fd) the result is the following:

enter image description here

The time signal is good, but the frequency signal has maximum around 6HZ instead of 1HZ.

Where did I take the mistake?

  • $\begingroup$ thank you for the code sample! $\endgroup$ – stiv Jun 20 '19 at 0:54

Your sine wave should use 2pi instead of frame rate. Also, your frequency data should have window size/2 points and go from 0 to frame rate/2, not frame rate.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.