Search code examples
image-processingprocessing

How to make a grid with random images in each cell - Processing


I'm trying to build a grid where each cell is filled by a random image in Processing. I have more than 500 images named img_xxx.jpg in the data folder. So far, I've accomplished a grid where the image that is displayed is random, but it's the same image for every cell. Hopefully you can help me out! Thanks.

final static byte GRID = 6, NUM = GRID*GRID;
PImage img;
int rand;

void setup() {
  size(400, 400);
  noLoop();
  smooth();
  background(0);

  final PImage[] imgs = new PImage[NUM];
  final int tileW = width/GRID, tileH = height/GRID;
  rand = int(random(0,687)); 
  for (int idx=0; idx!=NUM; imgs[idx++] = loadImage("img_" + nf(rand,3)+ ".jpg"));

  for (int idx=0, row=0; row!=GRID; ++row)  for (int col=0; col!=GRID; 
      image(imgs[idx++], col++*tileW, row*tileH, tileW, tileH));

  img = get();
}

void draw() {
  background(img);
}

Solution

  • The extreme abstraction you've done in your for loops is fun to write, but a huge pain to read. You need to recalculate rand at every image, so write your first for loop like this:

    for (int idx=0; idx!=NUM; idx++) {
      rand = int(random(0, 687));
      imgs[idx] = loadImage("img_" + nf(rand, 3)+ ".jpg");
    }
    

    or, in your abstracted version:

    for (int idx=0; idx!=NUM; imgs[idx++] = loadImage("img_" + nf(int(random(0,687)),3)+ ".jpg"));
    

    (as a side note, I believe that nf() works on floats in newer versions of Processing, so you wouldn't need that int() command)

    You might run into issues with memory because the images might not all load in time before you save them with img = get();. One way to solve this is to build in waiting time between loading the images and displaying them.