summaryrefslogtreecommitdiff
path: root/Year_2/IandM/median/median.pde
blob: a6fbbac8178f217637e2720c9cca002a42d24958 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
int k = 1;

void setup() {
  size(512, 256);
}

void draw() {
  PImage img = loadImage("lena.png");
  img.resize(256, 256);
  img.filter(GRAY);

  image(img, 0, 0);
  image(median(img, k), 256, 0);
}

void keyPressed() {
  if (key == '+') {
    k++;
  } else if (key == '-') {
    k--;
  }
}

PImage median(PImage I, int n) {
  PImage out = createImage(I.width, I.height, RGB);

  int off = n/2;

  for (int x = 0; x < I.width; ++x) {
    for (int y = 0; y < I.height; ++y) {
      PImage t = I.get(x-off, y-off, n, n);
      float[] tarr = new float[n*n];
      t.loadPixels();

      for (int i = 0; i < t.pixels.length; ++i) {
        tarr[i] = red(t.pixels[i]);
      }

      tarr = sort(tarr);
      float med = tarr[(n*n)/2];
      if ((n*n)%2 == 0) {
        med = (med+tarr[(n*n)/2-1])/2;
      }

      out.set(x, y, color(med));
    }
  }

  return out;
}