-
Notifications
You must be signed in to change notification settings - Fork 1
/
inference.py
55 lines (44 loc) · 1.26 KB
/
inference.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
import io
import json
import torch
import numpy as np
from PIL import Image
from meta_bilinear import ResNet
from torchvision import transforms
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = ResNet()
model.load_state_dict(torch.load('models/thanosnet.pth',
map_location=device))
model.eval()
labels_dict = {
0: 'Can',
1: 'Landfill',
2: 'Paper',
3: 'Plastic',
4: 'Tetrapak'
}
metadata = json.load(open('data/metadata.json'))
def transform_image(image):
inference_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406],
[0.229, 0.224, 0.225])
])
image = Image.open(image).convert('RGB')
return inference_transform(image).unsqueeze(0)
def predict_image(image: str, location: str) -> str:
if location not in metadata.keys():
meta = metadata.get('default')
else:
meta = metadata.get(location)
# Load metadata
meta_ = torch.tensor(meta).unsqueeze(0)
meta_ = meta_.to(device)
# Load and normalize image
tensor = transform_image(image)
input_img = tensor.to(device)
output = model.forward(input_img, meta_)
index = output.data.cpu().numpy().argmax()
return labels_dict[index]