forked from codecat0/CV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
predict.py
76 lines (61 loc) · 2.32 KB
/
predict.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# !/usr/bin/env python
# -*-coding:utf-8 -*-
"""
# File : predict.py
# Author :CodeCat
# version :python 3.7
# Software :Pycharm
"""
import os
import json
import argparse
import torch
from PIL import Image
from torchvision import transforms
import matplotlib.pyplot as plt
from models.base_model import BaseModel
def main(args):
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
data_transform = transforms.Compose(
[
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
]
)
img_path = args.img_path
assert os.path.exists(img_path), f"file {img_path} dose not exist."
img = Image.open(img_path)
plt.imshow(img)
img = data_transform(img)
# [C, H, W] -> [1, C, H, W]
img = torch.unsqueeze(img, dim=0)
json_path = './class_indices.json'
assert os.path.exists(json_path), f"file {json_path} does not exist."
json_file = open(json_path, 'r')
class_indict = json.load(json_file)
model = BaseModel(name=args.model_name, num_classes=args.num_classes).to(device)
model.load_state_dict(torch.load(args.model_weight_path, map_location=device))
model.eval()
with torch.no_grad():
output = torch.squeeze(model(img.to(device))).cpu()
predict = torch.softmax(output, dim=0)
predict_cla = torch.argmax(predict).numpy()
print_res = "real: {} predict: {} prob: {:.3f}".format(args.real_label, class_indict[str(predict_cla)],
predict[predict_cla].numpy())
plt.title(print_res)
plt.xticks([])
plt.yticks([])
print(print_res)
plt.savefig('./data/predict.jpg', bbox_inches='tight', dpi=600, pad_inches=0.0)
plt.show()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--img_path', type=str, default='./data/tulip.jpg')
parser.add_argument('--real_label', type=str, default='tulip')
parser.add_argument('--model_name', type=str, default='resnet')
parser.add_argument('--num_classes', type=int, default=5)
parser.add_argument('--model_weight_path', type=str, default='./weights/resnet34.pth')
args = parser.parse_args()
main(args)