Sketch checking if pixel is black or white crashes.

Hello, I´m trying to make a sketch that checks if pixels are black or white in order to find it´s geometrical center. I got the comparing done, however, I can compare only half of the image. Whenever I want to check the whole image the sketch crashes. I was wandering if you could tell me if there´s any bug in my code or if I´m missing anything.

This is the image I´m using right now. I tried changing it but the problem persists. 1

And this is the sketch I came up with:

PImage img;  

void setup() {
  size(500,500);

  img = loadImage("1.jpg");
  image(img,0,0);
  loadPixels();

  println(pixels.length);
  for(int a=0;a<pixels.length/5;a++){
    if(brightness(pixels[a])==255){
      println("white");
    }else if(brightness(pixels[a])==0){
      println("black");
    }
    //println(a);
    //println(brightness(pixels[a]));
  }
}

void draw() {

}

Thank you in advance.

Tagged:

Answers

  • Do not use println() nor print() inside a loop! [-X

  • Also, for performance reason, cache brightness(pixels[a]) in some variable rather than duplicating it. *-:)

  • Sorry for my ignorance, but I can´t grasp the performance reason. I don´t know much about coding or algorithm performance. Could you explain it a bit easier?

  • And thank you for your fast response. I removed the prints and it runs perfectly. =D>

  • edited May 2016

    ... but I can't grasp the performance reason.

    Extracting the brightness() of some color value isn't trivial. It demands a whole algorithm for it.
    Requesting it again for the same value more than once is a total waste of CPU power.
    See below what I mean by it. Notice the result of brightness() is cached in variable bright:

    loadPixels();
    
    final int len = pixels.length, threshold = 64;
    final boolean[] darks = new boolean[len];
    
    for (int i = 0; i < len; ++i) {
      float bright = brightness(pixels[i]); // cache
      darks[i] = bright > threshold;
    }
    
Sign In or Register to comment.