Skip to content

Instantly share code, notes, and snippets.

@akameco
Created November 1, 2016 18:29
Show Gist options
  • Save akameco/32315f6a5b9f800c8282aeb2a9f2cdba to your computer and use it in GitHub Desktop.
Save akameco/32315f6a5b9f800c8282aeb2a9f2cdba to your computer and use it in GitHub Desktop.
import cv2
import sys
import os.path
def detect(filename, cascade_file="./lbpcascade_animeface.xml"):
# ファイルがなければエラー
if not os.path.isfile(cascade_file):
raise RuntimeError("{}: not found".format(cascade_file))
# カスケードのロード
cascade = cv2.CascadeClassifier(cascade_file)
# 画像の読み込み
image = cv2.imread(filename)
# グレースケール
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# ヒストグラムの平坦化
# ヒストグラム: 画像の明るさを表すもの
# 平坦化を行うと濃度にムラがなくなりメリハリのある画像になる
gra = cv2.equalizeHist(gray)
# [物体検出 — opencv v2.1 documentation](http://opencv.jp/opencv-2.1/cpp/object_detection.html#cv-cascadeclassifier-detectmultiscale)
# 入力画像から異なるサイズの物体を検出する
faces = cascade.detectMultiScale(
gray,
scaleFactor = 1.1,
minNeighbors = 5,
minSize = (24, 24)
)
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x + w ,y + h), (0 , 0, 255), 2)
cv2.imshow('AnimeFaceDetect', image)
cv2.waitKey(0)
cv2.imwrite('out.png', image)
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.stderr.write('usage: detect.py <filename>')
sys.exit(-1)
detect(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment