Pixel Sorting

2.png
PImage img;

void setup() {
  size(915, 548);
  img = loadImage("Little_Chief_Mountain_GNP1.jpg");
  img.resize(915, 548);
}

void draw() {
  img.loadPixels();
  for (int x = 0; x < img.width; x+= img.width /300) {
    for (int y = 0; y < img.height; y+= img.height / 300) {
      int c = getPixel(img, x, y);
      if (getPixel(img, x-1, y) > c) {
        setPixel(img, x-1, y, c);
        c = getPixel(img, x-1, y);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x-1, y-1) > c){
        setPixel(img, x-1, y-1, c);
        c = getPixel(img, x-1, y-1);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x, y-1) > c){
        setPixel(img, x, y-1, c);
        c = getPixel(img, x, y-1);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x+1, y) > c){
        setPixel(img, x+1, y, c);
        c = getPixel(img, x+1, y);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x+1, y+1) > c){
        setPixel(img, x+1, y+1, c);
        c = getPixel(img, x+1, y+1);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x, y+1) > c){
        setPixel(img, x, y+1, c);
        c = getPixel(img, x, y+1);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x-1, y+1) > c){
        setPixel(img, x-1, y+1, c);
        c = getPixel(img, x-1, y+1);
        setPixel(img, x, y, c);
      }
      if (getPixel(img, x+1, y-1) > c){
        setPixel(img, x+1, y-1, c);
        c = getPixel(img, x+1, y-1);
        setPixel(img, x, y, c);
      }
    }
  }
  img.updatePixels();
  image(img, 0,0);
  noLoop();
}


public int getPixel(PImage img, int x, int y) {
   x = x < 0 ? 0 : x >= img.width ? img.width - 1 : x;
   y = y < 0 ? 0 : y >= img.height ? img.height - 1 : y;
  return img.pixels[x + y * img.width];
}

public void setPixel(PImage img, int x, int y, int c) {
   x = x < 0 ? 0 : x >= img.width ? img.width - 1 : x;
   y = y < 0 ? 0 : y >= img.height ? img.height - 1 : y;
  img.pixels[x + y * img.width] = c;
}