2

I'm trying to implement Hanning and Hamming window functions in C#. I can't find any .Net samples anywhere and I'm not sure if my attempts at converting from C++ samples does the job well.

My problem is mainly that looking at the formulas I imagine they need to have the original number somewhere on the right hand side of the equation - I just don't get it from looking at the formulas. (My math isn't that good yet obviously.)

What I have so far:


public Complex[] Hamming(Complex[] iwv)
{
    Complex[] owv = new Complex[iwv.Length];
    double omega = 2.0 * Math.PI / (iwv.Length);

    // owv[i].Re = real number (raw wave data)
    // owv[i].Im = imaginary number (0 since it hasn't gone through FFT yet)
    for (int i = 1; i < owv.Length; i++)
        // Translated from c++ sample I found somewhere
        owv[i].Re = (0.54 - 0.46 * Math.Cos(omega * (i))) * iwv[i].Re; 

    return owv;

}

public Complex[] Hanning(Complex[] iwv)
{
    Complex[] owv = new Complex[iwv.Length];
    double omega = 2.0 * Math.PI / (iwv.Length);

    for (int i = 1; i < owv.Length; i++)
        owv[i].Re = (0.5  + (1 - Math.Cos((2d * Math.PI ) / (i -1)))); // Uhm... wrong

    return owv;
}
Tedd Hansen
  • 12,074
  • 14
  • 61
  • 97
  • Check out your loops - it simple skip first element in array 'owv[0]'. It must be: for (int i = 0; i < owv.Length; i++) – Vladislav Apr 04 '14 at 15:12

3 Answers3

3

Here's an example of a Hamming window in use in an open source C# application I wrote a while back. It's being used in a pitch detector for an autotune effect.

Mark Heath
  • 48,273
  • 29
  • 137
  • 194
  • 1
    Thanks. I've posted my results in my blog: http://blog.tedd.no/2011/07/15/hanning-hamming-window-functions-in-c/ – Tedd Hansen Jul 15 '11 at 09:05
  • One quick performance improvement you can use is to pre-calculate the window coefficients for every value of n, since that usually doesn't change during the lifetime of an application, and calls to Math.Sin/Cos are relatively slow. – Mark Heath Jul 15 '11 at 15:45
2

You can use the Math.NET library.

    double[] hannDoubles = MathNet.Numerics.Window.Hamming(dataIn.Length);
    for (int i = 0; i < dataIn.Length; i++)
    {
        dataOut[i] = hannDoubles[i] * dataIn[i];
    }

See my answer to a similar question: https://stackoverflow.com/a/42939606/246758

Community
  • 1
  • 1
Gordon Slysz
  • 1,083
  • 12
  • 23
0

The operation of "windowing" means multiplying a signal by a window function. This code you found appears to generate the window function and scale the original signal. The equations are for just the window function itself, not the scaling.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720