Question

This is for the programing language Processing (2.0).

Say I wish to load a not square image (lets use a green circle for the example). If I load this on a black background you can visibly see the white square of the image(aka all parts of image that aren't the green circle). How would I go about efficiently removing them?

It can not think of an efficient way to do it, I will be doing it to hundreds of pictures about 25 times a second(since they will be moving).

Any help would be greatly appreciated, the more efficient the code the better.

Was it helpful?

Solution 2

Pixels are stored in the Pixels[] array, you can use a for loop to check to see if the value is 0 (aka white). If it is white load it as the black background.

OTHER TIPS

As @user3342987 said, you can loop through the image's pixels to see if each pixel is white or not. However, it's worth noting that 255 is white (not 0, which is black). You also shouldn't hardcode the replacement color, as they suggested -- what if the image is moving over a striped background? The best approach is to change all the white pixels into transparent pixels using the image's alpha channel. Also, since you mentioned you would be doing it "about 25 times a second", you shouldn't be doing these checks more than once-- it will be the same every time and would be wasteful. Instead, do it when the images are first loaded, something like this (untested):

PImage[] images;

void setup(){
  size(400,400);
  images = new PImage[10];
  for(int i = 0; i < images.length; i++){
    // example filenames
    PImage img = loadImage("img" + i + ".jpg");
    img.beginDraw();
    img.loadPixels();
    for(int p = 0; p < img.pixels.length; p++){
      //color(255,255,255) is white
      if(img.pixels[p] == color(255,255,255)){
        img.pixels[p] = color(0,0); // set it to transparent (first number is meaningless)
      }
    }
    img.updatePixels();
    img.endDraw();
    images[i] = img;
  }
}
void draw(){
  //draw the images as normal, the white pixels are now transparent
}

So, this will lead to no lag during draw() because you edited out the white pixels in setup(). Whatever you're drawing the images on top of will show through.

It's also worth mentioning that some image filetypes have an alpha channel built in (e.g., the PNG format), so you could also change the white pixels to transparent in some image editor and use those edited files for your sketch. Then your sketch wouldn't have to edit them every time it starts up.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top