Spaces:
Sleeping
Sleeping
File size: 2,702 Bytes
8a9662a 3e0991a 8a9662a 7a3cf1c 3e0991a b54a6c4 5b930d9 b54a6c4 8a9662a 437db0b 7a3cf1c b54a6c4 5f4a96a b54a6c4 5f4a96a b54a6c4 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 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
import torch
from torchvision import transforms
from PIL import Image
import streamlit as st
import json
from torchvision.models import efficientnet_b7, EfficientNet_B7_Weights
import torch.nn as nn
# Charger les noms des classes
with open("class_names.json", "r") as f:
class_names = json.load(f)
# Charger le modèle avec des poids pré-entraînés
weights = EfficientNet_B7_Weights.DEFAULT
base_model = efficientnet_b7(weights=weights)
# Adapter le modèle pour la classification
class CustomEfficientNet(nn.Module):
def __init__(self, base_model, num_classes):
super(CustomEfficientNet, self).__init__()
self.base = nn.Sequential(*list(base_model.children())[:-2])
self.global_avg_pool = nn.AdaptiveAvgPool2d(1)
self.fc1 = nn.Linear(2560, 512)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(512, num_classes)
def forward(self, x):
x = self.base(x)
x = self.global_avg_pool(x)
x = x.view(x.size(0), -1)
x = self.relu(self.fc1(x))
x = self.fc2(x)
return x
# Définir le modèle final
num_classes = 2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = CustomEfficientNet(base_model, num_classes).to("cuda" if torch.cuda.is_available() else "cpu")
model.load_state_dict(torch.load("efficientnet_b7_best.pth",weights_only=False, map_location=device))
model.eval() # Passer le modèle en 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}")
|