Last active
August 1, 2016 05:31
-
-
Save kenzo0107/5d174797a5a222295b5a39f6fa435777 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Python 3 | |
import cv2 | |
import sys | |
import os | |
args = sys.argv | |
argc = len(args) | |
cascade_path = "/usr/local/Cellar/opencv3/3.1.0_3/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml" | |
#cascade_path = "/usr/local/Cellar/opencv3/3.1.0_3/share/OpenCV/haarcascades/haarcascade_frontalface_alt2.xml" | |
#cascade_path = "/usr/local/Cellar/opencv3/3.1.0_3/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml" | |
#cascade_path = "/usr/local/Cellar/opencv3/3.1.0_3/share/OpenCV/haarcascades/haarcascade_eye.xml" | |
# 元画像から顔検知し枠で囲んだ画像を保存. | |
def saveDetectedFacesImg(image_path, facerect): | |
color = (255, 255, 255) | |
image = cv2.imread(image_path) | |
path = os.path.splitext(image_path) | |
for rect in facerect: | |
cv2.rectangle(image, tuple(rect[0:2]),tuple(rect[0:2]+rect[2:4]), color, thickness=2) | |
base = os.path.basename(image_path) | |
filename, ext = os.path.splitext(base) | |
cv2.imwrite("%s_detected.jpg"%(path[0]), image) | |
# 顔画像部分のみトリミングし保存. | |
def trimmingFaces(image_path, facerect): | |
path = os.path.splitext(image_path) | |
image = cv2.imread(image_path) | |
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] | |
trimming_image = '%s_%s_%s'%(path[0],i,path[1]) | |
cv2.imwrite(trimming_image, dst) | |
i += 1 | |
if __name__ == "__main__": | |
if(argc != 2): | |
print('You donnot set parameter, please again.') | |
quit() | |
image_path = args[1] | |
# read image file. | |
image = cv2.imread(image_path) | |
if(image is None): | |
print ('cannot open image : %s' %(image_path)) | |
quit() | |
# transite to gray scale | |
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
# get feature values. | |
cascade = cv2.CascadeClassifier(cascade_path) | |
# detect face. | |
facerect = cascade.detectMultiScale(image_gray, scaleFactor=1.02, minNeighbors=3, minSize=(7,7)) | |
if len(facerect) > 0: | |
saveDetectedFacesImg(image_path, facerect) | |
trimmingFaces(image_path, facerect) | |
print('can detect faces ! (^o^)') | |
else: | |
print('cannot detect faces...(>_<)') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment