Skip to content

Instantly share code, notes, and snippets.

@h1dia
Created January 1, 2017 08:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save h1dia/f3266299fbd96aa79b5f0f1573384b49 to your computer and use it in GitHub Desktop.
顔識別器
import cv2
import sys
import os
import os.path
import numpy as np
np.random.seed(1337)
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from PIL import Image
label = ["Meguru", "Nene", "no_face", "other", "Touko", "Tsumugi", "Wakana"]
def cnn():
model = Sequential()
model.add(Convolution2D(32, 3, 3, border_mode='same',
input_shape=(32, 32, 3)))
model.add(Activation('relu'))
model.add(Convolution2D(32, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Convolution2D(64, 3, 3, border_mode='same'))
model.add(Activation('relu'))
model.add(Convolution2D(64, 3, 3))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(7))
model.add(Activation('softmax'))
return model
model = cnn()
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['accuracy'])
model.load_weights('sanoba_cnn.hdf5')
def predict(img):
im = cv2.resize(img, (32, 32))
im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB).astype(np.float32)
# im = im.transpose((2, 0, 1)) # for theano
im = im.reshape((1,) + im.shape)
im /= 255
classes = model.predict_classes(im)
return label[classes[0]]
def detect(filename, cascade_file = "./lbpcascade_animeface.xml"):
if not os.path.isfile(cascade_file):
raise RuntimeError("%s: not found" % cascade_file)
cascade = cv2.CascadeClassifier(cascade_file)
image = cv2.imread(filename)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.equalizeHist(gray)
faces = cascade.detectMultiScale(gray,
# detector options
scaleFactor = 1.05,
minNeighbors = 5,
minSize = (32, 32))
for (x, y, w, h) in faces:
name = predict(image[y:y+h, x:x+w])
if name != "no_face":
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
cv2.putText(image, name, (x, y), cv2.FONT_HERSHEY_PLAIN, 3, (255, 255, 0), 3)
cv2.imshow(name, image)
cv2.waitKey(0)
cv2.imwrite("out.png", image)
if len(sys.argv) != 2:
sys.stderr.write("usage: detect.py <filename>\n")
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