argentinian_ids / test_model.py
Lautaro Suarez
Track large model files with Git LFS
4479560
Raw History Blame Contribute Delete
2.03 kB
import torch
import torch.nn as nn
from torchvision import models, transforms
from torch.autograd import Variable
from PIL import Image
import os
# Define the device
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Load the trained model (Assumes 'dni_image_validation_model.pth' is in the same folder as this script)
model = models.resnet18(weights=None)
num_ftrs = model.fc.in_features
model.fc = nn.Linear(num_ftrs, 3) # Assuming two classes: valid and invalid
# model.load_state_dict(torch.load('./dni_image_validation_model.pth', map_location=device))
model.load_state_dict(torch.load('./dni_image_validation_modelv3.pth', map_location=device))
model = model.to(device)
model.eval() # Set the model to evaluation mode
# Define the same image transformations used during training
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# Function to load and process the image
def process_image(image_path):
image = Image.open(image_path)
image = transform(image).unsqueeze(0) # Add batch dimension
return image
# Function to predict the class of an image
def predict_image(image_path):
image = process_image(image_path).to(device)
# Forward pass through the model
with torch.no_grad():
outputs = model(image)
_, predicted = torch.max(outputs, 1)
# Prediction output
classes = ['invalid', 'valid_back', 'valid_front']
prediction = classes[predicted.item()]
print(f'Prediction for {os.path.basename(image_path)}: {prediction}')
# Test the model with a new image
if __name__ == '__main__':
# Path to the test image (Ensure you provide the correct image file name)
test_image_path = './data_dir/tests/test01.jpeg' # Replace with your actual test image file
if os.path.exists(test_image_path):
predict_image(test_image_path)
else:
print(f'Image not found: {test_image_path}')