-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinference.py
More file actions
32 lines (27 loc) · 899 Bytes
/
inference.py
File metadata and controls
32 lines (27 loc) · 899 Bytes
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
import torch
import torchvision.transforms as T
from PIL import Image
def predict_image(model, image_path):
"""
Predict the class of a sample image.
Args:
model: The trained model.
image_path (str): Path to the image to predict.
Returns:
int: Predicted class label.
"""
transform = T.Compose([
T.Resize((256, 256)),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
image = Image.open(image_path).convert("RGB")
# Apply the transformations and add a batch dimension
image = transform(image).unsqueeze(0)
device = next(model.parameters()).device
image = image.to(device)
model.eval() # Set the model to evaluation mode
with torch.no_grad():
outputs = model(image)
_, predicted = torch.max(outputs, 1)
return predicted.item()