Image edge detection with JavaScript (no dependencies)

The source code below is an example implementation of image edge detection using 3×3 gradient operators and pure Java Script.

The code is written in pure JavaScript with no additional dependencies.

The algorithm is applicable to operators for contour detection such as: Sobel, Prewitt, Shaar and others.

Source Code



/**
* @param data - input pixels data
* @param idx - the index of the central pixel
* @param w - image width (width*4 in case of RGBA)
* @param m - the gradient mask (for Sobel=[1, 2, 1])
*/
function conv3x(data, idx, w, m){
  return (m[0]*data[idx - w - 4] + m[1]*data[idx - 4] + m[2]*data[idx + w - 4]
      -m[0]*data[idx - w + 4] - m[1]*data[idx + 4] - m[2]*data[idx + 4 + 4]);
}

function conv3y(data, idx, w, m){
  return (m[0]*data[idx - w - 4] + m[1]*data[idx - w] + m[2]*data[idx - w + 4]
      -(m[0]*data[idx + w - 4] + m[1]*data[idx + w] + m[2]*data[idx + w + 4]));
}


/**
* @param pixels - Object of image parameters
* @param mask - gradient operator e.g. Prewitt, Sobel, Scharr, etc. 
*/
function gradient_internal(pixels, mask)
{
  var data = pixels.data;
  var w = pixels.width*4;
  var l = data.length - w - 4;
  var buff = new data.constructor(new ArrayBuffer(data.length));
  
  for (var i = w + 4; i < l; i+=4){
    var dx = conv3x(data, i, w, mask);
    var dy = conv3y(data, i, w, mask);
    buff[i] = buff[i + 1] = buff[i + 2] = Math.sqrt(dx*dx + dy*dy);
    buff[i + 3] = 255;
  }
  pixels.data.set(buff);
}

/**
* @param canvas - HTML5 Canvas elementFromPoint
*/
function gradient(canvas){
  var context = canvas.getContext('2d');
  var pixels = context.getImageData(0, 0, canvas.width,canvas.height);
  gradient_internal(pixels, [1, 2, 1]); // Apply Sobel operator
  context.putImageData(pixels, 0, 0);
}

Description

  • Initially we should load an input image inside a HTML5 Canvas element.
  • As a next step we select the desirable kernel for contour detection (e.g. [1, 2, 1] for Sobel)
  • The gradient_internal() makes a 3×3 convolution to extract the edges of the image
  • Finally we put back the resulting grayscale image back to the Canvas element.

Some of the most popular masks are:


Related Algorithms


Online Demo