nao_api_flask / app.py
brightlembo's picture
Update app.py
7a3cf1c verified
raw
history blame
1.66 kB
import torch
from torchvision import transforms
from PIL import Image
import json
import streamlit as st
# Charger les noms des classes
with open("class_names.json", "r") as f:
class_names = json.load(f)
# Charger le modèle
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = torch.load("efficientnet_b7_best.pth", map_location=device)
model.eval() # Mode évaluation
# Définir la taille de l'image
image_size = (224, 224)
# Transformation pour l'image
class GrayscaleToRGB:
def __call__(self, img):
return img.convert("RGB")
valid_test_transforms = transforms.Compose([
transforms.Grayscale(num_output_channels=1),
transforms.Resize(image_size),
GrayscaleToRGB(), # Conversion en RGB
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
])
# Fonction de prédiction
def predict_image(image):
image_tensor = valid_test_transforms(image).unsqueeze(0).to(device)
with torch.no_grad():
outputs = model(image_tensor)
_, predicted_class = torch.max(outputs, 1)
predicted_label = class_names[predicted_class.item()]
return predicted_label
# Interface Streamlit
st.title("Prédiction d'images avec PyTorch")
st.write("Chargez une image pour obtenir une prédiction de classe.")
uploaded_image = st.file_uploader("Téléchargez une image", type=["jpg", "jpeg", "png"])
if uploaded_image is not None:
image = Image.open(uploaded_image)
st.image(image, caption="Image téléchargée", use_column_width=True)
predicted_label = predict_image(image)
st.write(f"Prédiction de la classe : {predicted_label}")