Skip to content

Instantly share code, notes, and snippets.

@tmaeda
Created December 25, 2010 17:49
Show Gist options
  • Save tmaeda/754967 to your computer and use it in GitHub Desktop.
Save tmaeda/754967 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# カレントディレクトリに存在するjpgsディレクトリ以下の全てのファイルに
# 顔認識を試行して、何らかの顔が検出できたファイルのみを
# detectedディレクトリ以下に保存します。
require 'opencv'
include OpenCV
# 顔検出に使うカスケードをロード
detector = CvHaarClassifierCascade::load('/usr/local/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml')
# jpgs以下の全てのファイル名を取って来て
Dir.glob("jpgs/*").each do |misawa|
detected = false
img = IplImage.load(misawa)
# 顔を検出して全てを四角で囲む
detector.detect_objects(img) { |rect|
img.rectangle!(rect.top_left, rect.bottom_right, :color => CvColor::Red)
puts "#{misawa}: #{rect.x} #{rect.y} #{rect.width} #{rect.height}"
detected = true
}
# 検出できたものだけを、detected以下に保存
if detected
img.save_image("detected/#{File.basename(misawa)}")
puts "saved to: detected/#{File.basename(misawa)}"
end
end
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
# カレントディレクトリに存在するmisawa.jpgというファイルを
# 読み込んで、顔認識をして赤い枠を描画し、
# カレントディレクトリのdetected.jpgというファイルに書き出します。
require 'opencv'
include OpenCV
# 顔検出に使うカスケードをロード
detector = CvHaarClassifierCascade::load('/usr/local/share/opencv/haarcascades/haarcascade_frontalface_alt2.xml')
# 画像をロード
img = IplImage.load("misawa.jpg")
# 顔を検出して四角で囲む
detector.detect_objects(img) { |rect|
img.rectangle!(rect.top_left, rect.bottom_right, :color => CvColor::Red)
}
# 画像をセーブ
img.save_image("detected.jpg")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment