Infinite loop error when trying to get pixels of an image

Hi there! This is part of a larger build where I need to store the coordinates of the black pixels in an image.

Here though, as a test I was first trying to simply change any pixel with an alpha of 255 to red.

The for loop is creating an infinite loop error. This doesn’t seem to happen in older versions (I’m using 2.3.4 right now) but it also doesn’t work either in older versions. My theory is that the image is just too big – I’m loading in an image at 4K resolution :confused:

It actually does start running before it hits the error as seen in the screenshot. I tried turning off loop protection and that just crashed the tab. Any help realllly appreciated as this is for an assignment due tomorrow.

Thanks!

let img;

async function setup() {
  createCanvas(windowWidth, windowHeight);

  img = await loadImage('silhouette.png');

  img.loadPixels();

  for (let i = 0; i < img.pixels.length; i += 4) {
    if (img.pixels[i + 3] > 1) {
      // Red.
      img.pixels[i] = 255;
    }
  }

  img.updatePixels();
}

function draw() {
  background(img);

}

If you are using the p5js web editor make sure you switch off infinite loop protection for the sketch in settings

Welcome to the forum :grinning_face:

Hi quark! Yes I did but it very quickly ended up crashing the tab

I have recreated your sketch in the p5ls web editor and it worked fine even without turning off loop protection. My silhouette image was 1135 x 773 pixels and used 45781 bytes, I don’t know how this compares with your original. You can find the sketch here.

JavaScript is a single threaded so when executing lengthy tasks some browsers will halt the script even though it is not an infinite loop. The solution is to create web-worker threads or use promises.