File size: 2,028 Bytes
4479560 | 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 | 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}')
|