Dealing with editing large images

Hi all, I’m working on a little p5js app that will take an image and convert the brightness to opacity. So far, it works well but it crashes the browser when editing large images.
here’s the code: https://editor.p5js.org/tinywitchdraws/sketches/ulDocIRxg
Do you have any tips for solving this- ie, could I break the image into parts, run the code, and stitch it back together?
Or, could I download p5js and run the code locally, or would that still crash my browser?
Any advice that could help would be lovely.

2 Likes

First thing I noticed was that you called image.updatePixels() for every pixel - You can call it once when every pixel has been updated (out of the for loops). Also, using pixels array instead of using get() method might be faster (at least that’s what I remember from Processing).

https://p5js.org/reference/#/p5.Image/updatePixels

1 Like

Hey I saw ur code changed a couple of things, The problem was the get() function is much slower than the pexels[] array try this code I have tested it and it’s working for large Images
if u have any more confusion use link @ErraticGenerator shared

var worldImage;

function preload() {
  worldImage = loadImage("https://images-wixmp-ed30a86b8c4ca887773594c2.wixmp.com/f/4e795204-5695-4330-9f4f-7ea75454aebb/dcwpjst-fa6af0c1-9090-4ca2-87ad-ac95e3b4f7a4.png?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1cm46YXBwOiIsImlzcyI6InVybjphcHA6Iiwib2JqIjpbW3sicGF0aCI6IlwvZlwvNGU3OTUyMDQtNTY5NS00MzMwLTlmNGYtN2VhNzU0NTRhZWJiXC9kY3dwanN0LWZhNmFmMGMxLTkwOTAtNGNhMi04N2FkLWFjOTVlM2I0ZjdhNC5wbmcifV1dLCJhdWQiOlsidXJuOnNlcnZpY2U6ZmlsZS5kb3dubG9hZCJdfQ.kDZrwYXjTd6hWRxMOQwsBBGOrK15vhTsnqlf27a8G30");
}

function setup() {
  noLoop();
  createCanvas(worldImage.width, worldImage.height);
  background(0, 0, 0, 0);
  brightness_to_op(worldImage);
}

function draw() {
  loop();
  log_color();


}

function brightness_to_op(worldImage) {
  worldImage.loadPixels();
  for (var x = 0; x < 4 * (worldImage.width * worldImage.height); x += 4) {
    //get red,green, blue channels
    var r = worldImage.pixels[x + 0];
    var g = worldImage.pixels[x + 1];
    var b = worldImage.pixels[x + 2];
    var l = round(((0.3 * r) + (0.59 * g) + (0.11 * b)));
    //set red,green and blue
    worldImage.pixels[x + 0] = 0;
    worldImage.pixels[x + 1] = 0;
    worldImage.pixels[x + 2] = 0;
    worldImage.pixels[x + 3] = 255 - l;

  }

  worldImage.updatePixels();
  noSmooth();
  image(worldImage, 0, 0, width, height);
  noLoop();
}

function keyTyped() {
  if (key === 's') {
    worldImage.save('photo', 'png');
  }
}

function log_color() {
  console.log("at this point the alpha is", get(mouseX, mouseY));
}
1 Like

Thank you so much for the help! I really appreciate it, sorry for the late reply. The code runs like a charm now :slight_smile:

1 Like