I was wondering if anyone can help me with my code. So I am using my camera on my macbook pro. In processing, the tracking software works almost perfectly, I am using opencv. Then through serial the coordinates of my face are supposed to be translated to servo commands and sent to the arduino. I am getting movement with the servo, but it is only jitters. Any help is well appreciated.
Processing Code:
import hypermedia.video.*;
import java.awt.Rectangle;
import processing.serial.*;
int gx = 15;
int gy = 35;
int spos=90;
Serial port;
OpenCV opencv;
// contrast/brightness values
int contrast_value = 0;
int brightness_value = 0;
void setup() {
size( 320, 240 );
opencv = new OpenCV( this );
opencv.capture( width, height ); // open video stream
opencv.cascade( OpenCV.CASCADE_FRONTALFACE_ALT ); // load detection description, here-> front face detection : "haarcascade_frontalface_alt.xml"
// print usage
println( "Drag mouse on X-axis inside this sketch window to change contrast" );
println( "Drag mouse on Y-axis inside this sketch window to change brightness" );
println(Serial.list());
port = new Serial(this, Serial.list()[1], 9600);
}
public void stop() {
opencv.stop();
super.stop();
}
void draw() {
// grab a new frame
// and convert to gray
opencv.read();
opencv.convert( RGB );
opencv.contrast( contrast_value );
opencv.brightness( brightness_value );
// proceed detection
Rectangle[] faces = opencv.detect( 1.2, 2, OpenCV.HAAR_DO_CANNY_PRUNING, 40, 40 );
// display the image
image( opencv.image(), 0, 0 );
// draw face area(s)
noFill();
stroke(255,1,1);
for( int i=0; i<faces.length; i++ ) {
rect( faces[i].x, faces[i].y, faces[i].width, faces[i].height );
}
for( int i=0; i<faces.length; i++ ) {
update( faces[i].x);
}
}
/**
* Changes contrast/brigthness values
*/
void mouseDragged() {
contrast_value = (int) map( mouseX, 0, width, -128, 128 );
brightness_value = (int) map( mouseY, 0, width, -128, 128 );
}
void update(int x)
{
//Calculate servo postion from mouseX
spos= x/30;
//Output the servo position ( from 0 to 180)
port.write(spos + "a");
gx = x/80;
gy = 100-x/120;
}
Arduino Code:
#include <Servo.h>
Servo neck;
int xPos=0;
int yPos = 0;
void setup() {
Serial.begin(9600);
neck.attach(9);
}
void loop() {
if(Serial.available() >0) {
xPos=Serial.read();
yPos=Serial.read();
}
int xServo = map(xPos, 0, 320, 20, 70);
int yServo = map(yPos, 0, 240, 20, 70);
neck.write(xServo);
Serial.println("testing....");
}