Search code examples
processingwebcam

Storing in a variable frame from webcam in Processing


I've tried a lot of time to store in a variable a frame from the webcam, but it doesn't work. The goal is to compare two consecutive frames from the video, so I need to store two frames in two variables, but storing one is already harder that what I thought.. Here's the code that corresponds to this problem:

import processing.video.*;

Capture video;
PImage image1;

void setup() {
  size(1280, 960);
  println("Caméras disponibles : ");
  printArray(Capture.list());
  video = new Capture(this, Capture.list()[75]);
  video.start();
}

void draw() {
  if (video.available() == true) {
    video.read();
    image1 = video;
  }

  image(image1, 0, 0);
}

It works fine when I write image(video, 0, 0); but as soon as I try to replace it by the variable image1, it doesn't print anything. Hence, the problem is the third line...

Would anyone have an idea of what is going on?

Thanks in advance!


Solution

  • You only set image1 to a value if your if statement evaluates to true:

      if (video.available() == true) {
        video.read();
        image1 = video;
      }
    
      image(image1, 0, 0);
    

    So what happens if video.isAvailable() is false? You won't set image1 equal to anything, so it retains its original value. Since it's original value is unset, it's the null value. Passing null into the image() function apparently doesn't draw anything.

    To fix your problem, you need to refactor your code to only draw image1 if it has a value. It could be as simple as this:

      if (video.available() == true) {
        video.read();
        image1 = video;
        image(image1, 0, 0);
      }
    

    This is just a guess, and what you do depends on how you want your code to behave.

    But one thing to note is that Capture is a special instance of PImage, so I'm not sure that what you're trying to do will work. Capture instances modify their internal state so that drawing the same Capture over time will draw different frames. So if you set two PImage variables equal to the same Capture, those two variables will continue to update along with the video. They'll always store the most recent frame.

    To fix that, you'll probably want to copy the current pixels from the Capture to each PImage variable.