How to make imaged based authentication?

Hello I want to make a a simple page where the user can upload an image, then that image is fed to a model, if the confidence of the model is higher than a certain threshold (for ex: 97%) then the user gets authenticated. How do I implement this using streamlit?

To perform inference locally, you will need to utilize a machine learning library. Alternatively, you can employ an API for a hosted model. Below is an example utilizing PyTorch:

import streamlit as st
from PIL import Image
import torch
from torchvision import transforms

# Load a pre-trained model (e.g., ResNet) for image classification
model = torch.hub.load('pytorch/vision', 'resnet18', pretrained=True)
model.eval()

# Define image transformation
transform = transforms.Compose([
    transforms.Resize(256),
    transforms.CenterCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])

# Function to predict image class
def predict_image(image):
    image = transform(image).unsqueeze(0)  # Transform image and add batch dimension
    with torch.no_grad():
        outputs = model(image)  # Forward pass
        probs = torch.nn.functional.softmax(outputs, dim=1)
        confidence, predicted_class = probs.max(1)
    return confidence.item(), predicted_class.item()

# Streamlit UI
st.title("Image Authentication")

# Upload image
uploaded_file = st.file_uploader("Choose an image", type=["jpg", "png", "jpeg"])

if uploaded_file is not None:
    # Display image
    image = Image.open(uploaded_file)
    st.image(image, caption="Uploaded Image", use_column_width=True)

    # Get prediction
    confidence, predicted_class = predict_image(image)

    # Set a confidence threshold (e.g., 97%)
    threshold = 0.97

    # Display result
    if confidence >= threshold:
        st.success(f"Authentication successful! Confidence: {confidence * 100:.2f}%")
    else:
        st.error(f"Authentication failed. Confidence: {confidence * 100:.2f}%")
1 Like

this isn’t secure, I need to authenticate the user to a secret page

To implement multiple protected pages with authentication, you can utilize the code example provided in the following GitHub repository.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.