2014年7月15日 星期二

Finding Peak and Valley with 1st Derivative



    
Looks like need some threshold to eliminate small noise bug as the right photo...

 
       ...
      //Randomize the sample as input
      int v = (int)random(-40, 40);
      a+=0.2; A = (int) (80 + sin(a) * (v+50)); //add sine wave
   
      stroke(100, 100, 100);
      line(lastXPos, lastA,   xPos, A); //draw gray samples------------------------------------

      //smooth it
      B = smooth(A, 0.9, B);    
   
      //get 1st derivative
      C = B - lastB;                   //  f''(x) =  f(x) - f(x-1);
      C = (C + lastC) >> 1;        // some easy smooth
         
      stroke(250, 100, 100);
      line(lastXPos, 100+lastB,   xPos, 100+B);          //draw smoothed samples-------------
      line(lastXPos+1, 100+lastB,   xPos+1, 100+B);

      stroke(100, 100, 250);
      line(lastXPos, 400+(lastC*8),   xPos, 400+(C*8));//draw 1st derivatives  --------------
      if ((C*lastC) <= 0) {
        //f'(x) changed; when (f'(x)>0, f'(x-1)<0) or (f'(x)<0, f'(x-1)>0) or f'(x)=0 or f'x(x-1)=0    
        if (lastC >0)  {//found valley, draw line------
           stroke(40,40, 60);
           line(xPos, 400, xPos, 200);
           }
        if (lastC <0)  {//found peak, draw line-------
           stroke(80,80, 120);
           line(xPos, 400, xPos, 150);
           }
        }
 
      lastA = A;           //store current value for next iteration
      lastB = B;
      lastC = C;
   
      lastXPos = xPos; //move forward
      ...
Change random samples into Perlin noise