-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathtest.py
54 lines (46 loc) · 1.49 KB
/
test.py
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
import numpy as np
import sys, random
import torch
from torchvision import models, transforms
from PIL import Image
from pathlib import Path
import matplotlib.pyplot as plt
# Paths for image directory and model
IMDIR=sys.argv[1])
MODEL='models/resnet18.pth'
# Load the model for testing
model = torch.load(MODEL)
model.eval()
# Class labels for prediction
class_names=['apple','atm card','cat','banana','bangle','battery','bottle','broom','bulb','calender','camera']
# Retreive 9 random images from directory
files=Path(IMDIR).resolve().glob('*.*')
images=random.sample(list(files), 9)
# Configure plots
fig = plt.figure(figsize=(9,9))
rows,cols = 3,3
# Preprocessing transformations
preprocess=transforms.Compose([
transforms.Resize(size=256),
transforms.CenterCrop(size=224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
# Enable gpu mode, if cuda available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# Perform prediction and plot results
with torch.no_grad():
for num,img in enumerate(images):
img=Image.open(img).convert('RGB')
inputs=preprocess(img).unsqueeze(0).to(device)
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
label=class_names[preds]
plt.subplot(rows,cols,num+1)
plt.title("Pred: "+label)
plt.axis('off')
plt.imshow(img)
'''
Sample run: python test.py test
'''