Transfer Learning Used For Face Recognition
Transfer Learning Used For Face Recognition
I want to thank #vimaldaga sir because he is only person who taught me to this level to create a project. This Project is to Detect Faces by transfer learning and this can be useful in drones or hospital programs and may be in door lock system many thing you can do from this. This program mails you if mach not found or any other data set enteres . you can use it for sms alert any many platform what you need. Let’s get to the project…
The github link of this Project
https://github.com/ashu-cybertron/face-recognition-mobilenet-vgg16.git
TASK : Using MobileNet we have to to create a project which can regognise who is the person
We started with the data set collection because if you don’t have any pre downloaded dataset this will wbe help ful (if you have already then it is very good to start faster )
Add alt text
import cv2
import numpy as np
face_classifier = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
def face_extractor(img):
faces = face_classifier.detectMultiScale(img, 1.3, 5)
if faces is ():
return None
for (x,y,w,h) in faces:
cropped_face = img[y:y+h, x:x+w]
return cropped_face
cap = cv2.VideoCapture(0)
count = 0
# Collect 1000 samples of your face from webcam
while True:
ret, frame = cap.read()
if face_extractor(frame) is not None:
count += 1
face = cv2.resize(face_extractor(frame), (224, 224))
file_name_path = 'C://Users//Lenovo//Desktop//ashu//test//' + str(count) + '.jpg'
cv2.imwrite(file_name_path, face)
cv2.putText(face, str(count), (50, 50), cv2.FONT_HERSHEY_COMPLEX, 1, (0,255,0), 2)
cv2.imshow('Face Cropper', face)
else:
print("Face not found")
pass
if cv2.waitKey(1) == 13 or count == 100:
break
cap.release()
cv2.destroyAllWindows()
print("Collecting Samples Complete")
By Mobile-net face recognising program steps
step 1: load mobile-net model
from keras.applications import MobileNet
# MobileNet was designed to work on 224 x 224 pixel input images sizes
img_rows, img_cols = 224, 224
# Re-loads the MobileNet model without the top or FC layers
MobileNet = MobileNet(weights = 'imagenet',
include_top = False,
input_shape = (img_rows, img_cols, 3))
# Here we freeze the last 4 layers
# Layers are set to trainable as True by default
for layer in MobileNet.layers:
layer.trainable = False
# Let's print our layers
for (i,layer) in enumerate(MobileNet.layers):
print(str(i) + " "+ layer.__class__.__name__, layer.trainable)
step 2: add layers
def lw(bottom_model, num_classes):
"""creates the top or head of the model that will be
placed ontop of the bottom layers"""
top_model = bottom_model.output
top_model = GlobalAveragePooling2D()(top_model)
top_model = Dense(1024,activation='relu')(top_model)
top_model = Dense(1024,activation='relu')(top_model)
top_model = Dense(512,activation='relu')(top_model)
top_model = Dense(num_classes,activation='softmax')(top_model)
return top_model
step 3: load dataset
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten, GlobalAveragePooling2D
from keras.layers import Conv2D, MaxPooling2D, ZeroPadding2D
from keras.layers.normalization import BatchNormalization
from keras.models import Model
# Set our class number to 3 (Young, Middle, Old)
num_classes = 2
FC_Head = lw(MobileNet, num_classes)
model = Model(inputs = MobileNet.input, outputs = FC_Head)
print(model.summary())
step 4 : train model
from keras.preprocessing.image import ImageDataGenerator
train_data_dir = 'face//train//'
validation_data_dir = 'face//validation//'
# Let's use some data augmentaiton
train_datagen = ImageDataGenerator(
rescale=1./255,
rotation_range=45,
width_shift_range=0.3,
height_shift_range=0.3,
horizontal_flip=True,
fill_mode='nearest')
validation_datagen = ImageDataGenerator(rescale=1./255)
# set our batch size
batch_size = 64
train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size=(img_rows, img_cols),
batch_size=batch_size,
class_mode='categorical')
validation_generator = validation_datagen.flow_from_directory(
validation_data_dir,
target_size=(img_rows, img_cols),
batch_size=batch_size,
class_mode='categorical')
step 5: save and test
from keras.optimizers import RMSprop
from keras.callbacks import ModelCheckpoint, EarlyStopping
from keras.models import load_model
checkpoint = ModelCheckpoint("facer.h5",
monitor="val_loss",
mode="min",
save_best_only = True,
verbose=1)
earlystop = EarlyStopping(monitor = 'val_loss',
min_delta = 0,
patience = 3,
verbose = 1,
restore_best_weights = True)
# we put our call backs into a callback list
callbacks = [earlystop, checkpoint]
# We use a very small learning rate
model.compile(loss = 'categorical_crossentropy',
optimizer = RMSprop(lr = 0.001),
metrics = ['accuracy'])
# Enter the number of training and validation samples here
nb_train_samples = 544
nb_validation_samples = 200
# We only train 5 EPOCHS
epochs = 10
batch_size = 64
history = model.fit_generator(
train_generator,
steps_per_epoch = nb_train_samples // batch_size,
epochs = epochs,
callbacks = callbacks,
validation_data = validation_generator,
validation_steps = nb_validation_samples // batch_size)
classifier = load_model('facer.h5')
And
For recognition by VGG16 ::>
Next we have to load VGG16 model:
Here we are using VGG16’s pre-trained model. We are unique sized (224x222) images
Add alt text
Next we have to Freeze pre-trained layers and Add layers:
Add alt text
Here we freezed pre-trained layers add 3 more layers for better accuracy.
Next we have to Load our dataset:
Add alt text
Here given location of our training and testing dataset and used categorical class..
Next we have to train our model:
Add alt text
and it is done val_accuracy is not up to the mark because it used 3 epochs try with 5 and more it will increase accuracy , i tried with 8 than it was 0.92 which is better but takes more time and resources so i given here only 3 epochs and images in data set should be greater 1000 and above an numbers because less data take you to less accuracy
again Thank you vimal sir to make me proud on me
Comments
Post a Comment