Detecting objects in a photograph with opencv part 2

Eyes being detected using
opencv

As I found out last time it is quite easy to detect objects in a photgraph. The difficult part is to create a classifier that will do this for the particular object you are looking for.

I am still working on building a simple object classifier and I will share how I have done this soon. In the mean time you may like to whet your appettite with some of the classifiers that ship as part of opencv.

You can find classifiers that can detect faces, eyes and whole bodies in opencvs source control. For the purpose of demonstration I will use the eye detector. I am also using ruby-opencv from this repository.

In your ruby file (eyes.rb for example) include opencv:

require "opencv"

Load the classifier into opencv:

classifier = 'haarcascade_eye.xml'
detector = OpenCV::CvHaarClassifierCascade::load(classifier)

Load the image you want to run the classifier against:

image = OpenCV::IplImage.load('sample_image.jpg')

We can now detect objects by:

detector.detect_objects(image) do |region|
  color = OpenCV::CvColor::Blue
  image.rectangle! region.top_left, region.bottom_right, :color => color
end

This will draw blue rectangles over around the eyes. We can then save that image:

image.save_image('eyes_detected.jpg')

The result? Yours truly with square blue glasses!