sclass BWImage_FastRegions { BWImage image; int w, h, size, runner; new IntBuffer stack; // locations as y*w+x int[] regionMatrix; int regionCounter; bool verbose; int x(int pos) { ret pos % w; } int y(int pos) { ret pos / w; } int getColor(int pos) { ret image.getInt(x(pos), y(pos)); } run { w = image.getWidth(); h = image.getHeight(); size = w*h; while (runner < size) { if (regionMatrix[runner] == 0) { // make a new region, get color int region = ++regionCounter; stack.add(runner); int color = getColor(runner); // flood-fill region while (nempty(stack)) { int pos = stack.popLast(); if (regionMatrix[pos] != 0) continue; // touching myself (or someone else) if (getColor(pos) != color) continue; // wrong color // new pixel found, mark as ours regionMatrix[pos] = region; // explore neighborhood int x = x(pos), y = y(pos); if (x > 0) stack.add(pos-1); if (x < w) stack.add(pos+1); if (y > 0) stack.add(pos-w); if (y < h) stack.add(pos+w); } } ++runner; } } }