'peak_detection' by warren


Report abuse

Created on July 31, 2013 11:48 | Updated over 6 years ago

Link: https://gist.github.com/jywarren/6020668

Peak detection by Peter Davidowicz, additions by jywarren

setup: function() {
  // code to run on startup
  compare = function(dist,i,pixels) {
    if (dist <= 1) return true
    else return (compare(dist-1,i,pixels)) && pixels[i+dist]['average'] <= pixels[i]['average'] && pixels[i-dist]['average'] < pixels[i]['average']
  }

  detect_peaks = function(search_dist) {
    var peaks = []
    var peak_wavelengths = []
    var pixels = $W.spectrum.lines

    for (var i = search_dist; i < pixels.length-search_dist+1; i++) { //start a few pixels because we need to compare to neighboring pixels
      if (pixels[i]['average'] > pixels[i-1]['average']) {
        if (compare(search_dist,i,pixels)) { //This skips tiny valleys, more checks (increasing search_dist) skips larger valleys
          // Pixel is Peak Pixel, add it to peak pixel list
          peaks.push(pixels[i]) // here, adding the entire pixel object, including separate rgb and wavelength values
          peaks[peaks.length-1]['index'] = i // save the pixel index too
          peak_wavelengths.push(parseFloat(pixels[i]['wavelength'].toFixed(2))) // here, adding just the rounded wavelength
          $W.plot.highlight(0,i) // highlight the peak on the graph
        } 
      }
    }
    alert(peak_wavelengths.join(','))
    return peaks
  }
  detect_peaks(parseInt(prompt('Enter a peak width to limit your search to, in pixels:',5)/2))
 
},
draw: function() {
  // code to run every frame

}