Skip to content

Instantly share code, notes, and snippets.

@masanoriyamaguchi
Last active August 29, 2015 14:22
Show Gist options
  • Save masanoriyamaguchi/7b48e3d9ff51d5d06ea5 to your computer and use it in GitHub Desktop.
Save masanoriyamaguchi/7b48e3d9ff51d5d06ea5 to your computer and use it in GitHub Desktop.
OpenCVで顔画像を抜き出す
import cv
import sys
storage = cv.CreateMemStorage()
# 読み込む画像を引数で指定する
img = cv.LoadImageM(sys.argv[1])
# haarcascade_frontalface_default.xmlへのパス
# haarcascade_frontalface_default.xmlはここからDLする
# https://opencvlibrary.svn.sourceforge.net/svnroot/opencvlibrary/tags/latest_tested_snapshot/opencv/data/haarcascades/
hc = cv.Load("/Path/to/haarcascade_frontalface_default.xml")
faces = cv.HaarDetectObjects(img, hc, storage, 1.1, 3, 0, (0, 0))
max=0
maxh=0
maxw=0
resx=0
resy=0
for (x, y, w, h), n in faces:
if max<w*h:
maxw=w
maxh=h
resx=x
resy=y
max=w*h
sub = cv.GetSubRect(img, (resx,resy,maxw,maxh))
# 顔を抽出した画像をface_引数で保存する
cv.SaveImage("face_" + sys.argv[1], sub)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment