-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuntitled33.py
140 lines (107 loc) · 4.4 KB
/
untitled33.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# -*- coding: utf-8 -*-
"""Untitled33.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1fahZPLmYxthVsJN10DCEcwOBY1WpI9kz
"""
import zipfile
import os
# Specify the path to the uploaded ZIP file (replace 'your_file.zip' with the actual file name)
zip_path = "/content/test.zip"
# Extract the contents of the zip file
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall("/content/test") # Extract to the 'dataset' directory
# Optionally, check extracted files
print(os.listdir("/content/test"))
import zipfile
import os
# Specify the path to the uploaded ZIP file (replace 'your_file.zip' with the actual file name)
zip_path = "/content/train.zip"
# Extract the contents of the zip file
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
zip_ref.extractall("/content/train") # Extract to the 'dataset' directory
# Optionally, check extracted files
print(os.listdir("/content/train"))
import numpy as np
import tensorflow as tf # Import tensorflow
#import keras # Remove this line as we are using tf.keras
#import keras.backend as k # Remove as we are using tf.keras.backend
from tensorflow.keras.layers import Conv2D,MaxPooling2D,SpatialDropout2D,Flatten,Dropout,Dense # Update import path
from tensorflow.keras.models import Sequential,load_model # Update import path
from tensorflow.keras.optimizers import Adam # Update import path
from tensorflow.keras.preprocessing import image # Update import path
import cv2
import datetime
# UNCOMMENT THE FOLLOWING CODE TO TRAIN THE CNN FROM SCRATCH
# BUILDING MODEL TO CLASSIFY BETWEEN MASK AND NO MASK
model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(150,150,3)))
model.add(MaxPooling2D() )
model.add(Conv2D(32,(3,3),activation='relu'))
model.add(MaxPooling2D() )
model.add(Conv2D(32,(3,3),activation='relu'))
model.add(MaxPooling2D() )
model.add(Flatten())
model.add(Dense(100,activation='relu'))
model.add(Dense(1,activation='sigmoid'))
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
from tensorflow.keras.preprocessing.image import ImageDataGenerator # Update import path
train_datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
training_set = train_datagen.flow_from_directory(
'train',
target_size=(150,150),
batch_size=16 ,
class_mode='binary')
test_set = test_datagen.flow_from_directory(
'test',
target_size=(150,150),
batch_size=16,
class_mode='binary')
# Replace fit_generator with fit
model_saved=model.fit(
training_set,
epochs=10,
validation_data=test_set,
)
model.save('my_model.keras',model_saved)
#To test for individual images
mymodel=load_model('my_model.keras')
#test_image=image.load_img('C:/Users/Karan/Desktop/ML Datasets/Face Mask Detection/Dataset/test/without_mask/30.jpg',target_size=(150,150,3))
test_image=image.load_img(r'/content/mask.png',
target_size=(150,150,3))
test_image
test_image=image.img_to_array(test_image)
test_image=np.expand_dims(test_image,axis=0)
mymodel.predict(test_image)[0][0]
# IMPLEMENTING LIVE DETECTION OF FACE MASK
mymodel=load_model('my_model.keras')
cap=cv2.VideoCapture(0)
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
while cap.isOpened():
_,img=cap.read()
face=face_cascade.detectMultiScale(img,scaleFactor=1.1,minNeighbors=4)
for(x,y,w,h) in face:
face_img = img[y:y+h, x:x+w]
cv2.imwrite('temp.jpg',face_img)
test_image=image.load_img('temp.jpg',target_size=(150,150,3))
test_image=image.img_to_array(test_image)
test_image=np.expand_dims(test_image,axis=0)
pred=mymodel.predict(test_image)[0][0]
if pred==1:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3)
cv2.putText(img,'NO MASK',((x+w)//2,y+h+20),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3)
else:
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)
cv2.putText(img,'MASK',((x+w)//2,y+h+20),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),3)
datet=str(datetime.datetime.now())
cv2.putText(img,datet,(400,450),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255),1)
cv2.imshow('img',img)
if cv2.waitKey(1)==ord('q'):
break
cap.release()
cv2.destroyAllWindows()