sobel filter in javascript

To apply a Sobel filter for edge detection in JavaScript, we need to perform convolution operations using the Sobel kernels.

Here's an example implementation of a Sobel filter in JavaScript:

index.tsx
function sobelFilter(imageData) {
  const { data, width, height } = imageData;
  const outputData = new ImageData(width, height);
  const kernelX = [-1, 0, 1, -2, 0, 2, -1, 0, 1];
  const kernelY = [-1, -2, -1, 0, 0, 0, 1, 2, 1];

  function getPixel(x, y) {
    const index = (y * width + x) * 4;
    const r = data[index];
    const g = data[index + 1];
    const b = data[index + 2];
    const a = data[index + 3];
    return [r, g, b, a];
  }

  function applyKernel(x, y, kernel) {
    let sum = [0, 0, 0];
    for (let j = -1; j <= 1; j++) {
      for (let i = -1; i <= 1; i++) {
        const pixel = getPixel(x + i, y + j);
        const weight = kernel[(j + 1) * 3 + i + 1];
        sum[0] += pixel[0] * weight;
        sum[1] += pixel[1] * weight;
        sum[2] += pixel[2] * weight;
      }
    }
    return sum;
  }

  for (let y = 0; y < height; y++) {
    for (let x = 0; x < width; x++) {
      const pixelX = applyKernel(x, y, kernelX);
      const pixelY = applyKernel(x, y, kernelY);
      const magnitude = Math.sqrt(
        Math.pow(pixelX[0], 2) + Math.pow(pixelY[0], 2) +
        Math.pow(pixelX[1], 2) + Math.pow(pixelY[1], 2) +
        Math.pow(pixelX[2], 2) + Math.pow(pixelY[2], 2)
      );
      const index = (y * width + x) * 4;
      outputData.data[index] = magnitude;
      outputData.data[index + 1] = magnitude;
      outputData.data[index + 2] = magnitude;
      outputData.data[index + 3] = 255;
    }
  }

  return outputData;
}
1468 chars
49 lines

This implementation takes an ImageData object as input and returns a new ImageData object with the Sobel filter applied. The two kernel arrays kernelX and kernelY represent the horizontal and vertical Sobel kernels, respectively. The applyKernel function performs the convolution operations using the given kernel and pixel coordinates. Finally, the magnitude of the gradient is calculated and set as the new pixel values in the output image.

gistlibby LogSnag