Skip to content

Instantly share code, notes, and snippets.

@kajiiiro
Last active August 4, 2019 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kajiiiro/8f9278255ac08d990a5a83c073926a94 to your computer and use it in GitHub Desktop.
Save kajiiiro/8f9278255ac08d990a5a83c073926a94 to your computer and use it in GitHub Desktop.
そのままだと動かなかったので少し変更 `opencv-contrib-python`が必要そう see: http://famirror.hateblo.jp/entry/2015/12/19/180000
# -*- coding:utf-8 -*-
import cv2
import sys
import os
import shutil
args = sys.argv
argc = len(args)
if(argc != 2):
print('引数を指定して実行してください。')
quit()
image_path = args[1]
cascade_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
#ファイル読み込み
image = cv2.cv2.imread(image_path)
if(image is None):
print('画像を開けません。')
quit()
#グレースケール変換
image_gray = cv2.cv2.cvtColor(image, cv2.cv2.COLOR_BGR2GRAY) # cv2.data.CV_BGR2GRAY
#カスケード分類器の特徴量を取得する
cascade = cv2.cv2.CascadeClassifier(cascade_path)
#物体認識(顔認識)の実行
facerect = cascade.detectMultiScale(image_gray, scaleFactor=1.01, minNeighbors=2, minSize=(50, 50))
# print("face rectangle")
# print(facerect)
#ディレクトリの作成
path, ext = os.path.splitext(image_path)
file = os.path.basename(path)
dir_path = './face/' + os.path.dirname(image_path)
if os.path.isdir(dir_path) == False:
os.makedirs(dir_path, exist_ok=True)
i = 0
for rect in facerect:
#顔だけ切り出して保存
x = rect[0]
y = rect[1]
width = rect[2]
height = rect[3]
dst = image[y:y+height, x:x+width]
new_image_path = dir_path + "/" + file + "_" + str(i).zfill(3) + ext
cv2.cv2.imwrite(new_image_path, dst)
print("create " + new_image_path)
i += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment