Skip to content

Instantly share code, notes, and snippets.

@timpulver
Created September 25, 2012 12:58
Show Gist options
  • Save timpulver/3781643 to your computer and use it in GitHub Desktop.
Save timpulver/3781643 to your computer and use it in GitHub Desktop.
[Processing] Image Threshold [Image manipulation, effect]
class Threshold{
/**
* Returns a new PImage with threshold thresh in Grayscale.
* All coulours will be splitted according to their
* brightness between black and white.
*/
PImage threshold(PImage pi, int thresh){
if(pi==null || thresh < 0 || thresh > 255){ // invalid argument
println("threshold(): PImage == 0 or threshold value not in range [0..255]");
return null;
}
PImage pit = createImage(pi.width, pi.height, RGB);
pit.loadPixels();
pi.loadPixels();
for(int x=0; x<pi.width; x++){
for(int y=0; y<pi.height; y++){
int b = (int) brightness(pi.pixels[y*pi.width+x]);
if(b <= thresh){
pit.pixels[y*pit.width+x] = color(0);
}
else{
pit.pixels[y*pit.width+x] = color(255);
}
}
}
pit.updatePixels();
return pit;
}
}
PImage pi;
Threshold thresh;
void setup(){
pi = loadImage("SOME_IMAGE_HERE.jpg");
size(pi.width, pi.height);
noLoop();
thresh = new Threshold();
PImage pit = thresh.threshold(pi, 127);
if(pit != null){
image(pit, 0, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment