|
import torch |
|
from torchvision import transforms |
|
from PIL import Image, ImageStat |
|
import gradio as gr |
|
import numpy as np |
|
|
|
|
|
model = torch.load('model_v11.pt', map_location=torch.device('cpu')) |
|
model.eval() |
|
|
|
|
|
def log_image_color_stats(image): |
|
stat = ImageStat.Stat(image) |
|
mean_rgb = stat.mean |
|
print(f"Color Stats - R: {mean_rgb[0] / 255.0}, G: {mean_rgb[1] / 255.0}, B: {mean_rgb[2] / 255.0}") |
|
|
|
|
|
def log_tensor_data(tensor): |
|
print(f"Tensor shape: {tensor.shape}") |
|
print(f"Tensor data (first 10 values): {tensor.flatten()[:10]}") |
|
|
|
|
|
preprocess = transforms.Compose([ |
|
transforms.Resize((224, 224)), |
|
transforms.ToTensor(), |
|
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) |
|
]) |
|
|
|
|
|
preprocess_without_normalize = transforms.Compose([ |
|
transforms.Resize((224, 224)), |
|
transforms.ToTensor() |
|
]) |
|
|
|
|
|
def classify_image(image): |
|
|
|
log_image_color_stats(image) |
|
|
|
|
|
img_resized = image.resize((224, 224)) |
|
print(f"Resized Bitmap dimensions: {img_resized.size}") |
|
|
|
|
|
img_tensor_no_normalize = preprocess_without_normalize(image).unsqueeze(0) |
|
print("Tensor data before normalization:") |
|
log_tensor_data(img_tensor_no_normalize) |
|
|
|
|
|
img_tensor = preprocess(image).unsqueeze(0) |
|
log_tensor_data(img_tensor) |
|
|
|
|
|
with torch.no_grad(): |
|
output = model(img_tensor) |
|
|
|
|
|
print(f"Raw output scores: {output}") |
|
|
|
|
|
probabilities = torch.softmax(output, dim=1) |
|
|
|
|
|
predicted_class_index = probabilities.argmax() |
|
predicted_probability = probabilities[0][predicted_class_index] |
|
|
|
|
|
print("Probabilities for each class:") |
|
for index, prob in enumerate(probabilities[0]): |
|
print(f"Class {index}: {prob.item():.4f}") |
|
|
|
|
|
return f"Predicted class index: {predicted_class_index.item()}, Probability: {predicted_probability.item():.4f}" |
|
|
|
|
|
gr.Interface(fn=classify_image, inputs="image", outputs="text").launch() |
|
|