import torch import torch.nn as nn import torchvision.models as models from PIL import Image from torchvision import transforms # Device setup device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Image transformations (same as the one used during training) transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) # ImageNet standard ]) # Load models (ResNet18 and MobileNetV2) def load_models(): # Load ResNet18 model resnet18 = models.resnet18(pretrained=False) resnet18.fc = nn.Linear(resnet18.fc.in_features, 11) # Modify output layer for 11 classes resnet18.load_state_dict(torch.load('models/resnet18_fish_classification_model.pth')) resnet18.to(device) # Load MobileNetV2 model mobilenet_v2 = models.mobilenet_v2(pretrained=False) mobilenet_v2.classifier[1] = nn.Linear(1280, 11) # Modify output layer for 11 classes mobilenet_v2.load_state_dict(torch.load('models/mobilenetv2_fish_classification_model.pth')) mobilenet_v2.to(device) # Return models dictionary models_dict = { 'ResNet18': resnet18, 'MobileNetV2': mobilenet_v2 } return models_dict # Image prediction function def predict_image(image_path): models_dict = load_models() image = Image.open(image_path).convert('RGB') image = transform(image).unsqueeze(0).to(device) # Add batch dimension and move to device predictions = {} for model_name, model in models_dict.items(): model.eval() with torch.no_grad(): outputs = model(image) probabilities = torch.nn.functional.softmax(outputs, dim=1) _, predicted_class = torch.max(probabilities, 1) confidence = probabilities[0, predicted_class].item() predictions[model_name] = {'predicted_class': predicted_class.item(), 'confidence': confidence} return predictions