Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
python2.7,opencvで顔認識
import cv2
from os import path
import numpy as np
from matplotlib import pyplot as plt
%matplotlib inline
cascades_dir = path.normpath(path.join(cv2.__file__, '..', '..', '..', '..', 'share', 'OpenCV', 'haarcascades'))
cascade_f = cv2.CascadeClassifier(path.join(cascades_dir, 'haarcascade_frontalface_alt2.xml'))
def faceDetect(filePath):
img = cv2.imread(filePath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = cascade_f.detectMultiScale(img, 1.3, 5)
if len(faces) > 0:
cnt = 1
for(x, y, w, h) in faces:
# 顔を四角で囲む
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
# 顔だけを表示
cut_face_img = img[y:y+h,x:x+w]
# 横一列に顔を表示
plt.subplot(1, len(faces), cnt)
plt.imshow(cv2.cvtColor(cut_face_img, cv2.COLOR_BGR2RGB))
cnt += 1
plt.show()
else:
print 'no face'
faceDetect('images/mai001.jpg')
def getCroppedFace(filePath):
img = cv2.imread(filePath)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = cascade_f.detectMultiScale(img, 1.3, 5)
cropped_size = 100
if len(faces) > 0:
for(x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cut_face_img = img[y:y+h,x:x+w]
return cut_face_img
else:
print 'no face'
return false
def getResizedImage(img):
cropped_size = 100
resized_img = cv2.resize(img, (cropped_size, cropped_size))
return resized_img
croppedFace = getCroppedFace('images/mai001.jpg')
# croppedFace = getResizedImage(croppedFace)
plt.imshow(cv2.cvtColor(croppedFace, cv2.COLOR_BGR2RGB))
plt.show()
def getRotateImage(img, angle):
original_width, original_height = img.shape[:2]
size = original_width
matrix = cv2.getRotationMatrix2D((size / 2, size / 2), angle, 1.0)
rotated_img = cv2.warpAffine(img, matrix, (size, size))
return rotated_img
for delta_angle in range(-150, 150, 50):
rotated_img = getRotateImage(croppedFace, delta_angle)
plt.imshow(cv2.cvtColor(rotated_img, cv2.COLOR_BGR2RGB))
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment