Flickering of graphics drawn over video

edited February 2017 in Library Questions

I'm having trouble with some code that I've patched together. I've managed to get this to mostly work, but when it runs the toplayer graphics over the video flicker, I think while the video updates. Is there a way to keep this from happening?

code below:

import ipcapture.*;

IPCapture cam1;

// Circular buffer
PImage[] cam1_buffer; 

// These determine the size of the circular buffer and help iterate while writing and reading through them
int nFrames = 1;
int iWrite = 0, iRead = 1;

// Track color var
color trackColor;

//top layer drawing thing
PGraphics topLayer;

void setup() {

  size(704, 480);

  cam1 = new IPCapture(this, "http://" + "155.41.145.37/mjpg/video.mjpg", "", "");
  cam1.start();
  // If the camera resolution isn't explicitely defined the PImage.get() method will give strange results
  cam1.pixelWidth = 704;
  cam1.pixelHeight = 480;

  cam1_buffer = new PImage[nFrames];

  //Track color vars
  colorMode(RGB,255,255,255,100);
  trackColor = color(255,0,64);
  noFill();
  smooth();
  strokeWeight(4.0);
  stroke(0);

  //create a top layer for circles
  topLayer = createGraphics(width, height, g.getClass().getName());

}

void draw() {
  if (cam1.isAvailable()) {
    cam1.read();
    cam1_buffer[iWrite] = cam1.get();
  if(cam1_buffer[0] != null){
  // The original camera image is displayed correctly at 480x300 in the upper left corner          
  image(cam1,0,0);
  }
}

  //Track colors below
  loadPixels();


  //Color tracking vars
  float closestDiff = 500.0f;
  int closestX = 0;
  int closestY = 0;

  //Loop through every pixel
  for (int x = 0; x < cam1.pixelWidth; x++){
    for (int y = 0; y < cam1.pixelHeight; y++){
      int loc = x + y*cam1.pixelWidth;

      //what is current color
      color currentColor = cam1.pixels[loc];
      float r1 = red(currentColor);
      float g1 = green(currentColor);
      float b1 = blue(currentColor);
      float r2 = red(trackColor);
      float g2 = green(trackColor);
      float b2 = blue(trackColor);

      //Using euclidean distance to compare colors
      float d = dist(r1,g1,b1,r2,g2,b2);

      //If current color is more similar to tracked color than
      //closest color, save current location and current difference
      if (d < closestDiff) {
        closestDiff = d;
        closestX = x;
        closestY = y;
      }
    }
  }

  //create a threshold
  //then create a circle at the tracked color

  if (closestDiff < 100) {
    topLayer.beginDraw();
    topLayer.noFill();
    topLayer.strokeWeight(4.0);
    topLayer.stroke(trackColor);
    topLayer.ellipse(closestX, closestY, 50, 50);
    topLayer.endDraw();
    image(topLayer, 0, 0);

  } 
}
Sign In or Register to comment.