Giulio Rossi
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,76 +1,59 @@
|
|
1 |
import torch
|
2 |
-
|
3 |
-
from
|
4 |
-
|
5 |
import numpy as np
|
|
|
6 |
|
7 |
-
#
|
8 |
-
|
9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
-
#
|
12 |
-
|
13 |
-
stat = ImageStat.Stat(image)
|
14 |
-
mean_rgb = stat.mean
|
15 |
-
print(f"Color Stats - R: {mean_rgb[0] / 255.0}, G: {mean_rgb[1] / 255.0}, B: {mean_rgb[2] / 255.0}")
|
16 |
|
17 |
-
#
|
18 |
-
|
19 |
-
|
20 |
-
print(f"Tensor data (first 10 values): {tensor.flatten()[:10]}")
|
21 |
|
22 |
-
#
|
23 |
preprocess = transforms.Compose([
|
24 |
transforms.Resize((224, 224)),
|
25 |
transforms.ToTensor(),
|
26 |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
27 |
])
|
28 |
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
transforms.ToTensor()
|
33 |
-
])
|
34 |
-
|
35 |
-
# Funzione di previsione
|
36 |
-
def classify_image(image):
|
37 |
-
# Logga i colori dell'immagine originale
|
38 |
-
log_image_color_stats(image)
|
39 |
-
|
40 |
-
# Ridimensiona l'immagine per coerenza
|
41 |
-
img_resized = image.resize((224, 224))
|
42 |
-
print(f"Resized Bitmap dimensions: {img_resized.size}")
|
43 |
-
|
44 |
-
# Preprocessa e ottieni il tensore non normalizzato
|
45 |
-
img_tensor_no_normalize = preprocess_without_normalize(image).unsqueeze(0)
|
46 |
-
print("Tensor data before normalization:")
|
47 |
-
log_tensor_data(img_tensor_no_normalize)
|
48 |
-
|
49 |
-
# Preprocessa e normalizza
|
50 |
-
img_tensor = preprocess(image).unsqueeze(0)
|
51 |
-
log_tensor_data(img_tensor)
|
52 |
-
|
53 |
-
# Esegui la previsione
|
54 |
with torch.no_grad():
|
55 |
output = model(img_tensor)
|
56 |
-
|
57 |
-
# Logga i punteggi raw
|
58 |
-
print(f"Raw output scores: {output}")
|
59 |
-
|
60 |
-
# Calcola le probabilità
|
61 |
probabilities = torch.softmax(output, dim=1)
|
62 |
-
|
63 |
-
|
64 |
-
predicted_class_index = probabilities.argmax()
|
65 |
-
predicted_probability = probabilities[0][predicted_class_index]
|
66 |
|
67 |
-
|
68 |
-
print("Probabilities for each class:")
|
69 |
-
for index, prob in enumerate(probabilities[0]):
|
70 |
-
print(f"Class {index}: {prob.item():.4f}")
|
71 |
|
72 |
-
|
73 |
-
|
|
|
|
|
|
|
|
|
74 |
|
75 |
-
|
76 |
-
gr.Interface(fn=classify_image, inputs="image", outputs="text").launch()
|
|
|
1 |
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torchvision import models, transforms
|
4 |
+
from PIL import Image
|
5 |
import numpy as np
|
6 |
+
import gradio as gr
|
7 |
|
8 |
+
# Definisci il modello e il numero di classi
|
9 |
+
class PretrainedModel(nn.Module):
|
10 |
+
def __init__(self, num_classes=19):
|
11 |
+
super(PretrainedModel, self).__init__()
|
12 |
+
|
13 |
+
weights = models.ResNet50_Weights.IMAGENET1K_V2
|
14 |
+
self.model = models.resnet50(weights=weights)
|
15 |
+
|
16 |
+
# Congela i layer iniziali
|
17 |
+
for param in self.model.parameters():
|
18 |
+
param.requires_grad = False
|
19 |
+
|
20 |
+
# Sostituisci l'ultimo layer
|
21 |
+
num_features = self.model.fc.in_features
|
22 |
+
self.model.fc = nn.Linear(num_features, num_classes)
|
23 |
+
|
24 |
+
def forward(self, x):
|
25 |
+
return self.model(x)
|
26 |
|
27 |
+
# Crea un'istanza del modello
|
28 |
+
model = PretrainedModel(num_classes=19)
|
|
|
|
|
|
|
29 |
|
30 |
+
# Carica i pesi
|
31 |
+
model.load_state_dict(torch.load('model_v11.pt', map_location=torch.device('cpu')))
|
32 |
+
model.eval() # Imposta il modello in modalità valutazione
|
|
|
33 |
|
34 |
+
# Trasformazioni
|
35 |
preprocess = transforms.Compose([
|
36 |
transforms.Resize((224, 224)),
|
37 |
transforms.ToTensor(),
|
38 |
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
39 |
])
|
40 |
|
41 |
+
def classify_image(img):
|
42 |
+
# Preprocessa l'immagine
|
43 |
+
img_tensor = preprocess(img).unsqueeze(0) # Aggiunge una dimensione per il batch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
with torch.no_grad():
|
45 |
output = model(img_tensor)
|
|
|
|
|
|
|
|
|
|
|
46 |
probabilities = torch.softmax(output, dim=1)
|
47 |
+
predicted_class_index = probabilities.argmax().item()
|
48 |
+
predicted_probability = probabilities[0][predicted_class_index].item()
|
|
|
|
|
49 |
|
50 |
+
return f"Class {predicted_class_index}, Confidence: {predicted_probability:.4f}"
|
|
|
|
|
|
|
51 |
|
52 |
+
# Configura Gradio
|
53 |
+
iface = gr.Interface(
|
54 |
+
fn=classify_image,
|
55 |
+
inputs=gr.inputs.Image(type="pil"),
|
56 |
+
outputs="text"
|
57 |
+
)
|
58 |
|
59 |
+
iface.launch()
|
|