get neighboring pixels from linear array (as in context.getImageData)

I have an image with a red filled-in circle in the middle. I want to read that image, analyze the pixels, and write it back to the canvas with just the outline of the circle. So I am checking to see if the pixel is surrounded by pixels with red channel value of 255. If yes, I make transparent. If no, I color the pixel cyan.

I used this post, as reference for writing the script.

I’m doing something wrong. Instead of outlining the circle in cyan, and making the center transparent, it is coloring all the white pixels cyan.

I’d really appreciate some help!

Image used: enter image description here

Code:

<img alt="input" height="170" id="input" src="img/input.png" width="170">
<canvas height="170" id="myCanvas" style="border:1px solid #d3d3d3;" width="170"></canvas>
let neighbors = []

  function isSurrounded(index, imageData, data) {
    neighbors = [] // clear array
    neighbors[0] = data[index - imageData.width * 4 - 4] // Upper left
    neighbors[1] = data[index - imageData.width * 4]     // Upper middle
    neighbors[2] = data[index - imageData.width * 4 + 4] // Upper right
    neighbors[3] = data[index - 4] // left
    neighbors[4] = data[index + 4] // right
    neighbors[5] = data[index + imageData.width * 4 - 4] // Lower left
    neighbors[6] = data[index + imageData.width * 4]     // lower middle
    neighbors[7] = data[index + imageData.width * 4 + 4] // Lower right

    // check red channel
    for (let i = 0; i < neighbors.length; i++) {
      let redPixel = neighbors[i]
      if (redPixel !== 255) {
        return false
      }
    }
    return true
  }

  let img = document.getElementById("input")
  img.onload = function () {
    let c = document.getElementById("myCanvas")
    let ctx = c.getContext("2d")
    ctx.drawImage(img, 0, 0)
    let imgData = ctx.getImageData(0, 0, c.width, c.height)
    let pxl = imgData.data
    for (let i = 0; i < pxl.length; i += 4) {
      if (isSurrounded(i, imgData, pxl)) {
        pxl[i] = 0
        pxl[i + 1] = 255
        pxl[i + 2] = 255
        pxl[i + 3] = 255
      } else {
        pxl[i + 3] = 0
      }
    }
    ctx.putImageData(imgData, 0, 0)
  }