Skip to content

Commit 7421c50

Browse files
committed
bug fixed
1 parent 8030b59 commit 7421c50

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+2283
-0
lines changed

acc.gif

28.7 KB
Loading

app.py

Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
from PIL import Image as Im
2+
import os
3+
import webcam
4+
import streamlit as st
5+
from configu import *
6+
from detect_mask_image import detect
7+
from db import Video,Image
8+
from sqlalchemy.orm import sessionmaker
9+
from sqlalchemy import create_engine
10+
import cv2
11+
# from converter import convert_video
12+
from detect_mask_video import video
13+
14+
def opendb():
15+
engine = create_engine('sqlite:///db.sqlite3') # connect
16+
Session = sessionmaker(bind=engine)
17+
return Session()
18+
19+
def save_image(file,path):
20+
try:
21+
db = opendb()
22+
file = os.path.basename(path)
23+
name, ext = file.split('.') # second piece
24+
img = Image(filename=name,extension=ext,filepath=path)
25+
db.add(img)
26+
db.commit()
27+
db.close()
28+
return True
29+
except Exception as e:
30+
st.write("database error:",e)
31+
return False
32+
33+
st.sidebar.header(PROJECT_NAME)
34+
st.sidebar.write(DONE_BY)
35+
36+
choice = st.sidebar.radio("select option",MENU_OPTION)
37+
38+
if choice == 'About project':
39+
st.title("About Our Project")
40+
st.image('image/maskgirls.png')
41+
st.info('''Face Mask Detection Platform utilizes Artificial Network to perceive if a person does/doesn't wear a mask.
42+
The application can be associated with any currentor new cameras to identify individuals with/without a mask.
43+
By developing a face mask detection technique,
44+
through which we identify people weared mask or not.
45+
so we suggest people who not weared mask to wear it to reduce the covid/ any viral disease spread''')
46+
47+
48+
49+
if choice == 'Instruction to use':
50+
st.title("HOW TO USE THE APPLICATION")
51+
st.info(''' step 1. install the software on your computer.\n''')
52+
st.image('image/Softwareinstall.jpeg')
53+
st.info('''step 2. Connect your computer with webcam.\n''')
54+
st.image('image/webcamset.jpeg')
55+
st.info('''step 3. click on the realtime detection if you want detection through live stream.\n''')
56+
st.image('image/realtime.png')
57+
st.info('''step 4. Now click on "start camera window" button to start detection.\n''')
58+
st.image('image/instruction_realtime.PNG')
59+
st.info('''->Here you go.......\n''')
60+
st.image('image/9.PNG')
61+
st.info('''step 5.click on image based test if you want to detect through providing images.\n''')
62+
st.info('''->n the right hand side now you see "Browse File" button to upload image.\n''')
63+
st.image('image/instruction_imgbased.PNG')
64+
st.info('''->Now select your image for detection of mask.\n''')
65+
66+
st.image('image/instruction_imgbasedbrowse.PNG')
67+
st.info('''->Here you go.......\n''')
68+
st.image('image/instruction_imgbasedresult.png')
69+
st.image('image/instruction_imgbasedresultmasked.PNG')
70+
71+
72+
73+
74+
if choice == 'Sample dataset':
75+
st.title("Dataset Samples")
76+
st.image('sampleImage/b.jpeg')
77+
st.image('sampleImage/i.jpeg')
78+
st.image('sampleImage/c.jpeg')
79+
st.image('sampleImage/d.jpeg')
80+
st.image('sampleImage/e.jpeg')
81+
st.image('sampleImage/g.jpeg')
82+
st.image('sampleImage/h.jpeg')
83+
st.image('sampleImage/a.jpeg')
84+
st.image('sampleImage/j.jpeg')
85+
st.image('sampleImage/f.jpeg')
86+
87+
88+
if choice == 'Camera based test':
89+
st.title("Real time camera based test")
90+
btn = st.button('start realtime AI camera')
91+
if btn:
92+
webcam.load_camera(num=0)
93+
94+
95+
if choice == 'image based test':
96+
st.title("Upload images for image based test")
97+
st.subheader('select an image')
98+
img = st.file_uploader("browse to select",type=['jpg','png','jpeg'])
99+
if img:
100+
im = Im.open(img)
101+
# create a address for image path
102+
path = os.path.join("images",img.name)
103+
# save file to upload folder
104+
im.save(path,format=img.type.split('/')[1])
105+
status = save_image(img,path)
106+
if status:
107+
st.sidebar.success("file uploaded")
108+
col1 ,col2 = st.beta_columns(2)
109+
col1.image(path,use_column_width=True,caption='original')
110+
out_img = detect(path)
111+
cv2.imwrite(path,out_img)
112+
col2.image(path,use_column_width=True,caption='prediction')
113+
else:
114+
st.sidebar.error('upload failed')
115+
116+
if choice =='realtime detection':
117+
st.title("Real time camera based test")
118+
119+
cnf = st.slider('confidence threshold',min_value=.1, max_value=1.0,value=.5)
120+
btn = st.button("start camera window")
121+
st.info('Click on start camer window for detection ')
122+
if btn:
123+
video(cnf=cnf)
124+
if choice == 'view previous predictions':
125+
db = opendb()
126+
results = db.query(Image).all()
127+
db.close()

configu.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
PROJECT_NAME = 'FACE MASK DETECTION SYSTEM'
2+
DONE_BY = 'BY : HARENDRA PRAJAPATI'
3+
PRESS1 = 'PRESS TO KNOW ABOUT'
4+
PRESS2 = 'PRESS FOR INSTRUCTION'
5+
PRESS3 = 'PRESS TO SEE DATASET SAMPLE'
6+
PRESS4 = 'PRESS FOR VIDEO BASED TEST'
7+
PRESS5 = 'PRESS FOR CAMERA BASED TEST'
8+
MENU_OPTION = ('About project','Instruction to use','Sample dataset','realtime detection','image based test')

db.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import sqlalchemy
2+
from datetime import datetime
3+
from sqlalchemy import create_engine, Column, Integer,String,DateTime
4+
from sqlalchemy.ext import declarative
5+
from sqlalchemy.ext.declarative import declarative_base
6+
7+
Base = declarative_base()
8+
9+
class Image(Base):
10+
__tablename__ ='images'
11+
12+
id = Column(Integer, primary_key=True)
13+
filename = Column(String)
14+
extension = Column(String)
15+
filepath = Column(String)
16+
uploader = Column(String,default='admin')
17+
created_on = Column(DateTime, default=datetime.now)
18+
19+
def __str__(self):
20+
return self.filename
21+
22+
class Video(Base):
23+
__tablename__ ='videos'
24+
25+
id = Column(Integer, primary_key=True)
26+
filename = Column(String)
27+
extension = Column(String)
28+
filepath = Column(String)
29+
uploader = Column(String,default='admin')
30+
created_on = Column(DateTime, default=datetime.now)
31+
32+
def __str__(self):
33+
return self.filename
34+
35+
if __name__ == "__main__":
36+
engine = create_engine('sqlite:///db.sqlite3')
37+
Base.metadata.create_all(engine)

detect_mask_image.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
# import the necessary packages
2+
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
3+
from tensorflow.keras.preprocessing.image import img_to_array
4+
from tensorflow.keras.models import load_model
5+
import numpy as np
6+
import cv2
7+
import os
8+
9+
# load our serialized face detector model from disk
10+
11+
def detect(image,face="face_detector",model="mask_detector.model",cnf=0.5):
12+
prototxtPath = os.path.sep.join([face, "deploy.prototxt"])
13+
weightsPath = os.path.sep.join([face,"res10_300x300_ssd_iter_140000.caffemodel"])
14+
net = cv2.dnn.readNet(prototxtPath, weightsPath)
15+
# load the face mask detector model from disk
16+
print("[INFO] loading face mask detector model...")
17+
model = load_model(model)
18+
# load the input image from disk, clone it, and grab the image spatial
19+
# dimensions
20+
image = cv2.imread(image)
21+
orig = image.copy()
22+
(h, w) = image.shape[:2]
23+
# construct a blob from the image
24+
blob = cv2.dnn.blobFromImage(image, 1.0, (300, 300),(104.0, 177.0, 123.0))
25+
# pass the blob through the network and obtain the face detections
26+
print("[INFO] computing face detections...")
27+
net.setInput(blob)
28+
detections = net.forward()
29+
30+
# loop over the detections
31+
for i in range(0, detections.shape[2]):
32+
# extract the confidence (i.e., probability) associated with
33+
# the detection
34+
confidence = detections[0, 0, i, 2]
35+
36+
# filter out weak detections by ensuring the confidence is
37+
# greater than the minimum confidence
38+
if confidence > cnf:
39+
# compute the (x, y)-coordinates of the bounding box for
40+
# the object
41+
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
42+
(startX, startY, endX, endY) = box.astype("int")
43+
# ensure the bounding boxes fall within the dimensions of
44+
# the frame
45+
(startX, startY) = (max(0, startX), max(0, startY))
46+
(endX, endY) = (min(w - 1, endX), min(h - 1, endY))
47+
# extract the face ROI, convert it from BGR to RGB channel
48+
# ordering, resize it to 224x224, and preprocess it
49+
try:
50+
face = image[startY:endY, startX:endX]
51+
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
52+
face = cv2.resize(face, (224, 224))
53+
face = img_to_array(face)
54+
face = preprocess_input(face)
55+
face = np.expand_dims(face, axis=0)
56+
# pass the face through the model to determine if the face
57+
# has a mask or not
58+
(mask, withoutMask) = model.predict(face)[0]
59+
# determine the class label and color we'll use to draw
60+
# the bounding box and text
61+
label = "Mask" if mask > withoutMask else "No Mask"
62+
color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
63+
# include the probability in the label
64+
label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
65+
# display the label and bounding box rectangle on the output
66+
# frame
67+
cv2.putText(image, label, (startX, startY - 10),
68+
cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
69+
cv2.rectangle(image, (startX, startY), (endX, endY), color, 2)
70+
except:pass
71+
72+
# show the output image
73+
return image
74+
75+
76+
if __name__=="__main__":
77+
out=detect(image="examples/1.jpg")
78+
cv2.imshow("output",out)
79+
print("[INFO] showing output, check image ...")
80+
cv2.waitKey(0)

detect_mask_video.py

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# import the necessary packages
2+
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
3+
from tensorflow.keras.preprocessing.image import img_to_array
4+
from tensorflow.keras.models import load_model
5+
from imutils.video import VideoStream
6+
import numpy as np
7+
8+
import imutils
9+
import time
10+
import cv2
11+
import os
12+
def detect_and_predict_mask(frame, faceNet, maskNet,cnf=.5):
13+
# grab the dimensions of the frame and then construct a blob
14+
# from it
15+
(h, w) = frame.shape[:2]
16+
blob = cv2.dnn.blobFromImage(frame, 1.0, (300, 300),(104.0, 177.0, 123.0))
17+
# pass the blob through the network and obtain the face detections
18+
faceNet.setInput(blob)
19+
detections = faceNet.forward()
20+
# initialize our list of faces, their corresponding locations,
21+
# and the list of predictions from our face mask network
22+
faces = []
23+
locs = []
24+
preds = []
25+
# loop over the detections
26+
for i in range(0, detections.shape[2]):
27+
# extract the confidence (i.e., probability) associated with
28+
# the detection
29+
confidence = detections[0, 0, i, 2]
30+
# filter out weak detections by ensuring the confidence is
31+
# greater than the minimum confidence
32+
if confidence > cnf:
33+
# compute the (x, y)-coordinates of the bounding box for
34+
# the object
35+
box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
36+
(startX, startY, endX, endY) = box.astype("int")
37+
# ensure the bounding boxes fall within the dimensions of
38+
# the frame
39+
(startX, startY) = (max(0, startX), max(0, startY))
40+
(endX, endY) = (min(w - 1, endX), min(h - 1, endY))
41+
# extract the face ROI, convert it from BGR to RGB channel
42+
# ordering, resize it to 224x224, and preprocess it
43+
face = frame[startY:endY, startX:endX]
44+
face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
45+
face = cv2.resize(face, (224, 224))
46+
face = img_to_array(face)
47+
face = preprocess_input(face)
48+
# add the face and bounding boxes to their respective
49+
# lists
50+
faces.append(face)
51+
locs.append((startX, startY, endX, endY))
52+
# only make a predictions if at least one face was detected
53+
if len(faces) > 0:
54+
# for faster inference we'll make batch predictions on *all*
55+
# faces at the same time rather than one-by-one predictions
56+
# in the above `for` loop
57+
faces = np.array(faces, dtype="float32")
58+
preds = maskNet.predict(faces, batch_size=32)
59+
# return a 2-tuple of the face locations and their corresponding
60+
# locations
61+
return (locs, preds)
62+
63+
64+
def video(face ='face_detector',model = 'mask_detector.model',cnf=.5):
65+
print("[INFO] loading face detector model...")
66+
prototxtPath = os.path.sep.join([face, "deploy.prototxt"])
67+
weightsPath = os.path.sep.join([face,"res10_300x300_ssd_iter_140000.caffemodel"])
68+
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)
69+
# load the face mask detector model from disk
70+
print("[INFO] loading face mask detector model...")
71+
maskNet = load_model(model)
72+
# initialize the video stream and allow the camera sensor to warm up
73+
print("[INFO] starting video stream...")
74+
vs = VideoStream(src=0).start()
75+
time.sleep(2.0)
76+
# loop over the frames from the video stream
77+
while True:
78+
frame = vs.read()
79+
frame = imutils.resize(frame, width=400)
80+
(locs, preds) = detect_and_predict_mask(frame, faceNet, maskNet)
81+
for (box, pred) in zip(locs, preds):
82+
(startX, startY, endX, endY) = box
83+
(mask, withoutMask) = pred
84+
label = "Mask" if mask > withoutMask else "No Mask"
85+
color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
86+
label = "{}: {:.2f}%".format(label, max(mask, withoutMask) * 100)
87+
cv2.putText(frame, label, (startX, startY - 10),cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
88+
cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)
89+
cv2.imshow("Frame", frame)
90+
key = cv2.waitKey(1)
91+
if key == 27:
92+
break
93+
# do a bit of cleanup
94+
cv2.destroyAllWindows()
95+
vs.stop()
96+
if __name__ =='__main__':
97+
video()

examples/1.jpg

19.3 KB
Loading

examples/5.jpg

26.3 KB
Loading

0 commit comments

Comments
 (0)