Skip to content

Instantly share code, notes, and snippets.

@bhelx
Last active December 30, 2015 21:09
Show Gist options
  • Save bhelx/7885500 to your computer and use it in GitHub Desktop.
Save bhelx/7885500 to your computer and use it in GitHub Desktop.
recursively walk directory and extract faces
require "opencv"
require "fileutils"
include OpenCV
detector = CvHaarClassifierCascade::load("./haarcascade_frontalface_alt.xml")
input_dir = ARGV[0]
output_dir = ARGV[1] || 'output'
FileUtils.mkdir_p(output_dir)
Dir.glob(File.join(input_dir, "**/*")).each_with_index do |image_file, index|
next unless /\.jpg|\.jpeg|\.png|\.pgm/.match File.extname(image_file)
image = IplImage.load(image_file, CV_LOAD_IMAGE_GRAYSCALE)
detector.detect_objects(image).each do |rect|
output_image = image.sub_rect(rect)
path = File.join(output_dir, "#{index}_#{File.basename(image_file)}")
output_image.save_image(path)
puts "Saved face to: #{path}"
image.reset_roi
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment