Friday, March 4, 2016

Processing and OpenCV for Video Movement Detection

Hi everybody!

Find below a little experiment done with Processing and OpenCV for Processing to detect movement in a Camera-Video-Stream. I put together the Capture Sample from Processing and the Contour Sample from OpenCV for Processing (https://github.com/atduskgreg/opencv-processing/blob/master/examples/BackgroundSubtraction/BackgroundSubtraction.pde) to achieve this.

import gab.opencv.*;

import processing.video.*;

Capture cam;
OpenCV opencv;

int lastContourRefresh = millis();
int contourRefreshTreshold = 100000;

void setup() {
  size(1280, 720);

  opencv = new OpenCV(this,1280, 720);
  opencv.startBackgroundSubtraction(2,3,0.5);

  String[] cameras = Capture.list();
  
  if (cameras.length == 0) {
    println("There are no cameras available for capture.");
    exit();
  } else {
    println("Available cameras:");
    for (int i = 0; i < cameras.length; i++) {
      println(cameras[i]);
    }
    
    // The camera can be initialized directly using an 
    // element from the array returned by list():
    cam = new Capture(this, cameras[0]);
    println("chosen cam: " + cameras[0]);
    cam.start();     
  }      
}

void draw() {
  
  if(cam.available()) {
     cam.read();
  }
  
  image(cam, 0, 0);

    try {
         opencv.loadImage(cam);
    } catch (RuntimeException e ) {
      
    }
    opencv.updateBackground();
    opencv.dilate();
    opencv.erode();
    
    noFill();
    stroke(255, 0, 0);
    strokeWeight(3);
    
    for (Contour contour : opencv.findContours()) {
      contour.draw();
    }
    
    lastContourRefresh = millis();
}