Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit cae89d8

Browse files
Merge pull request avinashkranjan#630 from sudipg4112001/Face_Mask
Face mask
2 parents 08fbdec + a2788f4 commit cae89d8

File tree

7 files changed

+157
-0
lines changed

7 files changed

+157
-0
lines changed

‎Face-Mask-Detection/Dataset.rar‎

3.45 MB
Binary file not shown.
59.1 KB
Loading[フレーム]
11 KB
Loading[フレーム]
8.22 KB
Loading[フレーム]
10.6 KB
Loading[フレーム]
Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
1+
import numpy as np
2+
import pandas as pd
3+
import cv2
4+
import matplotlib.pyplot as plt
5+
from tensorflow.keras.models import Model, Sequential
6+
from tensorflow.keras import layers
7+
import tensorflow as tf
8+
from keras.preprocessing.image import img_to_array
9+
from tensorflow.keras import backend
10+
from tensorflow.keras.preprocessing.image import ImageDataGenerator
11+
import os
12+
from sklearn.metrics import classification_report
13+
import sklearn.metrics as metrics
14+
import itertools
15+
for dirname, _, filenames in os.walk('/kaggle/input'):
16+
for filename in filenames:
17+
print(os.path.join(dirname, filename))
18+
def data_set(dir_data):
19+
data=[]
20+
target=[]
21+
data_map = {
22+
'with_mask':1,
23+
'without_mask':0
24+
}
25+
skipped=0
26+
root=dir_data+'_annotations.csv'
27+
df1 = pd.read_csv(root)
28+
df1.dataframeName = '_annotations.csv'
29+
nRow, nCol = df1.shape
30+
for i in range(len(df1)):
31+
without_mask='without_mask'
32+
k=dir_data+df1['filename'][i]
33+
image=cv2.imread(k)
34+
xmin=int(df1['xmin'][i])
35+
ymin=int(df1['ymin'][i])
36+
xmax=int(df1['xmax'][i])
37+
ymax=int(df1['ymax'][i])
38+
#image=image[ymin:ymax, xmin:xmax]
39+
try:
40+
# resizing to (70 x 70)
41+
image = cv2.resize(image,(70,70))
42+
except Exception as E:
43+
skipped += 1
44+
print(E)
45+
continue
46+
if(df1['class'][i]=='mask'):
47+
without_mask='with_mask'
48+
image=img_to_array(image)
49+
data.append(image)
50+
target.append(data_map[without_mask])
51+
data = np.array(data, dtype="float") / 255.0
52+
target = tf.keras.utils.to_categorical(np.array(target), num_classes=2)
53+
return data, target
54+
training_data,training_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/train/')
55+
testing_data,testing_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/test/')
56+
valid_data,valid_target=data_set('./Face-Mask-Detection/kaggle/input/face-mask-detection/valid/')
57+
plt.figure(0, figsize=(100,100))
58+
for i in range(1,10):
59+
plt.subplot(10,5,i)
60+
plt.imshow(training_data[i])
61+
img_shape=training_data[0].shape
62+
depth, height, width=3, img_shape[0], img_shape[1]
63+
img_shape=(height, width, depth)
64+
chanDim=-1
65+
if backend.image_data_format() == "channels_first": #Returns a string, either 'channels_first' or 'channels_last'
66+
img_shape = (depth, height, width)
67+
chanDim = 1
68+
model=Sequential()
69+
model.add(layers.Conv2D(32,(3,3),input_shape=img_shape))
70+
model.add(layers.MaxPooling2D(pool_size=(2,2)))
71+
model.add(layers.Conv2D(64,(3,3)))
72+
model.add(layers.Activation('relu'))
73+
model.add(layers.MaxPooling2D(pool_size=(2,2)))
74+
model.add(layers.Conv2D(128,(3,3)))
75+
model.add(layers.Activation('relu'))
76+
model.add(layers.MaxPooling2D(pool_size=(2,2)))
77+
model.add(layers.Conv2D(256,(3,3)))
78+
model.add(layers.Activation('relu'))
79+
model.add(layers.MaxPooling2D(pool_size=(2,2)))
80+
model.add(layers.Flatten())
81+
model.add(layers.Dropout(0.5))
82+
model.add(layers.Dense(64,activation='relu'))
83+
model.add(layers.Dropout(0.4))
84+
model.add(layers.Dense(2,activation='softmax'))
85+
adam =tf.keras.optimizers.Adam(0.001)
86+
model.compile(loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy'])
87+
model.summary()
88+
aug = ImageDataGenerator(rotation_range=25, width_shift_range=0.1,
89+
height_shift_range=0.1, shear_range=0.2, zoom_range=0.2,
90+
horizontal_flip=True, fill_mode="nearest")
91+
history = model.fit(aug.flow(training_data, training_target, batch_size=10),
92+
epochs=70,
93+
validation_data=(valid_data, valid_target),
94+
verbose=2,
95+
shuffle=True)
96+
plt.plot(history.history['accuracy'])
97+
plt.plot(history.history['val_accuracy'])
98+
plt.ylabel(['accuracy'])
99+
plt.xlabel(['epoch'])
100+
plt.legend(['accuracy', 'val_accuracy'])
101+
plt.plot(history.history['loss'])
102+
plt.plot(history.history['val_loss'])
103+
plt.ylabel(['loss'])
104+
plt.xlabel(['epoch'])
105+
plt.legend(['loss', 'val_loss'])
106+
loss, accuracy = model.evaluate(testing_data,testing_target)
107+
print('accuracy= ',loss," loss= ",loss)
108+
yhat = model.predict(testing_data)
109+
test_pred=np.argmax(yhat,axis=1)
110+
testing_target=np.argmax(testing_target,axis=1)
111+
report = classification_report(testing_target, test_pred)
112+
print(report)
113+
def plot_confusion_matrix(cm, classes,
114+
normalize=False,
115+
title='Confusion matrix',
116+
cmap=plt.cm.RdYlGn):
117+
plt.imshow(cm, interpolation='nearest', cmap=cmap)
118+
plt.title(title)
119+
plt.colorbar()
120+
tick_marks = np.arange(len(classes))
121+
plt.xticks(tick_marks, classes, rotation=45)
122+
plt.yticks(tick_marks, classes)
123+
124+
thresh = cm.max() / 2.
125+
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
126+
plt.text(j, i, cm[i, j],
127+
horizontalalignment="center",
128+
color="white" if cm[i, j] > thresh else "black")
129+
130+
plt.tight_layout()
131+
plt.ylabel('True label')
132+
plt.xlabel('Predicted label')
133+
134+
confusion = metrics.confusion_matrix(testing_target, test_pred)
135+
plt.figure()
136+
plot_confusion_matrix(confusion, classes=['without_mask','with_mask'], title='Confusion matrix')

‎Face-Mask-Detection/readme.md‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
### Introduction:
2+
- 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.
3+
- Convolutional Neural Network, Data augmentation are the key to this project.
4+
### Example:
5+
![face mask sample](https://raw.githubusercontent.com/sudipg4112001/Amazing-Python-Scripts/Face_Mask/Face-Mask-Detection/Sample-images/Sample_image_3.jpg)
6+
![face mask sample](https://raw.githubusercontent.com/sudipg4112001/Amazing-Python-Scripts/Face_Mask/Face-Mask-Detection/Sample-images/Sample_image_2.jpg)
7+
### Methodology:
8+
![face mask sample](https://raw.githubusercontent.com/sudipg4112001/Amazing-Python-Scripts/Face_Mask/Face-Mask-Detection/Sample-images/Method.jpg)
9+
### Setup Instructions:
10+
- 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.
11+
- 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.
12+
- All the datasets from the file 'Dataset.rar' should be uploaded, then the path is used in the script.
13+
### Requirements:
14+
- numpy
15+
- pandas
16+
- tensorflow
17+
- opencv
18+
- keras
19+
- sklearn
20+
21+
Install all the modules listed under 'Requirements' section.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /