-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Face mask #630
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
avinashkranjan
merged 9 commits into
avinashkranjan:master
from
sudipg4112001:Face_Mask
Mar 21, 2021
Merged
Face mask #630
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
bfc2c9d
Add files via upload
sudipg4112001 9da5a4b
Create readme.md
sudipg4112001 36b1a87
Add files via upload
sudipg4112001 a6c083e
Add files via upload
sudipg4112001 ecbb3a1
Delete face-mask-detection-using-cnn.ipynb
sudipg4112001 16a14df
Update face_mask_detection_using_cnn.py
sudipg4112001 8484f3a
Update readme.md
sudipg4112001 a4f8161
Update face_mask_detection_using_cnn.py
sudipg4112001 a2788f4
Update face_mask_detection_using_cnn.py
sudipg4112001 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
import numpy as np | ||
import pandas as pd | ||
import cv2 | ||
import matplotlib.pyplot as plt | ||
from tensorflow.keras.models import Model, Sequential | ||
from tensorflow.keras import layers | ||
import tensorflow as tf | ||
from keras.preprocessing.image import img_to_array | ||
from tensorflow.keras import backend | ||
from tensorflow.keras.preprocessing.image import ImageDataGenerator | ||
import os | ||
from sklearn.metrics import classification_report | ||
import sklearn.metrics as metrics | ||
import itertools | ||
for dirname, _, filenames in os.walk('/kaggle/input'): | ||
for filename in filenames: | ||
print(os.path.join(dirname, filename)) | ||
def data_set(dir_data): | ||
data=[] | ||
target=[] | ||
data_map = { | ||
'with_mask':1, | ||
'without_mask':0 | ||
} | ||
skipped=0 | ||
root=dir_data+'_annotations.csv' | ||
df1 = pd.read_csv(root) | ||
df1.dataframeName = '_annotations.csv' | ||
nRow, nCol = df1.shape | ||
for i in range(len(df1)): | ||
without_mask='without_mask' | ||
k=dir_data+df1['filename'][i] | ||
image=cv2.imread(k) | ||
xmin=int(df1['xmin'][i]) | ||
ymin=int(df1['ymin'][i]) | ||
xmax=int(df1['xmax'][i]) | ||
ymax=int(df1['ymax'][i]) | ||
#image=image[ymin:ymax, xmin:xmax] | ||
try: | ||
# resizing to (70 x 70) | ||
image = cv2.resize(image,(70,70)) | ||
except Exception as E: | ||
skipped += 1 | ||
print(E) | ||
continue | ||
if(df1['class'][i]=='mask'): | ||
without_mask='with_mask' | ||
image=img_to_array(image) | ||
data.append(image) | ||
target.append(data_map[without_mask]) | ||
data = np.array(data, dtype="float") / 255.0 | ||
target = tf.keras.utils.to_categorical(np.array(target), num_classes=2) | ||
return data, target | ||
training_data,training_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/train/') | ||
testing_data,testing_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/test/') | ||
valid_data,valid_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/valid/') | ||
plt.figure(0, figsize=(100,100)) | ||
for i in range(1,10): | ||
plt.subplot(10,5,i) | ||
plt.imshow(training_data[i]) | ||
img_shape=training_data[0].shape | ||
depth, height, width=3, img_shape[0], img_shape[1] | ||
img_shape=(height, width, depth) | ||
chanDim=-1 | ||
if backend.image_data_format() == "channels_first": #Returns a string, either 'channels_first' or 'channels_last' | ||
img_shape = (depth, height, width) | ||
chanDim = 1 | ||
model=Sequential() | ||
model.add(layers.Conv2D(32,(3,3),input_shape=img_shape)) | ||
model.add(layers.MaxPooling2D(pool_size=(2,2))) | ||
model.add(layers.Conv2D(64,(3,3))) | ||
model.add(layers.Activation('relu')) | ||
model.add(layers.MaxPooling2D(pool_size=(2,2))) | ||
model.add(layers.Conv2D(128,(3,3))) | ||
model.add(layers.Activation('relu')) | ||
model.add(layers.MaxPooling2D(pool_size=(2,2))) | ||
model.add(layers.Conv2D(256,(3,3))) | ||
model.add(layers.Activation('relu')) | ||
model.add(layers.MaxPooling2D(pool_size=(2,2))) | ||
model.add(layers.Flatten()) | ||
model.add(layers.Dropout(0.5)) | ||
model.add(layers.Dense(64,activation='relu')) | ||
model.add(layers.Dropout(0.4)) | ||
model.add(layers.Dense(2,activation='softmax')) | ||
adam =tf.keras.optimizers.Adam(0.001) | ||
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) | ||
model.summary() | ||
aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1, | ||
height_shift_range=0.1, shear_range=0.2, zoom_range=0.2, | ||
horizontal_flip=True, fill_mode="nearest") | ||
history = model.fit(aug.flow(training_data, training_target, batch_size=10), | ||
epochs=70, | ||
validation_data=(valid_data, valid_target), | ||
verbose=2, | ||
shuffle=True) | ||
plt.plot(history.history['accuracy']) | ||
plt.plot(history.history['val_accuracy']) | ||
plt.ylabel(['accuracy']) | ||
plt.xlabel(['epoch']) | ||
plt.legend(['accuracy', 'val_accuracy']) | ||
plt.plot(history.history['loss']) | ||
plt.plot(history.history['val_loss']) | ||
plt.ylabel(['loss']) | ||
plt.xlabel(['epoch']) | ||
plt.legend(['loss', 'val_loss']) | ||
loss, accuracy = model.evaluate(testing_data,testing_target) | ||
print('accuracy= ',loss," loss= ",loss) | ||
yhat = model.predict(testing_data) | ||
test_pred=np.argmax(yhat,axis=1) | ||
testing_target=np.argmax(testing_target,axis=1) | ||
report = classification_report(testing_target, test_pred) | ||
print(report) | ||
def plot_confusion_matrix(cm, classes, | ||
normalize=False, | ||
title='Confusion matrix', | ||
cmap=plt.cm.RdYlGn): | ||
plt.imshow(cm, interpolation='nearest', cmap=cmap) | ||
plt.title(title) | ||
plt.colorbar() | ||
tick_marks = np.arange(len(classes)) | ||
plt.xticks(tick_marks, classes, rotation=45) | ||
plt.yticks(tick_marks, classes) | ||
|
||
thresh = cm.max() / 2. | ||
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): | ||
plt.text(j, i, cm[i, j], | ||
horizontalalignment="center", | ||
color="white" if cm[i, j] > thresh else "black") | ||
|
||
plt.tight_layout() | ||
plt.ylabel('True label') | ||
plt.xlabel('Predicted label') | ||
|
||
confusion = metrics.confusion_matrix(testing_target, test_pred) | ||
plt.figure() | ||
plot_confusion_matrix(confusion, classes=['without_mask','with_mask'], title='Confusion matrix') |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
### Introduction: | ||
- Face mask detection had seen significant progress in the domains of Image processing and Computer vision, since the rise of the Covid-19 pandemic. Many face detection models have been created using several algorithms and techniques. The approach in this project uses deep learning, TensorFlow, Keras, and OpenCV to detect face masks. | ||
- Convolutional Neural Network, Data augmentation are the key to this project. | ||
### Example: | ||
 | ||
 | ||
### Methodology: | ||
 | ||
### Setup Instructions: | ||
- This project contains datset with large number of data so all the datsets(Training, Testing, Validation) are put in a file named 'Dataset.rar'. This file needs to be extracted before proceeding with the project. | ||
- The python script is fully made using Kaggle kernel. Anyone proceeding with the script are suggested to use Kaggle kernel, Google Colab, or Jupyter Notebook to run the script smoothly. | ||
- All the datasets from the file 'Dataset.rar' should be uploaded, then the path is used in the script. | ||
### Requirements: | ||
- numpy | ||
- pandas | ||
- tensorflow | ||
- opencv | ||
- keras | ||
- sklearn | ||
|
||
Install all the modules listed under 'Requirements' section. |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This path also needs modification