Spaces:
Sleeping
Sleeping
File size: 1,657 Bytes
8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c 8a9662a 7a3cf1c |
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 |
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}")
|