How to iterate video.pixels.length for random area of image

Hello, not sure if I’m realy getting what you want, but maybe…

This sample code does 2 diff things:

  • draw a rect using nesteds for loops to access pixels[]
  • draw a rect using one for loop that traverse the whole pixels[] and change only what is needed.

I guess you are looking for the second. If you are going to traverse the whole pixels array you need to have a test to see if that particlar index of the array represents a pixel inside the wanted area.

Or you could adapt the other method pRect(), to return a collection with the indexes inside the area. then you could say (lets say it returned an array indxs[]).

// note not going trhough the whole pixels array
for(int i=0; i< indxs.length;i++){
  pixels[indxs[i]] = //blah;
}

But I think this makes not a lot of sense, anyway you would go trough 2 nesteds for loops (to buid indxs[]), so why not just do whatever you need to do at that time, so this seems useless, don’t now… anyways it’s here to help the comprehension of what’s involved.

here, have a look:

void setup() {
  size(400, 500);
}

void draw() {
  background(200);

  // draw a rect using pixels[] direct access
  // using a single for loop, the isIN() function gets:
  // index, xpos, ypos, rectWidt, rectHeight
  // returns if index represents a point inside rect area
  loadPixels();
  for (int i = 0; i < pixels.length; i++) {
    //define the rect here
    if (isIn(i, mouseX, mouseY, 300, 120))
      pixels[i] = color(220, 220, 0, 200);
  }
  updatePixels();


  //draw a rect using pixels[] direct access
  //with a nested for loop
  pRect(78, 94, 150, 84);
}


void pRect(int x, int y, int w, int h) {
  loadPixels();
  for (int i = x; i < w + x; i++) {
    for (int j = y; j < h + y; j++) {
      //you got address od each point inside the area
      int index = j*width+i;
      // limit to pixels inside screen
      if (index < pixels.length && i< width)
        pixels[index] = color(255, 0, 255);
    }
  }
  updatePixels();
}

boolean isIn(int ind, int x, int y, int w, int h) {
  int ix = ind%width;
  int iy = int(ind/width);
  return ix > x && ix < x+w && ix < width && iy > y && iy < y+h && iy < height;
}

This is the idea, you can easily adapt it for you r needs I think…

1 Like