Sort PImage array by brightness

this is terrible but it works and might at least point you in the correct direction.

PImage [] source; // images to re-order
float  [] bScore; //array of brightness "scores" for the images 

void setup () {
  size(20,20);
  source = new PImage[9];
  bScore = new float [9];
  
  for(int i = 0; i < 9; i ++) {
    source[i] = loadImage(sketchPath("data/img"+i+".png") );
    
    bScore[i] = score(source[i]);
  }
  sortImagesByBrightness();
  for (int i = 0; i < bScore.length; i++) {
    source[i].save("data/simg" + i + ".png");
  }
}

void sortImagesByBrightness() {
  int numUnsorted = source.length;
  int max = 0;
  while(numUnsorted > 0) {
    max = 0;
    for(int i = 1; i < numUnsorted; i++) {
      if(bScore[max] < bScore[i]) max = i;
    }
    PImage temp1 = source[max];
    source[max] = source[numUnsorted - 1];
    source[numUnsorted - 1] = temp1;
    
    float temp2 = bScore[max];
    bScore[max] = bScore[numUnsorted - 1];
    bScore[numUnsorted - 1] = temp2;
    
    numUnsorted--;
  }
}

//function to calculate brightness for each image
float score(PImage source) {
  float avg = 0.0;
  source.loadPixels();
  
  for(int i = 0; i < source.pixels.length; i ++) {
    float b = brightness(source.pixels[i]);    
    avg += b;
  }
    avg /= source.pixels.length;  
    return avg; 
}

these are the images i used

img0 img1 img2 img3 img4 img5 img6 img7 img8

3 Likes