Created
March 17, 2010 02:21
-
-
Save lian/334812 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
# stripped cvHaarDetectObjects version of ffi-opencv | |
# % pacman -S opencv (tested/updated for 2.3.1) | |
# % ruby ffi-facedetect.rb some.png | |
require 'ffi' | |
module OpenCv | |
extend FFI::Library | |
ffi_lib 'opencv_objdetect' | |
attach_function :cvGetErrStatus, [], :int | |
attach_function :cvLoadImage, [:string, :int], :pointer | |
attach_function :cvSaveImage, [:string, :pointer], :int | |
attach_function :cvLoad, [:string, :int, :int, :int], :pointer | |
CV_MAGIC_MASK = 0xFFFF0000 | |
CV_HAAR_MAGIC_VAL = 0x42500000 | |
CV_TYPE_NAME_HAAR = "opencv-haar-classifier" | |
CV_HAAR_DO_CANNY_PRUNING = 1 | |
def self.is_haar_classifier(haar_ptr) | |
if haar_ptr.respond_to?(:address) && haar_ptr.address != 0 | |
haar_ptr.get_int(0) & CV_MAGIC_MASK == CV_HAAR_MAGIC_VAL | |
end | |
end | |
attach_function :cvCreateMemStorage, [:int], :pointer | |
attach_function :cvClearMemStorage, [:pointer], :int | |
attach_function :cvReleaseMemStorage, [:pointer], :int | |
attach_function :cvHaarDetectObjects, [:pointer, :pointer, :pointer, :double, :int, :int, :int, :int], :pointer | |
attach_function :cvGetSeqElem, [:pointer, :int], :pointer | |
HaarTreeDefault = "/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml" | |
end | |
filename = ARGV.last | |
exit 1 unless File.exists? filename | |
iplimage = OpenCv.cvLoadImage(filename, 1) | |
if OpenCv.cvGetErrStatus != 0 | |
p 'ERROR loading file; no valid haar classifier'; exit 1 | |
end | |
cascade = OpenCv.cvLoad(OpenCv::HaarTreeDefault, 0, 0, 0) | |
unless OpenCv.is_haar_classifier(cascade) | |
p 'ERROR loading file; no valid haar classifier'; exit 1 | |
end | |
storage = OpenCv.cvCreateMemStorage(0); OpenCv.cvClearMemStorage(storage) | |
scale_haar = 1.2 | |
faces = OpenCv.cvHaarDetectObjects(iplimage, cascade, storage, scale_haar, 2, OpenCv::CV_HAAR_DO_CANNY_PRUNING, 5, 5) | |
#OpenCv.cvGetErrStatus | |
x86_64 = FFI.type_size(:pointer) == 8 | |
if (found_count = faces.get_uint( x86_64 ? 40 : 24 )) != 0 | |
rects = 0.upto(found_count-1).map do |idx| | |
OpenCv.cvGetSeqElem(faces, idx).get_array_of_int(0, 4) | |
end | |
puts "found %i faces:\n%s" % [found_count, rects.inspect] | |
rects | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment