Created
April 4, 2014 19:00
-
-
Save atduskgreg/9981064 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gab.opencv.*; | |
import processing.video.*; | |
import java.awt.Rectangle; | |
int minBlobArea = 500; | |
float smoothAmount = 0.8; // 1.0 is never move, 0.0 is don't smooth | |
OpenCV opencv; | |
Capture cam; | |
ArrayList<Contour> contours; | |
PVector previousPosition; | |
void setup() { | |
cam = new Capture(this, 640/2, 480/2); | |
size(cam.width, cam.height); | |
opencv = new OpenCV(this, cam.width, cam.height); | |
opencv.useGray(); | |
opencv.startBackgroundSubtraction(5, 3, 0.1); | |
cam.start(); | |
previousPosition = new PVector(); | |
} | |
void draw() { | |
image(cam, 0, 0); | |
opencv.loadImage(cam); | |
// update the background subtractor | |
opencv.updateBackground(); | |
// close holes by eroding and dilating. | |
opencv.erode(); | |
opencv.dilate(); | |
// find the average of the center of the contours | |
// whose area is bigger than the threshold | |
PVector currentPosition = new PVector(); | |
int numContours = 0; | |
contours = opencv.findContours(false, true); | |
for (Contour contour : contours) { | |
if(contour.area() > minBlobArea){ | |
Rectangle boundingBox = contour.getBoundingBox(); | |
currentPosition.x += (boundingBox.x + boundingBox.width/2); | |
currentPosition.y += (boundingBox.y + boundingBox.height/2); | |
numContours++; | |
noFill(); | |
strokeWeight(2); | |
stroke(0, 0, 255, 125); | |
rect(boundingBox.x, boundingBox.y, boundingBox.width, boundingBox.height); | |
noFill(); | |
stroke(0, 255, 0, 125); | |
contour.draw(); | |
} | |
} | |
// finish the average calculation | |
if(numContours > 0){ | |
currentPosition.x /= numContours; | |
currentPosition.y /= numContours; | |
} | |
// Smoothing: | |
// Calculate the vector between the previous and the new position | |
// move a fraction of the way from the previous position towards the new one | |
PVector motionDirection = PVector.sub(currentPosition, previousPosition); | |
motionDirection.mult(smoothAmount); | |
currentPosition.sub(motionDirection); | |
println("movementAmt: " + motionDirection.mag()); | |
println("target position: x: " + currentPosition.x + " y: " + currentPosition.y); | |
fill(255,0,0); | |
ellipse(currentPosition.x,currentPosition.y, 20,20); | |
previousPosition = new PVector(currentPosition.x,currentPosition.y); | |
} | |
void captureEvent(Capture c) { | |
c.read(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment