Create streamlit interface that user input an picture and tell him if the person in the picture masked or not with ai moodle i already trained it
To upload files, please first save the app
import streamlit as st
from PIL import Image
import numpy as np
import tensorflow as tf
import io
# Set page title and description
st.title("Face Mask Detection")
st.write("Upload an image to check if the person is wearing a mask or not.")
# Load the pre-trained model
@st.cache_resource
def load_model():
try:
model = tf.keras.models.load_model('mask_detection_model.h5')
return model
except:
st.error("Error: Model file not found. Please ensure 'mask_detection_model.h5' is in the same directory.")
return None
model = load_model()
def preprocess_image(image):
# Resize image to match model's expected sizing
image = image.resize((224, 224))
# Convert image to array
image_array = np.array(image)
# Normalize pixel values
image_array = image_array / 255.0
# Add batch dimension
image_array = np.expand_dims(image_array, axis=0)
return image_array
# Create file uploader
uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
# Display the uploaded image
image = Image.open(uploaded_file)
st.image(image, caption='Uploaded Image', use_column_width=True)
# Add a button to perform detection
if st.button("Detect Mask"):
if model is not None:
# Preprocess the image
processed_image = preprocess_image(image)
# Make prediction
try:
prediction = model.predict(processed_image)
probability = prediction[0][0]
# Display result
st.write("### Detection Result")
if probability > 0.5:
st.success(f"Mask detected! (Confidence: {probability:.2%})")
st.balloons()
else:
st.error(f"No mask detected! (Confidence: {(1-probability):.2%})")
# Display probability bar
st.progress(float(probability))
except Exception as e:
st.error(f"Error during prediction: {str(e)}")
else:
st.error("Model not loaded properly. Please check if the model file exists.")
# Add information about the model
st.sidebar.title("About")
st.sidebar.info("""
This app uses a deep learning model trained to detect whether a person is wearing a face mask or not.
To use:
1. Upload an image
2. Click 'Detect Mask'
3. View the results
""")
Hi! I can help you with any questions about Streamlit and Python. What would you like to know?