Skip to content

Instantly share code, notes, and snippets.

@jeffkreeftmeijer
Created March 27, 2011 17:59
Show Gist options
  • Save jeffkreeftmeijer/889416 to your computer and use it in GitHub Desktop.
Save jeffkreeftmeijer/889416 to your computer and use it in GitHub Desktop.
OpenCV MacRuby
framework 'AppKit'
class AppDelegate
def applicationDidFinishLaunching(notification)
opencv = OpenCV.new
opencv.setup
loop { opencv.trackFace; sleep 1 }
end
end
app = NSApplication.sharedApplication
app.delegate = AppDelegate.new
window = NSWindow.alloc.initWithContentRect([200, 300, 300, 100],
styleMask:NSTitledWindowMask|NSClosableWindowMask|NSMiniaturizableWindowMask,
backing:NSBackingStoreBuffered,
defer:false)
window.title = 'FaceTracker'
window.level = NSModalPanelWindowLevel
window.delegate = app.delegate
window.display
window.orderFrontRegardless
app.run
#import <Cocoa/Cocoa.h>
#import "opencv2/imgproc/imgproc_c.h"
#import "opencv2/highgui/highgui_c.h"
#import "opencv2/objdetect/objdetect.hpp"
@interface OpenCV : NSObject {
int scale;
CvCapture* camera;
CvHaarClassifierCascade* cascade;
CvMemStorage* storage;
IplImage * current_frame;
IplImage * gray_image;
IplImage * small_image;
}
@end
#import "OpenCV.h"
@implementation OpenCV
- (void) setup
{
scale = 4;
camera = cvCreateCameraCapture (CV_CAP_ANY);
cascade = (CvHaarClassifierCascade*) cvLoad ("/Users/jeff/Desktop/haar.xml", 0, 0, 0);
storage = cvCreateMemStorage(0);
current_frame = cvQueryFrame (camera);
gray_image = cvCreateImage(cvSize (current_frame->width, current_frame->height), IPL_DEPTH_8U, 1);
small_image = cvCreateImage(cvSize (current_frame->width / scale, current_frame->height / scale), IPL_DEPTH_8U, 1);
}
-(void) trackFace
{
current_frame = cvQueryFrame(camera);
cvCvtColor (current_frame, gray_image, CV_BGR2GRAY);
cvResize (gray_image, small_image, CV_INTER_LINEAR);
// cvHaarDetectObjects seems to kill the webcam stream somehow --the app runs
// and the webcam stays on without it--, without leaving any output in the
// log whatsoever. It simply turns off the green webcam light and warns the
// log that the webcam is gone:
//
// WARNING: Couldn't grab new frame from camera!!!
CvSeq* faces = cvHaarDetectObjects (small_image, cascade, storage,
1.1, 2, CV_HAAR_DO_CANNY_PRUNING,
cvSize (0, 0), cvSize (0, 0));
int i;
for (i = 0; i < (faces ? faces->total : 0); i++)
{
CvRect* r = (CvRect*) cvGetSeqElem (faces, i);
printf("r->x: %d\n", r->x);
printf("r->y: %d\n", r->y);
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment